vimcode-formattingastyle

Vim code formating with astyle (formatprg in vimrc)


I'm trying to use astyle as my code formatter in Vim. However, I can't seem to find how to tell vim which options to use for astyle.

The following is in my vimrc:

autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\

If given no options in command line mode, astyle will try to find an options file named .astyle. However this does not seem to work here. (Ie: when I format in vim: gqG the result is totaly different than if I had called astyle from the command line !) This is my .astyle options file:

 --style=allman
 --mode=c
 --attach-classes              # -xc
 --attach-closing-while        # -xV
 --indent-classes              # -C
 --keep-one-line-blocks        # -O
 --keep-one-line-statements    # -o
 --align-pointer=name          # -k3                                

So I tried to simply specify the options in my vimrc like in this answer:

autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ --style=allman --mode=c -xc -xV -C -O -o -k3

Saved, sourced, reloaded vim entierly: no change. The options seem to not take effect. When I format with gggqG the result is still not what my options ask for... Can anyone see why this is not working ?

(Note: I want to be able to format using gq and I don't mind reformatting the whole file entierly each time, unlike in this question)

EDIT: After a few stupid mistakes I've escaped all the spaces as suggested in @romainl comment. However there seems to be an error comming from vim which I cannot interpret:

/bin/bash: -c: line 1: syntax error: unexpected end of file

shell returned 1

E485: Can't read file /tmp/vHXZmnp/3

Solution

  • Since no one is answering, I'll share what I managed to come up with. Following the advice given in the comments I escaped all the spaces in the sequence of options passed to astyle. However, this leads to bash trying to interpret the options, failing and kindly telling us so: see question edit.

    The solution that seems to work is to create a system wide astyle options file and pass the path to that using command line arguments instead of giving it the options directly. (This can probably also be done with a project options file but requires having an options file at the root directory of every project)

    Taking my options file .astylerc in my home directory this gives:

    autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ --options="/home/myusername/.astylerc"\
    

    Note that a relative path did not work, but it is possible to write the path to the options file using a 'pseudo relative' path using the $HOME environment variable as mentioned in the astyle documentation