Search code examples
regexvimvim-tabular

How to ignore lines containing curly braces when using the Tabular plugin in Vim?


Consider aligning properties in a CSS file using the Tabular plugin in Vim. Suppose we have the following CSS ruleset:

body {
  margin: 0;
  padding: 0;  
  font-family: arial, verdana;
}

With the cursor inside the rule, vi{ followed by :Tab /:\zs results in

body {
  margin:      0;
  padding:     0;  
  font-family: arial, verdana;
}

However, I would like to align all the property values in all rulesets in the file at once, not just in one ruleset.

Running the same Tabular command for all lines (:%Tab /:\zs) does achieve the desired effect, as rule names needlessly affect the width of the left column. Besides, some CSS rules contain several : characters.

How to ignore lines containing curly braces when running such Tabular command?


Solution

  • To work around the issue, one can eliminate the problematic lines from affecting the width of the first column by prepending the column separator at the start of each of those lines. When the alignment is done, this extra prefix can be easily removed. Following this approach we will have three commands, like so:

    :%g/:.*{/ s/^/:/ | exe '%Tab/^[^:]*:\zs' | %s/^:\s*//
    

    You can map this command to a shortcut, or even run it automatically when a CSS file is saved:

    :autocmd BufWrite *.css %g/:.*{/ s/^/:/ | exe '%Tab/^[^:]*:\zs' | %s/^:\s*//