Wikia

Vim Tips Wiki

Toggling yes-no

Talk0
1,612pages on
this wiki
Revision as of 08:51, March 28, 2012 by JohnBot (Talk | contribs)

Tip 1033 Printable Monobook Previous Next

created 2005 · complexity intermediate · author Bertram Scharpf · version 6.0


When editing config files, you may need to frequently convert between yes and no settings.

With the following in your vimrc, you can press gy to toggle between the words shown in the script.

function s:ToggleYesNo()
  let w=expand("<cword>")
  if     w=="yes"    | let w="no"
  elseif w=="no"     | let w="yes"
  elseif w=="on"     | let w="off"
  elseif w=="off"    | let w="on"
  elseif w=="manual" | let w="auto"
  elseif w=="auto"   | let w="manual"
  else               | let w=""
  endif
  if w!=""
    exec "normal! \"_ciw\<C-R>=w\<CR>\<Esc>b"
  endif
endfunc
nnoremap gy :call <SID>ToggleYesNo()<CR>

This could be supplemented with:

  else
    let n=strpart(w,0,2)
    if n=="no"
      let w=strpart(w,2)
    else
      let w="no".w
    endif
  endif

Comments

Use

exec "normal! m`\"_ciw\<C-R>=w\<CR>\<Esc>``"

to preserve cursor position.


The function will print

:call <SNR>#_ToggleYesNo()

if you press gy on a non-listed word.

Use

nnoremap <silent> gy :call <SID>ToggleYesNo()<CR>

to prevent this behavior.

Around Wikia's network

Random Wiki