Search code examples
vimalignmenttabular

Right align a specific column separated by spaces


Example:

Monte Bianco 4.807 France/Italy
Monte Rosa 4.634 Italy/Switzerland
Dom 4.545 Switzerland/Italy
Weisshorn 4.505 Switzerland
Cervino (Matterhorn) 4.478 Italy/Switzerland
Suphan Dagi 4.434 Turkey   

I'm trying to create 2 new menu options (in menu.vim):

  • Align right 1st column
  • Align right last column

I can't find out how to align right only the first, only the last column or a specific column in the middle of my table.

Monte Bianco 4.807              France/Italy
Monte Rosa 4.634           Italy/Switzerland
Dom 4.545                  Switzerland/Italy
Weisshorn 4.505                  Switzerland
Cervino (Matterhorn) 4.478 Italy/Switzerland
Suphan Dagi 4.434                     Turkey   

I know I can use this to align right the latest column

Tabular /^\(.\{-}\s\{1,}\)\{1,}/l0l0r0 

but what I want to find out is how to find the latest align parameter before the end of line
(p.e. in above example "Spaces") and align right all text after this (without counting the number of columns).

Is this possible?

And I have no idea at all how to align right only the first column or a specific column.


Solution

  • In order to right align the first whitespace-separated column leaving the rest of them aligned to the left, use the following :Tabular command,

    :Tab/^\S*\s\+\zs/r1l0l0
    

    Similarly, to right align the last column, run

    :Tab/\s\@<!\ze\s\+\S*$/l1l0r0
    

    If column separators must have, say, at least two space characters, modify the commands as follows.

    :Tab/\(\s\{2,}.*\)\@<!\s\{2,}\zs/r1l0l0
    

    and

    :Tab/\s\@<!\ze\s\{2,}\(.*\s\{2,}\)\@!/l1l0r0