Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I align columns where the biggest number or greatest string is the align indicator?

Tags:

alignment

vim

How can I right align (and left align?) a block of numbers or text in vim like this:

from:

45    209   25     1
2      4     2     3
34      5   300     5
34    120   34    12

to this:

45    209    25    1
 2      4     2    3
34      5   300    5
34    120    34   12

That means the biggest number or greatest string in every column doesn't move.
In the first column it is 45+34, in the second column 209+120, in the third column 300 and in the last column 12.

like image 331
Reman Avatar asked Jun 30 '11 14:06

Reman


3 Answers

Have a look at the align plugin, it can do this and much more. Great tool in your utility belt!

Found here

After some serious vimhelp/reading I found the correct AlignCtrl mapping... Visually select the table, e.g. by using ggVG, then do a \Tsp i.e. <leader>Tsp

Then I get this:

 45   209    25    1
  2     4     2    3
 34     5   300    5
 34   120    34   12

From vimhelp:

\Tsp  : use Align to make a table separated by blanks |alignmap-Tsp|
        (right justified)
like image 185
Fredrik Pihl Avatar answered Nov 15 '22 10:11

Fredrik Pihl


You can look into the Tabularize plugin. So if you have something like

45 209 25 1
2 4 2 3
34 5 300 5
34 120 34 12

just select those lines in the visual mode and type :Tab/ and it will format it as

45   209   25    1
2    4     2     3
34   5     300   5
34   120   34    12

Also, it looks like you don't have an equal number of spaces separating the numbers at the moment. So before you use the plugin, replace all the multiple spaces with a single space with the following regex:

%s![^ ]\zs  \+! !g
like image 26
abcd Avatar answered Nov 15 '22 10:11

abcd


With the Align plugin you can select the rows you want to align and hit :

<Leader>Tsp

From Align.txt

  \Tsp  : use Align to make a table separated by blanks |alignmap-Tsp|
          (right justified)

(The help mention \ because it is the default leader but in case you have changed it to something else you must adapt accordingly)

Just trying on my install, I got the following result :

45   209    25    1
 2     4     2    3
34     5   300    5
34   120    34   12

In my opinion Align plugin is great but the "align maps" and various commands are not really easy to remember.

like image 35
Xavier T. Avatar answered Nov 15 '22 09:11

Xavier T.