Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 483
Juniper Belmont Avatar asked Feb 17 '23 15:02

Juniper Belmont


1 Answers

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>
like image 195
Juniper Belmont Avatar answered Feb 20 '23 05:02

Juniper Belmont