How to auto indent a C++ class with 4 spaces using clang-format?

后端 未结 3 796
北荒
北荒 2021-02-01 03:13

I got the next .clang-format file in my project\'s root directory:

---
AlignTrailingComments: true
AllowShortFunctionsOnASingleLine: false
AllowShortIfStatements         


        
相关标签:
3条回答
  • 2021-02-01 03:28

    I managed to achieve the effect you want by changing both AccessModifierOffset with IndentWidth. Basically, the first is used as an offset of the second, so if you create your .clang-format like this you get what you want:

    AccessModifierOffset: -4
    IndentWidth:     8
    

    If AccessModifierOffset is 0, the public keyword would be at the same level of indentation as the members. However, changing IndentWidth will indent all code by 8 spaces, even those outside the class declaration. This is a sample code:

    class Foo {
        public:
            Foo();
            virtual ~Foo(); };
    
    int main(int argc, char *argv[]) {
            std::cout << "Hello world" << std::endl;
            return 0;
    }
    
    0 讨论(0)
  • 2021-02-01 03:47

    As near as I can tell, clang-format offers no option for indenting function contents differently from non-access-modifier class contents. That is, consider the following code:

    class A {
      public:
        void foo() {}
    }
    
    void bar() {
        int a;
    }
    

    In this code, the line "void foo() {}" will always be indented the same amount as "int a;" by clang-format.

    The closest thing to the style you seem to want that is available would come from not indenting the access modifiers, e.g.:

    class A {
    public:
        void foo() {}
    }
    
    void bar() {
        int a;
    }
    

    This is done, for example, by the WebKit, Mozilla, and LLVM styles. It's achieved by setting:

    IndentWidth: 4
    AccessModifierOffset: -4
    
    0 讨论(0)
  • 2021-02-01 03:47

    I met the same problems, and find the quickest solution is to make a copy of clang default setting(found by Preference -> Package Settings -> Clang Format -> Custom Style-Default) into the user custom setting(Preference -> Package Settings -> Clang Format -> Custom Style - User), then uncomment and modify some options into your own preference. For Example:

    "ColumnLimit": 119,
    // Indent width for line continuations.
    "ContinuationIndentWidth": 4,
    // The number of columns to use for indentation.
    "IndentWidth": 4,
    "TabWidth": 4,
    "UseTab": "Never"
    
    0 讨论(0)
提交回复
热议问题