简体   繁体   English

Vim autocmd(保存文件,运行代码格式化程序,重新加载文件)

[英]Vim autocmd (save file, run code formatter, reload file)

I wish to integrate the source code formatter Uncrustify with Vim. 我希望将源代码格式化程序Uncrustify与Vim集成。 Any of the below two options will suffice. 以下两个选项中的任何一个都足够了。

  1. Format the code that I am currently editing (ie when gq is pressed). 格式化我当前正在编辑的代码(即按下gq时)。
  2. Format the code when I save the file and then reload the formatted file into current Vim window. 保存文件时格式化代码,然后将格式化文件重新加载到当前Vim窗口。

Option 1 is preferable. 选项1是优选的。 I tried 我试过了

set formatprg=uncrustify\ -c ~/misc/uncrustify.cfg --no-backup

ie I call Uncrustify with command line options. 即我用命令行选项调用Uncrustify。 This does not work. 这不起作用。 Vi gives the E518: Unknown option: ~/misc/uncrustify.cfg error. Vi给出了E518: Unknown option: ~/misc/uncrustify.cfg错误。

For option 2, I tried the following in the vimrc file 对于选项2,我在vimrc文件中尝试了以下内容

autocmd bufwritepost *.cpp ! ~/bin/uncrustify -c ~/misc/uncrustify.cfg --no-backup <afile>

The file is formatted after the save, but I have to manually reload the file into Vim. 保存后文件格式化,但我必须手动将文件重新加载到Vim中。

Have you tried escaping whitespaces: 你有没有试过逃避空格:

:set formatprg=uncrustify\\ -c\\ ~/misc/uncrustify.cfg\\ --no-backup

UPDATE UPDATE

uncrustify prints "Parsing: 170 bytes ..." message to stderr so we need to redirect it to /dev/null : uncrustify打印“解析:170字节......”消息给stderr所以我们需要将它重定向到/dev/null

:set formatprg=uncrustify\\ -c\\ ~/misc/uncrustify.cfg\\ -l\\ CPP\\ --no-backup\\ 2>/dev/null

gq operates on lines, so you can select necessary lines in visual mode and execute gq . gq运行,因此您可以在可视模式下选择必要的行并执行gq For example, if you want to reformat whole file execute ggVGgq . 例如,如果要重新格式化整个文件,请执行ggVGgq

More info at :help gq 有关更多信息,请访问:help gq

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM