如何在Vim中为命令创建别名? [英] How to create an alias for a command in Vim?

查看:206
本文介绍了如何在Vim中为命令创建别名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编程时,Vim是我首选的文本编辑器,因此,我总是遇到一个特别烦人的问题。

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 continue on to some other miscellaneous task, I do the typical

:w

但是,我总是(似乎超过50%的时间)设法将:w 大写。自然,Vim向我大喊,因为 W 是无效的命令:

However, I always — what seems to be like more than 50% of the time — manage to capitalize that :w. Naturally, Vim yells at me because W is an invalid command:

E492: Not an editor command: W

我的问题是,如何在Vim中使用别名冒号命令。特别是,您能举例说明如何将 W 别名为 w

My question is how can one alias colon-commands in Vim. Particularly, could you exemplify how to alias W to w.

I我知道将键映射到某些命令的过程,但这不是我想要的。

I am aware of the process to map keys to certain commands, but that is not what I’m looking for.

推荐答案

要保持不变,请尝试使用

To leave completion untouched, try using

cnoreabbrev W w

它将在命令行中将 W 替换为 w ,但前提是它既不带字字符也不带字字符,因此:W< CR> 将替换为:w< CR> ,但:Write 不会。 (请注意,这会影响所有匹配的命令,包括您可能不会想到的命令。例如,命令:saveas WZ 将替换为: saveas w Z ,所以要小心。)

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.)

这是我写它的方式 now

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

作为功能:

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

这将检查命令类型是否为并且命令为 W ,因此它比 cnoreabbrev W w 更安全。

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

这篇关于如何在Vim中为命令创建别名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆