How to create an alias for a command in Vim?

后端 未结 7 2054
梦毁少年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 03:11

    The best solution involves writing a custom function for handling abbreviations that only take place in the beginning of the command bar.

    For this, add the following your vimrc file or anywhere else.

    " cabs - less stupidity                                                      {{{
    fu! Single_quote(str)
      return "'" . substitute(copy(a:str), "'", "''", 'g') . "'"
    endfu
    fu! Cabbrev(key, value)
      exe printf('cabbrev <expr> %s (getcmdtype() == ":" && getcmdpos() <= %d) ? %s : %s',
        \ a:key, 1+len(a:key), Single_quote(a:value), Single_quote(a:key))
    endfu
    "}}}
    

     

    " use this custom function for cabbrevations. This makes sure that they only
    " apply in the beginning of a command. Else we might end up with stuff like
    "   :%s/\vfoo/\v/\vbar/
    " if we happen to move backwards in the pattern.
    
    " For example:
    call Cabbrev('W', 'w')
    

    A few useful abbreviations from the source material where I found this stuff:

    call Cabbrev('/',   '/\v')
    call Cabbrev('?',   '?\v')
    
    call Cabbrev('s/',  's/\v')
    call Cabbrev('%s/', '%s/\v')
    
    call Cabbrev('s#',  's#\v')
    call Cabbrev('%s#', '%s#\v')
    
    call Cabbrev('s@',  's@\v')
    call Cabbrev('%s@', '%s@\v')
    
    call Cabbrev('s!',  's!\v')
    call Cabbrev('%s!', '%s!\v')
    
    call Cabbrev('s%',  's%\v')
    call Cabbrev('%s%', '%s%\v')
    
    call Cabbrev("'<,'>s/", "'<,'>s/\v")
    call Cabbrev("'<,'>s#", "'<,'>s#\v")
    call Cabbrev("'<,'>s@", "'<,'>s@\v")
    call Cabbrev("'<,'>s!", "'<,'>s!\v")
    
    0 讨论(0)
提交回复
热议问题