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

查看:54
本文介绍了如何在 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 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,但 :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.)

这是我将如何编写现在:

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天全站免登陆