7

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

  1. Format the code that I am currently editing (i.e. when gq is pressed).
  2. Format the code when I save the file and then reload the formatted file into current Vim window.

Option 1 is preferable. 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 the E518: Unknown option: ~/misc/uncrustify.cfg error.

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 the save, but I have to manually reload the file into Vim.

ib.
  • 27,830
  • 11
  • 80
  • 100
user1280213
  • 269
  • 3
  • 10

1 Answers1

4

Have you tried escaping whitespaces:

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

UPDATE

uncrustify prints "Parsing: 170 bytes ..." message to 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 operates on lines, so you can select necessary lines in visual mode and execute gq. For example, if you want to reformat whole file execute ggVGgq.

More info at :help gq

galymzhan
  • 5,505
  • 2
  • 29
  • 45
  • That removed the VI error. I also had to add the -l option to specify the language as CPP, since input to uncrustify is from stdin. However, pressing gq in vi does not format the file. If I press it again, then the only the current line is formatted and the following line is added to the file being edited - "Parsing: 57 bytes (57 chars) from stdin as language CPP " . I think what I am missing is how to configure the formatprg command to read the entire file, and secondly prevent output of the above line to the file being edited. – user1280213 Mar 21 '12 at 04:36