Search code examples
c++cparsingastyle

Astyle - how to format condition without braces to 1TBS


I have a program which uses Astyle to format the code into 1TBS. So, if I have a code like this

if(condition)
    func(a, b);

it changes to this

if(condition) {
    func(a, b);
}

The problem is, when parameters in the called function are broken into multiple lines, like this:

if(condition)
    func(a, 
         b);

Then Astyle is not able to add braces even if I try to force him with --add-brackets. Is it possible to do it some other way?

My command now looks like this:

astyle --style=1tbs --add-brackets  test.c

Solution

  • This may seem a bit convoluted but if you have a lot of sources and adding braces is an operation that you just need once, the following scheme might work.

    You can stick with astyle but you need uncrustify temporarily as well as a script I wrote called whatstyle.

    In the following steps replace test1.c with your sources and keep a backup of your sources as they will be modified.

    Teach astyle the current style of your sources

    whatstyle.py -f astyle --mode resilient --output astylerc test1.c
    

    Teach uncrustify the current style of your sources

    whatstyle.py -f uncrustify --output uncrustify.cfg test1.c
    

    Tell uncrustify to always add braces to ifs

    ( egrep -v mod_full_brace_if < uncrustify.cfg ; echo "mod_full_brace_if = force" ) \
      > uncrustify_addbrace.cfg
    

    Reformat your sources with as little style changes as possible with uncrustify

    uncrustify --replace -c uncrustify_addbrace.cfg test1.c
    

    The braces have been added now retransform into the original style with astyle.

    ARTISTIC_STYLE_OPTIONS=astylerc astyle test1.c
    

    Now your sources should look almost the same as before except for the added braces although there might be more changes by the back-and-forth style transformation.