Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to wrap struct initializer in clang-format?

Tags:

c

clang-format

Take this example before clang-format runs:

struct ApplicationState app_state = {
    .signal = {
        .use_crash_handler = true,
        .use_abort_handler = true,
    },
    .exit_code_on_error = {
        .python = 0,
    }
};

After running, clang-format applies as follows:

struct ApplicationState app_state = {.signal =
                                             {
                                                     .use_crash_handler = true,
                                                     .use_abort_handler = true,
                                             },
                                     .exit_code_on_error = {
                                             .python = 0,
                                     }};

Is there a way to add a newline after the brace, before the struct member so it's more like the first example and not like the second?

like image 245
ideasman42 Avatar asked Nov 21 '17 09:11

ideasman42


2 Answers

Currently clang-format doesn't have a useful way of controlling this (as of version 14.0).

While BreakBeforeBinaryOperators: All does force wrapping (see @eric-backus' s answer), it impacts formatting in many other places too, unrelated to struct declaration.

You can however, workaround this simply by using a trailing comma.


Before:

struct ApplicationState app_state = {.signal =
                                             {
                                                     .use_crash_handler = true,
                                                     .use_abort_handler = true,
                                             },
                                     .exit_code_on_error = {
                                             .python = 0,
                                     }};

After:


struct ApplicationState app_state = {
    .signal = {
        .use_crash_handler = true,
        .use_abort_handler = true,
    },
    .exit_code_on_error = {
        .python = 0,
    },
};
/*   ^ notice trailing comma on the second last line! */
like image 103
ideasman42 Avatar answered Oct 23 '22 03:10

ideasman42


The primary thing you need is:

BreakBeforeBinaryOperators: All

You could instead set the overall style to WebKit, because that sets BreakBeforeBinaryOperators to All.

Clearly, clang-format must see the . as a binary operator. I'm not sure if it should, but that's what it seems to do.


I tested this with clang-format 6.0.0. Presumably newer versions would work the same, but I haven't tested so I can't be sure.

like image 1
Eric Backus Avatar answered Oct 23 '22 05:10

Eric Backus