regexvimtext-cursor

Easily aligning characters after whitespace in vim


I would like to create a mapped vim command that helps me align assignments for variables across multiple lines. Imagine I have the following text in a file:

foo                     = 1;
barbar            = 2;
asdfasd    = 3;
jjkjfh                = 4;
baz              = 5;

If I select multiple lines and use the regex below, noting that column 10 is in the whitespace for all lines, stray whitespace after column 10 will be deleted up to the equals sign.

:'<,'>s/^\(.\{10}\)\s*\(=.*\)$/\1\2/g

Here's the result:

foo       = 1;
barbar    = 2;
asdfasd   = 3;
jjkjfh    = 4;
baz       = 5;

Is there a way to get the current cursor position (specifically the column position) while performing a visual block selection and use that column in the regular expression?

Alternatively, if it is possible to find the max column for any of the equals signs on the selected lines and insert whitespace so all equals signs are aligned by column, that is preferred to solving the previous problem. Imagine quickly converting:

foo = 1;
barbar = 2;
asdfasd = 3;
jjkjfh = 4;
baz = 5;

to:

foo     = 1;
barbar  = 2;
asdfasd = 3;
jjkjfh  = 4;
baz     = 5;

with a block selection and a key-combo.


Solution

  • There are two plugins for that: Either the older Align - Help folks to align text, eqns, declarations, tables, etc, or Tabular.