Danish
Danish

Reputation: 407

clang-format: How to align list of struct inits

I have an array of structs:
(assume that the identifiers are #defined somewhere else...)

typedef struct
{
    int a;
    char id[2+1];
} T;

const T T_list[] = {
    { PRIO_HOUSE, "HI" },
    { PRIO_SOMETHING_ELSE, "WO" }
    // ...
}

I would like clang-format to format it like this:

const T T_list[] = {
    { PRIO_HOUSE         , "HI" },
    { PRIO_SOMETHING_ELSE, "WO" }
    // ...
}

Is it possible?

I already read the docs, but I didnt find something helpful in this regard. https://clang.llvm.org/docs/ClangFormatStyleOptions.html

This is my .clang-format

---
BasedOnStyle: WebKit
BreakBeforeBraces: Allman
BraceWrapping:
  AfterEnum: false  
IndentCaseLabels: 'true'
AlignConsecutiveAssignments: 'true'
AlignConsecutiveDeclarations: 'true'
AlignEscapedNewlines: 'true'
AlignTrailingComments: 'true'
AllowShortFunctionsOnASingleLine: 'false'
#...

Upvotes: 8

Views: 6907

Answers (3)

Robert Andrzejuk
Robert Andrzejuk

Reputation: 5232

No. clang-format cannot do this.

The way I do it is:

  1. use a third party tool to align it
  2. before the formatted region put: // clang-format off
  3. after the formatted region put: // clang-format on

Upvotes: 5

Claudio Perez
Claudio Perez

Reputation: 106

As of clang-format version 13 (2021) there is a new AlignArrayOfStructures option that does exactly this. From the now updated documentation linked in the question:

AlignArrayOfStructures (ArrayInitializerAlignmentStyle) clang-format 13

if not None, when using initialization for an array of structs aligns the >fields into columns.

And an example with AlignArrayOfStructures: Left:

struct test demo[] =
{
   {56, 23,    "hello"},
   {-1, 93463, "world"},
   {7,  5,     "!!"   }
};

Upvotes: 8

scx
scx

Reputation: 3947

If what you want is vertical alignement, you can achieve that with a trailing comma when using initializer lists.

Before

    const T T_list[] = { { PRIO_HOUSE, "HI" }, { PRIO_SOMETHING_ELSE, "WO" } };

After

    const T T_list[] = {
        { PRIO_HOUSE, "HI" },
        { PRIO_SOMETHING_ELSE, "WO" }, // <-- notice the comma here
    };

If you further want to align the declarations, I'm unsure how you'd go about it. But the trailing comma is step 1.

Upvotes: 1

Related Questions