首页 > 解决方案 > 如何使用 clang 格式保持标签缩进?

问题描述

gotoClang-format 删除标签上的缩进。使用// clang-format off不是首选。如何配置 clang-format 以不更改配置文件中标签的缩进?

期望的输出

标签缩进以匹配函数中的代码。他们应该留在那个缩进中。

int new_foo(foo **bar) {

  *bar = malloc(sizeof(foo));
  if ( !bar ) {
    goto failed;
  }

  goto done;
  failed: {
    return -1;
  }
  done:
  return 1;
}

实际输出

这是 clang-format 实际产生的。这是不可取的,因为它会破坏缩进折叠。

int new_foo(foo **bar) {

  *bar = malloc(sizeof(foo));
  if ( !bar ) {
    goto failed;
  }

  goto done;
failed: {
  return -1;
}
done:
  return 1;
}

更新

在配置中使用IndentGotoLabels: false(or true) 时,.clang-format这是结果。注意done:failed:标签向左移动。

int new_foo(foo **bar) {
  *bar = malloc(sizeof(foo));
  if (!bar) {
    goto failed;
  }

  goto done;
failed : { return -1; }
done:
  return 1;
}

的内容.clang-format

IndentGotoLabels: false

命令是cat test.cc | clang-format并在存在的同一目录中运行.clang-format

标签: cclang-format

解决方案


编辑:我最初的答案是错误的。

看起来无论如何IndentGotoLabels设置 goto 标签都没有缩进与代码相同的级别。考虑以下代码片段:

int new_foo()
{
    {
        int *p = malloc(sizeof(int));
        if (!p)
            goto first_label;

        int *q = malloc(sizeof(int));
        if (!q)
            goto second_label;

        return 0;

        first_label:
        return 1;
    }

    second_label:
    return 2;
}

使用以下配置:

---
Language:        Cpp
IndentGotoLabels: false
TabWidth: 4
...

跑步clang-format会给我们:

int new_foo() {
  {
    int *p = malloc(sizeof(int));
    if (!p)
      goto first_label;

    int *q = malloc(sizeof(int));
    if (!q)
      goto second_label;

    return 0;

first_label:
    return 1;
  }

second_label:
  return 2;
}

如果我们更改IndentGotoLabels为,true我们有:

int new_foo() {
  {
    int *p = malloc(sizeof(int));
    if (!p)
      goto first_label;

    int *q = malloc(sizeof(int));
    if (!q)
      goto second_label;

    return 0;

  first_label:
    return 1;
  }

second_label:
  return 2;
}

标签现在缩进了,但与{开始代码块的标签处于同一级别,而不是代码本身。

我不知道这是clang-format不能做的事情,还是我错过了一些选择。即使它实际上并不能解决问题,我也会保留我的答案。它可能被证明是有用的。

如果我们查看文档中的示例,这也是记录在案的行为,因此可能无法更改它。

这属于意见领域,但clang-format有时可能非常有限。如果您可以自由使用其他代码格式化程序,astyle可能会做您想做的事情--indent-labels

初步答案:

在您的文件中设置IndentGotoLabels为 false 。.clang-format有关更多信息,请参阅文档

如果您没有.clang-format文件,您可以根据预定义的样式生成一个文件:

clang-format -style=llvm -dump-config > .clang-format

推荐阅读