Search code examples
regexvimformattingindentationcol

VIM - "Pretty" column format of structs in C


I have some C code with a lot of typedef'ed structs, and look like so in VIM:

typedef struct {
  int         a;
  someValue*    b;
  someOtherValue* c;
} val_t;

When I enable "print whitespace characters" in VIM via :set list, I see the code appears like so (with . characters denoting spaces, and --> denoting hard tabs):

typedef struct {
  int->-->-->-->a;
  someValue*....b;
  someOtherValue*>>c;
} val_t;

So, it seems like this code has a mix of hard-tabs and spaces all over the place, likely due to different editors being used to maintain it. I'm attempting to write some commands to tidy it up. I know I can do a visual selection via SHIFT+V, then pipe off the selection to col via:

:'<:'>!col

However, the output in VIM looks terrible, as it seems col is just separating the columns "logically" (ie: via three hard-tabs), rather than lexically, and the output looks like so:

typedef struct {
  int--->--->--->a;
  someValue*>--->--->b;
  someOtherValue*--->--->--->c;
} val_t;

Is there a way to tell col to align the columns of data using hard-tabs of a fixed width (ie: 4 "spaces" per tab) as shown below, so that the beginning of the variable names within the struct visually align? The desired result would be:

typedef struct {
  int--->--->--->--->a;
  someValue*>--->--->b;
  someOtherValue*--->c;
} val_t;

This would allow me to re-factor a bunch of header files on a per-block/per-struct level rather than spending hours manually indenting chunks of code to look nice.

Thank you.


Solution

  • Are you stuck on hard tabs? If not you may want to look into tabular or vim-easy-align.

    With tabular you can do something like this:

    :?{?+,/}/-Tabularize/\ze\w\+;/
    

    For more help see:

    :h \ze
    :h range