【问题标题】:Brace on new line only if current line overflows clang format仅当当前行溢出 clang 格式时才在新行上大括号
【发布时间】:2023-07-05 07:53:02
【问题描述】:

我最近决定在我的 C++ 项目中包含一个.clang-format 文件,以使代码更加统一和易于阅读。我最喜欢 Google 的默认设置,除了我想使用 4 个空格缩进而不是两个。

这样做的问题是,当当前行超出 80 个字符的列限制时,它会使某些语句更难阅读。例如,在溢出的 if 语句中:

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

yet_another_condition 的对齐方式与 if 块开头的对齐方式相匹配,这使得如果没有某种中断就很难阅读。理想情况下,我希望在这种情况下发生的事情是这样的:

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

但是,我只希望在新行上使用左大括号当当前行溢出到下一行时,就像上面的例子一样。在所有其他情况下,我希望左大括号在同一行(适用于 if/for/while/switch 等语句以及函数)。

是否可以在我的 .clang-format 文件中指定此行为,同时保持其余 Google 默认值不变?

【问题讨论】:

    标签: c++ formatting curly-braces clang-format google-style-guide


    【解决方案1】:

    clang-format 工具允许使用 BraceWrapping: Custom 指定自定义大括号包装,但它不够灵活,无法了解您需要的上下文。

    提高可读性的替代解决方案是使用大于 4 的连续缩进,例如ContinuationIndentWidth: 8.

    【讨论】:

    • 我担心可能是这种情况。不过感谢您的帮助,ContinuationIndentWidth 看起来是下一个最好的选择。