Wiki: Auto Change


Challenge

A request was made in #vim for there to be an automatic version of change. This would be a special version of change that would "snap" back to normal mode after a word or line is typed.

For example when using cw and c$, set it so that as soon as soon as enter (or space for cw) is pressed it goes into normal mode?


Solutions

Houl? how damn old is this challenge??

nno <script> cw <sid>spw_cw
nno <script> c$ <sid>crd_c$

nno <silent> <sid>spw_ :call <sid>Stopkey("space")<cr>
nno <silent> <sid>crd_ :call <sid>Stopkey("cr")<cr>

fun! s:Stopkey(key)
    exe "ino <silent> <sid>unmap <esc>:call <sid>Unmap('".a:key."')<cr>"
    exe "ino <script> <".a:key."> <sid>unmap"
    ino <script> <esc> <sid>unmap
    ino <script> <c-o> <sid>unmap
    ino <script> <c-c> <sid>unmap
    " not complete: Ctrl-\_Ctrl-N, Ctrl-R="\<esc>"<cr>, ...
endfun

fun! s:Unmap(key)
    exe "sil! iunmap <".a:key.">"
    sil! iunmap <esc>
    sil! iunmap <c-o>
    sil! iunmap <c-c>
endfun

" Notes:
" * <script> and <sid> need a surrounding script file
" * no switching (enable/disable AutoChange)
" * remaps some other keys that stop Insert mode, to not leave i_Space resp.
"   i_Enter mapped (and do unwanted things later)
" * i_Ctrl-O works like i_Esc
" * not a general solution: key must be a <...>-key, one key only

Copyright © 2007 RobertMelton.com