How to create an alias for a command in Vim?

后端 未结 7 2053
梦毁少年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条回答
  • 2020-11-28 02:46

    Safest and easiest is a plugin such as cmdalias.vim or my recent update vim-alias of it that take into account

    • preceding blanks or modifiers such as :sil(ent)(!) or :redi(r),
    • range modifiers such as '<,'> for the current visual selection,
    • escape special characters such as quotes, and
    • check if the chosen alias is a valid command line abbreviation.
    0 讨论(0)
  • 2020-11-28 02:59

    I find that mapping the ; key to : would be a better solution, and would make you more productive for typing other commands.

    nnoremap ; :
    vnoremap ; :
    
    0 讨论(0)
  • 2020-11-28 03:02

    Maybe you would like to map one of your function keys (F1..F12) to :w ? Then put this into your .vimrc:

    noremap  <f1> :w<return>
    inoremap <f1> <c-o>:w<return>
    

    (ctrl-o in insert mode switches temporarily to normal mode).

    0 讨论(0)
  • 2020-11-28 03:05

    Suppose you want to add alias for tabnew command in gvim. you can simply type the following command in your .vimrc file (if not in home folder than create one)

    cabbrev t tabnew
    
    0 讨论(0)
  • 2020-11-28 03:09

    With supplementary searching, I've found that someone asked nearly the same question as I.

    :command <AliasName> <string of command to be aliased>
    

    will do the trick.

    Please be aware that, as Richo points out, the user command must begin with a capital letter.

    0 讨论(0)
  • 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<CR> will be replaced with :w<CR>, 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 <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))
    

    As a function:

    fun! SetupCommandAlias(from, to)
      exec 'cnoreabbrev <expr> '.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.

    0 讨论(0)
提交回复
热议问题