6

I'm using the linux kernel .clang-format as a reference, but this part is bothering me.

How can I get clang-format to format this code

const struct my_struct hello = {.id = 0,
                                .modsmin = 10,
                                .modsmax = 20,
                                .strengthmin = 0,
                                .strengthmax = 100,
                                .color = COLOR_FOREGROUND };

to this

const struct my_struct hello = {
    .id = 0,
    .modsmin = 10,
    .modsmax = 20,
    .strengthmin = 0,
    .strengthmax = 100,
    .color = COLOR_FOREGROUND
};
aganm
  • 1,245
  • 1
  • 11
  • 30

2 Answers2

13

Looking at the documentation, there don't seem to be any clang-format style options which will do what you want.

But, you can use the "comma-after-last-item" trick. Put a comma after the last designated initializer, before the final closing brace. I believe this is still valid C code. Then clang-format will put each initializer on a separate line, and this will move the indentation back to what you're looking for. So the output would look like this:

const struct my_struct hello = {
    .id = 0,
    .modsmin = 10,
    .modsmax = 20,
    .strengthmin = 0,
    .strengthmax = 100,
    .color = COLOR_FOREGROUND,
};

This behavior is not documented anywhere (as far as I know), so I suppose it could be changed in the future. But this behavior has been there for many years and many versions of clang-format so I think it is reasonable to rely on it.

Eric Backus
  • 1,614
  • 1
  • 12
  • 29
1

I solved it by adding the following to my .clang-format:

Cpp11BracedListStyle: false

In the documentation it's said that if this parameter is true, there is "No line break before the closing brace".

If this option must be set to true, then other tricks, like putting , or // before closing brace would still suffice.

Sun of A beach
  • 171
  • 1
  • 10