How to create an alias for a command in Vim?

后端 未结 7 2140
梦毁少年i
梦毁少年i 2020-11-28 02:32

Vim is my preferred text editor when I program, and thus I always run into a particularly annoying issue.

Frequently, when I quickly need to save the buffer and conti

7条回答
  •  萌比男神i
    2020-11-28 03:11

    To leave completion untouched, try using

    cnoreabbrev W w
    

    It will replace W in command line with w, but only if it is neither followed nor preceded by word character, so :W will be replaced with :w, but :Write won’t. (Note that this affects any commands that match, including ones that you might not expect. For example, the command :saveas W Z will be replaced by :saveas w Z, so be careful with this.)

    Update

    Here is how I would write it now:

    cnoreabbrev  W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))
    

    As a function:

    fun! SetupCommandAlias(from, to)
      exec 'cnoreabbrev  '.a:from
            \ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
            \ .'? ("'.a:to.'") : ("'.a:from.'"))'
    endfun
    call SetupCommandAlias("W","w")
    

    This checks that the command type is : and the command is W, so it’s safer than just cnoreabbrev W w.

提交回复
热议问题