views:

122

answers:

3

I like spaces between almost all semantic elements in my C code.

Thus I prefer

if ( ( foo = bar ( arg1, arg2, arg3 ) ) ==  NULL ) {
    printf ( "Error 42" );
}

to

if((foo=bar(arg1,arg2,arg3))==NULL){
    printf("Error 42");
}

Is there a C beautifier around (unix platform) that can do this?
It takes a seriously smart beautifier 'cos it has to leave function macros alone.

+2  A: 

You may want to look at GNU Indent. I believe it can do everything you're looking for.

Variable Length Coder
+1  A: 

Gnu Indent can probably do that. Unfortunately, indent has a huge number of options, many of which aren't at all intuitive, and many of them interact in extremely strange ways. I've never (not even once) managed to get it to format code in a way that wasn't uglier coming out than going in. In some cases it was more uniform. In others I suppose it must really have been uniform, but the rules it was following were still strange enough that the result often just looked wierd.

After struggling with indent for a while, I decided that it was easier to write a much simpler program that only supported one format, and just edit the code if I wanted to change the format.

Jerry Coffin
+4  A: 
indent -prs -br -i 4 file

Turns this:

#define f(x) ((x)+(x))

if((foo=bar(arg1,arg2,arg3))==NULL){
    printf("Error 42");
    f(42);
}

Into this:

#define f(x) ((x)+(x))

if ( ( foo = bar ( arg1, arg2, arg3 ) ) == NULL ) {
    printf ( "Error 42" );
    f ( 42 );
}

The -prs option puts spaces around parenthesis, the spaces around operators and after the commas come standard. The -br option enforces your bracing style, and -i 4 uses 4 spaces to indent. Note that the macro definition is not modified but the call to the function-like macro in the code is (presumably what you'd want).

Robert Gamble