如何将两个 Vim 命令合并为一个(命令不是键绑定)

How to combine two Vim commands into one (command not keybinding)

我发现很少有 Stack Overflow 问题谈到这个,但它们都只与 :nmap:noremap 命令有关。 我想要一个命令,而不仅仅是一个键绑定。有什么办法可以做到这一点吗?

用例:

当我 运行 :make 时,我不会自动保存。所以我想合并 :make:w。我想创建一个命令 :Compile/:C:Wmake 来实现这个。

经过反复试验,我找到了解决方案。

我的用例的解决方案

command C w <bar> silent make <bar> redraw!

这是为了使用 make 进行编译,并且仅当存在非零输出时才打印输出。

一般解决方案

command COMMAND_NAME COMMAND_TO_RUN

其中 COMMAND_TO_RUN 可以通过以下构造使用多个命令来构造。

COMMAND_1_THAN_2 = COMMAND_1 <bar> COMMAND_2

您可以多次使用它,它与 shell 中的管道非常相似。

关于通过 | 连接 Ex 命令的一般信息可以在 :help cmdline-lines 找到。

您可以将其应用于交互式命令、映射以及自定义命令。

请注意,您只需要在映射中使用特殊的<bar>(以避免过早地结束映射定义并立即执行余数,初学者常犯的错误::nnoremap <F1> :write | echo "This causes an error during Vim startup!"<CR>)。对于自定义命令,您可以只写 |,但请记住哪些命令自己将其视为它们的参数。

:help line-continuation will help with overly long command definitions. Moving multiple commands into a separate :help :function 也有帮助(但请注意,这会微妙地改变错误处理)。

参数

如果要传递自定义命令行参数,可以将 -nargs=* 添加到 :command 定义中,然后通过 <args> 在右侧指定插入点.例如,要允许对您的 :write 命令执行命令,您可以使用

:command -nargs=* C w <args> | silent make | redraw!

您可以将命令与 | 结合使用,请参阅 :bar 的帮助:

command! C update | silent make | redraw!

但是,有一种更简洁的方法可以实现您想要的效果。 只需启用 'autowrite' 选项即可自动写入 :make:

之前修改的文件
                                 'autowrite' 'aw' 'noautowrite' 'noaw'
'autowrite' 'aw'        boolean (default off)
                        global
        Write the contents of the file, if it has been modified, on each
        :next, :rewind, :last, :first, :previous, :stop, :suspend, :tag, :!,
        :make, CTRL-] and CTRL-^ command; and when a :buffer, CTRL-O, CTRL-I,
        '{A-Z0-9}, or `{A-Z0-9} command takes one to another file.
        Note that for some commands the 'autowrite' option is not used, see
        'autowriteall' for that.

此选项已在 :make 的帮助中提及。