17

I want my visibility modifiers (public, protected and private) to be indented by clang-format who currently leaves them at the same level as the class declaration. I've looked for indent and visibility on a dump of the default format options but couldn't find anything.

ruipacheco
  • 15,025
  • 19
  • 82
  • 138

2 Answers2

23

From the Clang-Format Style Options documentation:

AccessModifierOffset (int) The extra indent or outdent of access modifiers, e.g. public:.

So, add the appropriate entry to your .clang-format. For example,

AccessModifierOffset: 2
Pradhan
  • 16,391
  • 3
  • 44
  • 59
  • 5
    Is there a way to have the code following them indented accordingly? Just using this only indents the modifier and the following code does not follow? – oarfish Aug 22 '19 at 13:44
4

If you want to give the access modifiers themselves their own level of indentation, you can use IndentAccessModifiers: true. This will give you code that looks like the following.

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

With IndentAccessModifiers: false, by default you'll get the access modifiers not indented at all, and class members will be indented only one level beyond the surrounding scope.

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

You can then use AccessModifierOffset to adjust the alignment of the access modifiers only, without affecting the alignment of the class members. With IndentAccessModifiers: false and AccessModifierOffset: 1, you'd get this.

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

With IndentAccessModifiers: true, AccessModifierOffset is ignored.

I'm sure all reasonable programmers would agree that only one of these options is even remotely acceptable. Though they probably wouldn't agree on which one it is.

Sam Marinelli
  • 999
  • 1
  • 6
  • 16
  • 1
    I just discovered to my dismay that `IndentAccessModifiers` is not yet in a released version of ClangFormat. Hopefully this answer will at least be useful in the future once Clang 12 is released (or to those with from-source Clang installations now). – Sam Marinelli Apr 08 '21 at 08:27
  • For the second demo, AccessModifierOffset should be -1? – BonieSV Oct 24 '22 at 10:03