Sea*_*ean 145 vim alias command
Vim
我编程时是我首选的文本编辑器,因此我总是遇到一个特别恼人的问题.
通常,当我快速需要保存缓冲区并继续执行其他一些其他任务时,我会做典型的
:w
Run Code Online (Sandbox Code Playgroud)
然而,我 - 似乎超过50%的时间 - 总是设法利用它:w
.当然,vim对我大吼大叫,因为这W
是一个无效的命令
E492: Not an editor command: W
Run Code Online (Sandbox Code Playgroud)
我的问题是如何在vim中为冒号命名.尤其是,你能举例说明如何别名W
来w
.
我知道将键映射到某些命令的过程.不幸的是,这不是我想要的.
ZyX*_*ZyX 121
要完成保持不变,请尝试使用
cnoreabbrev W w
Run Code Online (Sandbox Code Playgroud)
,它将W
在命令行中替换w
,但只有当它既没有被跟随也没有前面的单词字符时,所以:W<CR>
将替换为:w<CR>
,但:Write
不会.(请注意,这会影响任何匹配的命令,包括您可能不期望的命令,例如命令:saveas W Z
将被替换:saveas w Z
,因此请小心.)
这是我怎么会写现在:
cnoreabbrev <expr> W ((getcmdtype() is# ':' && getcmdline() is# 'W')?('w'):('W'))
Run Code Online (Sandbox Code Playgroud)
作为一个功能:
fun! SetupCommandAlias(from, to)
exec 'cnoreabbrev <expr> '.a:from
\ .' ((getcmdtype() is# ":" && getcmdline() is# "'.a:from.'")'
\ .'? ("'.a:to.'") : ("'.a:from.'"))'
endfun
call SetupCommandAlias("W","w")
Run Code Online (Sandbox Code Playgroud)
这将检查命令类型是否:
为命令W
,因此它比仅更安全cnoreabbrev W w
.
Sea*_*ean 93
通过补充搜索,我发现有人问了几乎和我一样的问题.
:command <AliasName> <string of command to be aliased>
Run Code Online (Sandbox Code Playgroud)
会做的.
请注意,正如Richo指出的那样,用户命令必须以大写字母开头.
fen*_*ent 19
我发现将;
键映射到:
更好的解决方案,并且可以使您更有效地键入其他命令.
nnoremap ; :
vnoremap ; :
Run Code Online (Sandbox Code Playgroud)
最佳解决方案涉及编写自定义函数来处理仅在命令栏开头发生的缩写.
为此,请添加以下vimrc文件或其他任何位置.
" 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
"}}}
Run Code Online (Sandbox Code Playgroud)
" 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')
Run Code Online (Sandbox Code Playgroud)
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")
Run Code Online (Sandbox Code Playgroud)
也许你想将你的一个功能键(F1..F12)映射到:w?然后把它放到你的.vimrc中:
noremap <f1> :w<return>
inoremap <f1> <c-o>:w<return>
Run Code Online (Sandbox Code Playgroud)
(插入模式下的ctrl-o暂时切换到正常模式).
小智 6
假设您要在gvim中为tabnew命令添加别名.您只需在.vimrc文件中键入以下命令(如果不在主文件夹中而不是创建一个)
cabbrev t tabnew
Run Code Online (Sandbox Code Playgroud)
小智 5
最安全和最简单的是一个插件,比如cmdalias.vim或者我最近更新的vim-alias,它考虑到了
:sil(ent)(!)
or :redi(r)
,'<,'>
当前的视觉选择,