Vim Tips Wiki
Advertisement
Tip 1285 Printable Monobook Previous Next

created July 17, 2006 · complexity intermediate · author Yakov Lerner · version n/a


Sometimes you want to change the behaviour of a built-in command like :e. Or, you may have a common typo, like using :w1 instead of :w!. If for whatever reason, you want to change, tweak, or extend the behavior of a built-in command, you can't just use command to over-ride it, because user-defined commands must begin with a capital letter.

The closest thing to doing this is to automatically replace the existing command to the desired command whenever you type it, using 'cabbrev'. For example, if you have a custom-made 'E' command that you want to use to over-ride the default 'e' command, you could do the following:

cabbrev e <c-R>=(getcmdtype()==':' && getcmdpos()==1 ? 'E' : 'e')<cr>

The (getcmdtype()==':' && getcmdpos()) part in cabbrev is needed to make sure the replacement happens ONLY in the first column of the command line (i.e. not the search line, which is also affected by cabbrev).

If you do this a lot, it would be useful to to define a function to do it for you. Use this to quickly and easily define lower-case abbreviations for whatever command you want:

function! CommandCabbr( abbreviation, expansion )
  execute 'cabbr ' . a:abbreviation . ' <c-r>=getcmdpos() == 1 && getcmdtype() == ":" ? "' . a:expansion . '" : "' . a:abbreviation . '"<CR>'
endfunction
command! -nargs=+ CommandCabbr call CommandCabbr( <f-args> )
" Use it itself to define a simpler abbreviation for itself.
CommandCabbr ccab CommandCabbr

This not only creates the function, but also provides the (lowercase!) command ccab to define such abbreviations "on the fly".

See also

These are all good candidates for this technique (or use it already):

This is good reference in case this tip causes you problems:

References

Comments


Advertisement