c++code-formattingpretty-print

Remove spaces and add newlines with astyle on c++ code


I inherited a massive amount of code formatted as follows:

void <whitespace> Foo::bar <whitespace> ( ) <whitespace> // short documentation
{
  // code
}
void Foo::bar()
{
  // code
}

with no empty line at the end of files and sometimes missing newline between functions. I've successfully used the following options with astyle to remove most style errors, but I can't find any reference or documentation on how to fix these issues.

--style=ansi -t3 -N -j -k1 -z2 -n -r -H -U -p -q -w -Y -L -S

I've used a simple python script in the past to make sure that there are a newline at the end, and I guess that I could use something like it again together with regex to remove whitespace and add newlines, but since I use astyle now it would be great if it could do it, so... suggestions?


Solution

  • I don't know what platform you're using, but if you're on any type of NIX-based platform, you have access to a lot of text-editing tools such as sed, meaning you don't have to roll your own code to do it.

    I'm not great with regex, but the general syntax for sed search and replace on the command line is this:

    sed -i -e 's/expr1/expr2/g' filename
    

    This will replace "expr1" with "expr2". It works with spaces and regex, so you can condense all multiple spaces into one space (or none, if you don't type anything for expr2).

    sed may have what you need to deal with your newlines, but unfortunately, I'm not that skilled with its language.

    Good luck, though.