30

How can I realize the following indentation after access modifiers:

class A{
public:
int a;
}

should result in

class A
{
    public:
        int a; // note the indentation
}

clang-format only allows the access modifiers to be on the same level as the int a AccessModifierOffset: 0 resulting in

class A
{
    public:
    int a;
}
Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • What IDE are you using? – Jonathan Mee Dec 07 '16 at 16:59
  • VisualStudio 15 (unfortunately) – Gabriel Dec 07 '16 at 16:59
  • 3
    One way would be to set `IndentWidth` to 8 and `AccessModifierOffset` to `-4`. But this will also affect how statements within functions are indented. AFIK there's no clean way to do what you want here – Yan Zhou Dec 07 '16 at 20:07
  • 3
    I haven't found a way either, but it would be really nice, since this is the default in vim and my preferred style – Paul Jun 14 '17 at 07:43
  • 2
    Possible duplicate of [How to auto indent a c++ class with 4 spaces using clang-format?](https://stackoverflow.com/questions/42799183/how-to-auto-indent-a-c-class-with-4-spaces-using-clang-format) – AMA Jun 06 '18 at 18:41

3 Answers3

5

Where I work, we've stumbled upon the same problem. Since the IndentWidth parameter controls the indentation everywhere (classes, functions, etc.) what you're trying to achieve seems impossible. The next best thing, in my opinion, is to keep IndentWidth=4 and set AccessModifierOffset=-2. That way you get:

class Foo
{
  public:
    Foo() = default;
};

bool foo()
{
    return true;
}
ronhe
  • 126
  • 3
  • 6
4

@Gabriel: as of clang-format-13, the boolean key IndentAccessModifiers is supported in your .clang-format.

You can achieve this for instance with:

UseTab: ForContinuationAndIndentation
IndentWidth: 4
TabWidth: 4
IndentAccessModifiers: true

See https://clang.llvm.org/docs/ClangFormatStyleOptions.html for the complete reference.

godo
  • 195
  • 1
  • 11
0

I've achieved that with these settings:

IndentWidth: 4
AccessModifierOffset: 0
IndentAccessModifiers: true

If you are using a different IndentWidth have in mind that AccessModifierOffset stacks on top of that value.

Have in mind that clang-format-13 or never is needed to use IndentAccessModifiers option.

Since there is no anchor, I can't link it directly, but you should read more about IndentAccessModifiers at https://clang.llvm.org/docs/ClangFormatStyleOptions.html

CleanCoder265
  • 574
  • 1
  • 5
  • 22