如何配置clang-format,避免后续行缩进受上一行符号影响?
问题与解决方案
需求
希望变量、函数等名称的长度绝不影响后续行的缩进(或尽可能减少影响)。目前已设置AlignAfterOpenBracket: AlwaysBreak,纯函数调用时所有参数会移至下一行,修改第一行内容不会影响后续行(除非调用能整行容纳),符合预期;但添加二元操作符后,参数会与函数名对齐(叠加ContinuationIndentWidth: 4的缩进),修改第一行的变量名会导致后续行重新缩进,不符合需求。
理想格式示例:
const auto result = SomeVeryLooooooonFunctionName( parameter1, parameter2, parameter3, parameter4, parameter5, parameter6) + 1;
当前配置
--- Language: Cpp BasedOnStyle: Mozilla AlignAfterOpenBracket: AlwaysBreak AlignOperands: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None PenaltyReturnTypeOnItsOwnLine: 0 ColumnLimit: 100 ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true IndentWidth: 2 ...
修改后的配置
在现有配置基础上添加以下选项,即可实现需求:
BreakBeforeBinaryOperators: All IndentWrappedFunctionNames: false
完整配置示例:
--- Language: Cpp BasedOnStyle: Mozilla AlignAfterOpenBracket: AlwaysBreak AlignOperands: false AlwaysBreakAfterDefinitionReturnType: None AlwaysBreakAfterReturnType: None PenaltyReturnTypeOnItsOwnLine: 0 ColumnLimit: 100 ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 Cpp11BracedListStyle: true IndentWidth: 2 BreakBeforeBinaryOperators: All IndentWrappedFunctionNames: false ...
配置说明
BreakBeforeBinaryOperators: All:让二元操作符(如示例中的+)换行到下一行,使函数调用部分独立排版,避免操作符影响参数的缩进规则。IndentWrappedFunctionNames: false:禁止函数名换行时与后续内容对齐,确保函数调用的参数始终从固定缩进位置开始,不受函数名长度变化影响。
内容的提问来源于stack exchange,提问作者sebrockm
相关产品推荐
相关产品推荐

