Search code examples
c++clangclang-format

Clang-format binpack OnePerLine for return arguments and variables


I have the following code:


    return first_long_function_name(argument) ||
           second_long_function_name(argument) || third_long_function_name(argument);

I want it to behave like BinPackParameters=false and if it can't fit in one line it should have each clause in a separate line. Is there some way to do this?

    return first_long_function_name(argument) ||
           second_long_function_name(argument) || 
           third_long_function_name(argument);

My .clang-format file is as follows:

# See https://clang.llvm.org/docs/ClangFormatStyleOptions.html for all options

Language: Cpp

# Spaces
ColumnLimit: 120
IndentWidth: 4
AccessModifierOffset: -4
IndentAccessModifiers: false
NamespaceIndentation: None
IndentCaseLabels: true
AlwaysBreakTemplateDeclarations: Yes
SpaceAfterTemplateKeyword: false

# Function calls
AlignAfterOpenBracket: Align
BinPackParameters: false
BinPackArguments: false
AllowAllArgumentsOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false

# Curly Braces
BreakBeforeBraces: Custom
BraceWrapping:
    AfterFunction: true
    AfterControlStatement: Never
InsertBraces: true

# Variables
PointerAlignment: Right

# Short lines
AllowShortEnumsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: false
AllowShortBlocksOnASingleLine: Empty

# Comments
ReflowComments: false

# Includes
SortIncludes: Never

ForEachMacros: ['LOOP', 'LOOP_FROM', 'LOOP_TYPE', 'LOOP_FROM_TYPE']

PenaltyReturnTypeOnItsOwnLine: 1000

Solution

  • Yes, starting with clang-format 20 this is possible using the BreakBinaryOperations option (also compare pull request). You can set it to OnePerLine or RespectPrecedence (in the latter case, e.g. operations containing && and || end up with the && operations still on one line). Live example on godbolt for OnePerLine.

    Note that llvm version 20 has not yet been released. But depending on your system, you might find nightly builds for it. Also, I personally found that building from source was quite easy on Windows if you have Visual Studio installed, so you might give it a try.