Brace on new line only if current line overflows clang format

1.5k Views Asked by At

I've recently decided to include a .clang-format file in a C++ project of mine to make the code more uniform and easy to read. I mostly like the Google defaults, except I'd like to use 4 space indents instead of two.

The problem with this is that it makes certain statements harder to read when the current line overflows the 80 character column limit. For example, in an if statement that overflows:

if (some_condition || some_other_condition ||
    yet_another_condition) {
    // block starts here
}

The alignment of yet_another_condition matches that of the start of the if-block, which makes it hard to read without some kind of a break. Ideally, what I would want to happen in this situation is something like this:

if (some_condition || some_other_condition ||
    yet_another_condition)
{
    // block starts here
}

However, I only want the opening brace on a new line when the current line overflows into the next, like in the above example. In all other cases I want the opening brace on the same line (that goes for if/for/while/switch etc. statements as well as functions).

Is it possible to specify this behavior in my .clang-format file while keeping the rest of the Google defaults intact?

2

There are 2 best solutions below

1
On

The clang-format tool allows to specify custom brace wrapping with BraceWrapping: Custom, but it is not flexible enough to be aware of the context you require.

The alternative solution to improve readability is to use continuation indent greater than 4, e.g. ContinuationIndentWidth: 8.

0
On

It can be done with AfterControlStatement set to MultiLine

You also need to set BreakBeforeBraces to Custom.

Example:

BreakBeforeBraces: Custom
BraceWrapping:
      AfterControlStatement: MultiLine