如何让ClangFormat达到列宽限制时换行并对齐?
实现指定clang-format格式化效果的配置调整
我使用的是Ubuntu clang-format 14.0.0-1ubuntu1,当前.clang-format配置如下:
--- BasedOnStyle: Google AlignAfterOpenBracket: Align AlignOperands: 'true' AllowAllArgumentsOnNextLine: 'false' AllowAllConstructorInitializersOnNextLine: 'true' AllowShortBlocksOnASingleLine: 'true' BinPackParameters: 'false' BreakBeforeBraces: Attach ColumnLimit: '80' ConstructorInitializerAllOnOneLineOrOnePerLine: 'false' Cpp11BracedListStyle: 'false' IndentWidth: '4' Language: Cpp NamespaceIndentation: All SortIncludes: 'true' Standard: Cpp03 ...
当前格式化后的代码:
static inline VecABf clarke(Vec3f in) { float const sq3 = sqrtf(3.f); return VecABf(in.u - 0.5f * (in.v + in.w), sq3 * 0.5f * (in.v - in.w)) * (2.f / 3.f); }
期望的格式化效果:
static inline VecABf clarke(Vec3f in) { float const sq3 = sqrtf(3.f); return VecABf( in.u - 0.5f * (in.v + in.w), sq3 * 0.5f * (in.v - in.w) ) * (2.f / 3.f); }
要实现这个效果,需要调整两个配置项:
- 将
AllowAllArgumentsOnNextLine从false改为true:允许函数/构造函数的所有参数移到开括号的下一行 - 添加
PenaltyBreakBeforeFirstCallParameter: 0:降低在第一个调用参数前换行的惩罚值,让clang-format优先选择在这里换行,而非在二进制运算符处拆分表达式
修改后的完整配置如下:
--- BasedOnStyle: Google AlignAfterOpenBracket: Align AlignOperands: 'true' AllowAllArgumentsOnNextLine: 'true' AllowAllConstructorInitializersOnNextLine: 'true' AllowShortBlocksOnASingleLine: 'true' BinPackParameters: 'false' BreakBeforeBraces: Attach ColumnLimit: '80' ConstructorInitializerAllOnOneLineOrOnePerLine: 'false' Cpp11BracedListStyle: 'false' IndentWidth: '4' Language: Cpp NamespaceIndentation: All SortIncludes: 'true' Standard: Cpp03 PenaltyBreakBeforeFirstCallParameter: 0 ...
应用这个配置后,clang-format会将VecABf的参数单独拆分为多行并对齐到开括号位置,同时保留闭括号与后续乘法表达式在同一行,符合期望格式。
内容的提问来源于stack exchange,提问作者nowox
相关产品推荐
相关产品推荐

