0

How to do proper indentation in vim for designated initializers of structs (in C)?

This is how it is indented by default:

typedef struct {
    int foo;
    int bar;
} child_t;

typedef struct {
    child_t child;
} parent_t;

int main(int argc, char *argv[]) {
    parent_t p;
    p.child = (child_t) {
        .foo = 1,
            .bar = 2,
    };
}

How can I have it indented like this?

typedef struct {
    int foo;
    int bar;
} child_t;

typedef struct {
    child_t child;
} parent_t;

int main(int argc, char *argv[]) {
    parent_t p;
    p.child = (child_t) {
        .foo = 1,
        .bar = 2,
    };
}

I've tried quite a few options from https://vimdoc.sourceforge.net/htmldoc/indent.html but haven't been able to make it work.

Removing (child_t) allows it to do indent properly, but in that case the gcc compiler complains with an expected expression before ‘{’ token error message (because apparently it isn't able to infer what type p.child is.

Anne van Rossum
  • 3,091
  • 1
  • 35
  • 39
  • 1
    If you remove the `(child_t)` it's no longer a compound literal but invalid syntax. – Lundin Jan 17 '23 at 13:25
  • 1
    I don't know how to fix the indentation in `vim`. In this special case you could initialize `p` where you define it without using the type specification. As a workaround you could use a variable of type `child_t` for a structure field assignment. `parent_t p;` `child_t c = { ... };` `p.child = c;`. – Bodo Jan 17 '23 at 13:26
  • You can send the content of the file to `clang-format` (https://clang.llvm.org/docs/ClangFormat.html) with `:%!clang-format`. – Tekki Jan 17 '23 at 14:15
  • @Tekki and then .clang-format based on LLVM? – Anne van Rossum Jan 17 '23 at 16:13
  • @AnnevanRossum Depends on your preferences. I have "BasedOnStyle: Google" in my `~/.clang-format`. – Tekki Jan 18 '23 at 07:23
  • Note sure, how easy it is, but would also be nice to know how to do so without external tools. – Anne van Rossum Jan 19 '23 at 15:28

1 Answers1

0

If you use vim and want propper formatting, I can recomd to use coc vim and ccls. Further you can use clang-format to format your source files propperly.

leongross
  • 329
  • 2
  • 8