Can clang-format align variable or macro assignments in columns?

13.2k views Asked by At

Is it possible to have clang-format align variable assignments in columns? For example:

int someInteger             = 42;
std::string someString      = "string";
const unsigned someUnsigned = 42;

#define SOME_INTEGER        42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT       42

enum Enum {
    ONE   = 1,
    TWO   = 2,
    THREE = 3,
    FOUR  = 4,
    FIVE  = 5,
    SIX   = 6,
    SEVEN = 7
};

is more readable than:

int someInteger = 42;
const unsigned someUnsigned = 42;
std::string someString = "string";

#define SOME_INTEGER 42
#define SOME_STRING_LITERAL "string"
#define SOME_CONSTANT 42

enum Enum {
    ONE = 1,
    TWO = 2,
    THREE = 3,
    FOUR = 4,
    FIVE = 5,
    SIX = 6,
    SEVEN = 7
};

I realize that it may not be practical for clang-format to always do this, but when code as already been manually formatted like said code, it would be nice for clang-format to leave the formatting in place.

5

There are 5 answers

6
Michael Anderson On BEST ANSWER

It looks like 3.7 supports something like this (haven't tested yet).

From the docs

AlignConsecutiveAssignments (bool)
If true, aligns consecutive assignments.

This will align the assignment operators of consecutive lines. This will result in formattings like code int aaaa = 12; int b = 23; int ccc = 23; endcode

(sic)

1
bames53 On

Clang-format does not have any option to do this.

If you want to tell clang-format to leave certain lines alone, you can make it do so with // clang-format off and // clang-format on comments.

1
conecon On

I tested it using https://github.com/mattga/ClangFormat-Xcode/tree/clang_3.7 which is branch of ClangFormat-Xcode supporting 3.7.

I could format a = 9999; type list as I wanted by option

AlignConsecutiveAssignments = true

. But definitions were not aligned. Is there any indication to align them?

0
hiproz On

you can use this options:AlignConsecutiveMacros: true ref:https://clang.llvm.org/docs/ClangFormatStyleOptions.html support llvm version: >=10.0

0
rhssk On

For macros: looks like you will be able to accomplish this once clang 10 is released, by adding AlignConsecutiveMacros: true to you .clang-format

https://reviews.llvm.org/D28462