How to indent after access modifiers with clang-format
Asked Answered
S

3

33

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;
}
Spermatic answered 7/12, 2016 at 16:47 Comment(5)
What IDE are you using?Trollope
VisualStudio 15 (unfortunately)Spermatic
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 hereTrawler
I haven't found a way either, but it would be really nice, since this is the default in vim and my preferred styleRobers
Possible duplicate of How to auto indent a c++ class with 4 spaces using clang-format?Privy
V
6

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;
}
Validate answered 5/6, 2020 at 12:27 Comment(1)
Also IndentAccessModifiers should be set to falseCoroner
S
5

@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.

Samala answered 7/3, 2022 at 15:22 Comment(0)
Q
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

Quickfreeze answered 21/11, 2022 at 12:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.