如何在Vim中使用波浪符号将“==”替换为“!=”?

4
我希望正常模式下的波浪符号~,除了更改字母大小写外,还能够更改文本 == != != ==
我发现我经常这样做,我想要一个仍然使用波浪符号的快捷方式。

8
@Kent,在 Stack Overflow 上鼓励用户回答自己的问题(http://blog.stackoverflow.com/2011/07/its-ok-to-ask-and-answer-your-own-questions/)。对于这个问题,虽然它并没有比使用“r”更短,但我觉得有点奇怪。 - cms_mgr
@cms_mgr 当我从 != 切换到 == 时,我几乎总是会不小心按到 ~ 而不是 r!这真的让我很烦恼。我想在这里记录下我所做的事情,因为 Stack Overflow 对于像这样的小例子非常有用。 - Juniper Belmont
1
就我所知,这个问题从一开始就很令人困惑,因为你的措辞有误。你谈论的是“正常模式命令”,而不是运算符,但你又在问如何更改“==”等运算符。;-) - cptstubing06
3个回答

5
这在vimscript中非常简单。 将以下代码添加到您的.vimrc或从其他文件中source此代码即可。
" ----------------------
"  Tilde switches ==/!=
" ----------------------
function! TildeSwitch()
  " Gets the pair of characters under the cursor, before and behind.
  let cur_pair = getline(".")[col(".") - 2 : col(".") - 1]
  let next_pair = getline(".")[col(".") - 1 : col(".")]

  if cur_pair == "=="
    normal! "_ch!
    normal! l
  elseif next_pair == "=="
    normal! r!
  elseif cur_pair == "!="
    normal! "_ch=
    normal! l
  elseif next_pair == "!="
    normal! r=
  else
    " If == and != are not found, simply use the regular tilde.
    normal! ~
  endif
endfunction

nnoremap <silent> ~ :silent call TildeSwitch()<cr>

"_ch!之前是什么意思?当进行更改时,寄存器不是自动填充的吗? - 244an
“_”是黑洞寄存器(_)。我在那里使用该寄存器,以便“最后使用”的引号寄存器不会改变。http://vimdoc.sourceforge.net/htmldoc/change.html#quote_ - Juniper Belmont

3
在切换两个选项(例如==!=)之间进行切换只是切换多个选项的特例。我建议不要重载二进制~命令,而是使用<C-A>/<C-X>SwapIt-可扩展关键字交换插件提供此功能,并实际上有一个默认选项可以切换==!=<=等等。

2

让我提出这个扩展~命令的另一种实现方式:

nnoremap <silent> ~ :call SwitchNeq()<cr>~

function! SwitchNeq()
    let [s, c] = [@/, getpos('.')]
    s/[!=]\ze\%#=\|\%#[!=]\ze=/\='!='[submatch(0)=='!']/e
    let @/ = s
    call setpos('.', c)
endfunction

4
你能否添加一些评论来解释它是如何工作的?或者只是解释一下思路? - Juniper Belmont

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接