如何使用clang-format自动缩进4个空格的C ++类?

问题描述 投票:24回答:3

我在项目的根目录中获得了下一个.clang格式的文件:

---
AlignTrailingComments: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatementsOnASingleLine: true
AllowShortLoopsOnASingleLine: true
BreakBeforeBinaryOperators: false
IndentWidth: 4
SortIncludes: false
NamespaceIndentation: All
...

当我在我的c ++标题上运行clang-format时出现问题,类会自动缩进,如下所示:

enter image description here

如您所见,标签public和private仅缩进2个空格。但我想要实现的是下面的输出(缩进是手动调整):

enter image description here

这样,代码崩溃变得非常愉快。

我怎么能调整我的.clang格式才能达到这个效果?如果不可能,你将如何修补clang格式的源代码来实现这种期望的行为?

编辑:

我尝试过使用AccessModifierOffset失败,我使用了以下值{-2,0,2,4}:

enter image description here

如您所见,公共块内的语句将不会正确缩进。

Aaditi:

我已经尝试了@Henrique Jung解决方案,这绝对不是我要求的,如果使用这种组合,结果将是这样的:

enter image description here

正如您所看到的,函数内部缩进了8个空格而不是4个,这并不好。

Aadita:

几个月前我给了赏金,所以我要再试一次,因为这个肯定很有趣。如果我对俚语格式的源代码有足够的了解,我会试一试,不幸的是我没有。

c++ indentation auto-indent clang-format
3个回答
2
投票

就像我所知,clang-format没有提供缩进函数内容的选项,与non-access-modifier类内容不同。也就是说,请考虑以下代码:

class A {
  public:
    void foo() {}
}

void bar() {
    int a;
}

在此代码中,“void foo(){}”行将始终缩进与“int a;”相同的量。通过clang格式。

与您似乎想要的样式最接近的是来自不缩进访问修饰符,例如:

class A {
public:
    void foo() {}
}

void bar() {
    int a;
}

例如,这可以通过WebKit,Mozilla和LLVM样式完成。它是通过设置来实现的:

IndentWidth: 4
AccessModifierOffset: -4

1
投票

我设法通过使用IndentWidth更改AccessModifierOffset来实现您想要的效果。基本上,第一个用作第二个的偏移,所以如果你像这样创建.clang格式,你得到你想要的:

AccessModifierOffset: -4
IndentWidth:     8

如果AccessModifierOffset为0,则public关键字将与成员处于相同的缩进级别。但是,更改IndentWidth会将所有代码缩进8个空格,甚至是类声明之外的空格。这是一个示例代码:

class Foo {
    public:
        Foo();
        virtual ~Foo(); };

int main(int argc, char *argv[]) {
        std::cout << "Hello world" << std::endl;
        return 0;
}

0
投票

我遇到了同样的问题,并找到最快的解决方案是将clang默认设置(通过首选项 - >包设置 - > Clang格式 - >自定义样式 - 默认)复制到用户自定义设置(首选项 - >包设置) - > Clang Format - > Custom Style - User),然后根据自己的喜好取消注释并修改某些选项。例如:

"ColumnLimit": 119,
// Indent width for line continuations.
"ContinuationIndentWidth": 4,
// The number of columns to use for indentation.
"IndentWidth": 4,
"TabWidth": 4,
"UseTab": "Never"
© www.soinside.com 2019 - 2024. All rights reserved.