Juniper Belmont
Juniper Belmont

Reputation: 3574

How can I make the tilde operator change ‘==’ to ‘!=’ in Vim?

I would like the normal-mode command tilde ~, in addition to changing the case of letters, to also be able to change the text == to != and != to ==.

I find that I do this quite often and I'd like a shortcut that still uses the tilde.

Upvotes: 4

Views: 1567

Answers (3)

ib.
ib.

Reputation: 28964

Let me propose an alternative implementation of this extended ~ command:

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

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

Upvotes: 2

Ingo Karkat
Ingo Karkat

Reputation: 172648

Toggling between two alternatives (like == and !=) is only a special case of toggling between multiple options. I'd advise against overloading the binary ~ command and instead use <C-A> / <C-X>. The SwapIt - Extensible keyword swapper plugin offers this and actually has a default option to toggle ==, !=, <=, etc.

Upvotes: 3

Juniper Belmont
Juniper Belmont

Reputation: 3574

This is fairly simple to do in vimscript. Add the following to your .vimrc or source this code from a different file.

" ----------------------
"  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>

Upvotes: 5

Related Questions