Vim autocmd (save file, format startup code, reload file)

I want to integrate Uncrustify source code formatter with Vim. Any of the following two options will suffice.

  • Format the code that I am currently editing (i.e., by pressing gq ).
  • Format the code when saving the file, and then reload the formatted file into the current Vim window.

Option 1 is preferred. I tried

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

i.e. I call Uncrustify with command line options. This does not work. Vi gives error E518: Unknown option: ~/misc/uncrustify.cfg .

For option 2, I tried the following in the vimrc file

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

The file is formatted after saving, but I need to manually reload the file in Vim.

+6
source share
1 answer

You tried to avoid spaces:

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

UPDATE

uncrustify displays the message "Parsing: 170 bytes ..." on stderr, so we need to redirect it to /dev/null :

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

gq works with lines, so you can select the desired lines in visual mode and execute gq . For example, if you want to reformat the entire file, run ggVGgq .

Further information at :help gq

+4
source

Source: https://habr.com/ru/post/911177/


All Articles