Vim 保存时调用命令

Vim calling command on save

我正在尝试在保存时调用 this 自动格式化插件

这是我的自动命令:

autocmd BufWrite *.css,*.html,*.js,*.py :Autoformat<CR>

当我保存时没有任何反应,如果我手动调用 :Autoformat 然后自动格式化程序运行。

我做错了什么?

根据我的经验,您有时需要将它包围在 augroup

augroup autoFormat
    autocmd BufWrite *.css,*.html,*.js,*.py :Autoformat<CR>
augroup END

我不知道为什么,但它对我有用!从技术上讲,autocmd 应该可以独立工作,但有时却不能。此外,在 GitHub 页面上它说使用 :Autoformat<CR><CR>,也许可以试试。

出于某种原因,我不得不摆脱马车 return 并更改为 BufWritePre(尽管 CR 是主要问题,BufWritePre 只是确保它在写入缓冲区之前而不是之后被更改所以它被保存了):

autocmd BufWritePre *.css,*.html,*.js,*.py :Autoformat

为什么,我不知道?

您已经找到了解决方案 - 解释如下:

<CR> 用于 mappings,它的工作方式类似于记录的键入键序列,因此您需要使用 : 启动命令行模式并以 <CR> 结尾。 autocmd 采用 Ex 命令,因此 <CR> 被视为(无效)参数。您也不需要 :,但这不会造成伤害。

:help BufWrite 所示,这是 BufWritePre 的同义词。

  BufWrite or BufWritePre     Before writing the whole buffer to a file.

所以,这是推荐的形式:

autocmd BufWritePre *.css,*.html,*.js,*.py Autoformat