Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align text only on first separator in VIM

Tags:

alignment

vim

Suppose I have this code:

width: 215px;
height: 22px;
margin-top: 3px;
background-color: white;
border: 1px solid #999999;

I want to align it this way:

width:            215px;
height:           22px;
margin-top:       3px;
background-color: white;
border:           1px solid #999999;

using Align.vim I can do :Align \s to use whitespace as separator, but that has 2 problems

  1. the initial indent is doubled
  2. all whitespaces are considered separators, so the last line is messed up

I've read through the many options Align.vim offers, but I haven't found a way to do this.

like image 623
Matteo Riva Avatar asked Jan 25 '10 00:01

Matteo Riva


2 Answers

You can do this with a Vim macro, no plugins needed. Put the cursor anywhere on the first line, and type in normal mode, not insert mode:

qa0f:w100i <Esc>19|dwjq4@a

Note the single space after the 100i, and the <Esc> means "press escape"--don't type "<Esc>" literally.

Translation:

qa         -- record macro in hotkey a
0          -- go to beginning of line
f:         -- go to first : symbol
w          -- go to next non-space character after the symbol
100i <Esc> -- insert 100 spaces
19|        -- go to 19th column (value 19 figured out manually)
dw         -- delete spaces until : symbol
j          -- go to next line
q          -- stop recording macro
4@a        -- run the macro 4 times (for the remaining 4 lines)

And yes, I used a similar macro to format the above code block :)

Cf. my answer to a similar Vim alignment question.

To apply this to a number of lines in visual mode, do, select and type:

:norm!@a
like image 64
TalkLittle Avatar answered Sep 22 '22 17:09

TalkLittle


If you use Tabular, then you can just do :Tabularize /:\zs/.

Looking at Align's description on vim.org, a similar invocation should work for it. You could try :Align :\zs. I don't use Align, so I'm not positive.

like image 31
jamessan Avatar answered Sep 25 '22 17:09

jamessan