【问题标题】:clang-format weird indentation of array of structs in C++C++中结构数组的clang格式奇怪的缩进
【发布时间】:2019-06-18 07:12:01
【问题描述】:

我正在尝试使用 clang-format(在 VS 代码中)来格式化我的 C++ 文件并将其配置为我喜欢的样式。对于结构数组(对于 getopts),它会添加大量额外的空格并弄乱大括号包装:

我将在此查询的末尾附加我的 .clang 格式

这是我希望我的数组出现的方式:

int main()
{
  const struct option longopts[]=
  {
    {"log-file", required_argument, 0, LOGFILE},
    {"log-level", required_argument, 0, LOGLEVEL},
    {nullptr, 0, nullptr, 0}
  };
}

这是它的实际显示方式:

int main()
{
  const struct option longopts[] =
      {
          {"log-file", required_argument, 0, LOGFILE},
          {"log-level", required_argument, 0, LOGLEVEL},
          {nullptr, 0, nullptr, 0}};
}

我的 .clang 格式文件包含:

BasedOnStyle: LLVM
IndentWidth: 2
AlignAfterOpenBracket: Align
AlignTrailingComments: true
AllowAllParametersOfDeclarationOnNextLine: true
AllowShortFunctionsOnASingleLine: true
AllowShortBlocksOnASingleLine: true
BinPackParameters: true
BreakBeforeBraces: Custom
BraceWrapping:
  AfterClass: true
  AfterControlStatement: true
  AfterEnum: true
  AfterFunction: true
  AfterNamespace: true
  AfterObjCDeclaration: true
  AfterStruct: true
  AfterUnion: true
  AfterExternBlock: true
  BeforeCatch: true
  BeforeElse: true
  IndentBraces: false
  SplitEmptyFunction: false
  SplitEmptyRecord: false
  SplitEmptyNamespace: false
BreakConstructorInitializers: AfterColon
ColumnLimit: 0
ConstructorInitializerAllOnOneLineOrOnePerLine: false
IndentCaseLabels: true
KeepEmptyLinesAtTheStartOfBlocks: true
NamespaceIndentation: All
PointerAlignment: Right
SortIncludes: false
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: Never
SpaceInEmptyParentheses: false
SpacesInContainerLiterals: false
SpacesInAngles: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
UseTab: Never

欢迎任何解决方案!

【问题讨论】:

    标签: c++ code-formatting clang-format


    【解决方案1】:

    我不确定是否可以实现您想要的,但有时最简单的方法是稍微修改源文件以帮助使用 clang-format 实用程序。首先,您需要在格式文件中添加一个ContinuationIndentWidth: 2 选项。然后在数组最后一项后加逗号:

    {nullptr, 0, nullptr, 0}, // <---
    

    最后将第一个花括号移动到与数组名称相同的行上。生成的文件将是这样的:

    int main()
    {
      const struct option longopts[] = {
        {"log-file", required_argument, 0, LOGFILE},
        {"log-level", required_argument, 0, LOGLEVEL},
        {nullptr, 0, nullptr, 0},
      };
    }
    

    运行 clang-format 将保持原样。在来自 LLVM 快照构建 LLVM-9.0.0-r351376-win64.exe 的 clang 格式上进行了测试。

    【讨论】:

    • 谢谢!正如你所说,由于左大括号的结束位置,它不是很完美,但比以前好多了!
    猜你喜欢
    • 1970-01-01
    • 2021-04-15
    • 1970-01-01
    • 2016-06-07
    • 1970-01-01
    • 2017-03-01
    • 2020-07-09
    • 2020-02-02
    • 1970-01-01
    相关资源
    最近更新 更多