How do I align like this with VIM's Tabular Plugin?

Reman picture Reman · Mar 25, 2011 · Viewed 7.4k times · Source

This is my code:

john,betty,wally,beth 
walter,george,thomas,john
herbert,bob,petty,mick`

Does anyone know how to align it to this with VIM's Tabular Plugin:

john,    betty,  wally,  beth
walter,  george, thomas, john
herbert, bob,    petty,  mick

I know how to do this in Align Plugin but can't find out how it works in Tabular.

Answer

sidyll picture sidyll · Mar 26, 2011

I'm not a master in this, and everything I'll say here is based on my understanding of Tabularize.

Tabularize always splits things in fields, described by the regex. For example:

abc,d,e
a,b,cde

:Tab /,

Causes it to divide each line like the following:

|abc|,|d|,|e|
|a|,|b|,|cde|

Then each field is padded with spaces so the delimiter field align — and everything receives and extra-space by default (except for the last field, I think).

|abc |, |d |, |e  |
|a   |, |b |, |cde|

Resulting in:

abc , d , e
a   , b , cde

By adding flags, you can control alignment and padding for each field. If you provide less flags than needed, they are reused. So, to make everything align the same way, say left with padding 0 you can use a single flag that will be repeated for every field. So:

abc,d,e
a,b,cde

Tab /,/l0 <-- or c0, or r0 or whatever

abc,d,e
a  ,b,cde

The conclusion I have I my mind is that there isn't much sense in having a zero width field (like :Tab /,\zs), probably causing it to get the first character after the pattern and messing up, cutting it.

Now, for me :Tab /[^,]\+, didn't worked properly, generating doubled spaces:

john,     betty,   wally,  beth
walter,   george,  thomas, john
herbert,  bob,     petty,  mick`
        ^^       ^^

I think that's because there is no intermediate field. This pattern, makes a field delimiter reside side by side with another one, like this:

|john,||betty,||wally,||beth|

Then the zero with field generated (between delimiters) is also padded with the extra 1 space by default.

|john, | |betty, | |wally, ||beth| <-- for some outrageous reason the las one is cut.

john,  betty,  wally, beth

How to solve it?

I'd open space for a delimiter, that doesn't cause a delimiter to be near others. How? Simply adding a space after the comma.

john,betty,wally,beth 
walter,george,thomas,john
herbert,bob,petty,mick`

:%s/,/, /g

john, betty, wally, beth 
walter, george, thomas, john
herbert, bob, petty, mick`

Now you can align everything on spaces and zero padding:

john, betty, wally, beth 
walter, george, thomas, john
herbert, bob, petty, mick`

:Tab / /l0

john,    betty,  wally,  beth
walter,  george, thomas, john
herbert, bob,    petty,  mick`

I hope that helps understanding Tabularize!