How to insert spaces up to column X to line up things in columns?
The other answers here are great, especially @nelstrom's comment for Tabular.vim and his excellent screencast.
But if I were feeling too lazy to install any Vim plugins, yet somehow willing to use Vim macros, I'd use macros.
The algorithm:
For each line,
Add tons of spaces before the symbol =
Go to the column you want to align to
Delete all text up to =, thereby shifting the = into the spot you want.
For your example,
foo = rhs.foo;
foobar = rhs.foobar;
bar = rhs.bar;
toto = rhs.toto;
Position the cursor anywhere on the first line and record the macro for that line by typing, in normal mode:
qa0f=100i <Esc>8|dwjq
Which translates to:
-
qa
-- Record a macro in hotkeya
-
0
-- Go to the beginning of the line -
f=
-- Go to the first equals sign -
100i <Esc>
-- (There's a single space after thei
, and the<Esc>
means press escape, don't type "<Esc>".) Insert 100 spaces -
8|
-- Go to the 8th column (sorry, you'll have to manually figure out which column to align to) -
dw
-- Delete until the next non-space character -
j
-- Go to the next line -
q
-- Stop recording.
Then run the macro stored at hotkey a
, 3 times (for the 3 remaining lines), by putting the cursor on the second line and pressing:
3@a
If you are using a unix-like environment, you can use the command line tool column
. Mark your lines using visual mode, then:
:'<,'>!column -t
This pastes the selected text into the stdin of the command after '<,'>!
. Note that '<,'>!
is inserted automatically when you hit :
in visual mode.
There is a nice plugin which does exactly that and more, called Align.vim
For you case, you would need to select your expression and then type :Align =
. It will align everything, using =
as a separator and reference.
(There is a lots of options to align, left, right, cyclically, etc)
You can also check Tabular.vim which provides similar features. See the screencast there for a demo.
A quick, simple way to proceed is to add X spaces and then delete back to column X. For example, if X=40, type
40a<Space><Esc>d40|
An alternative solution is to perform two consecutive substitutions:
%s/=/ =/
%s/\%>7c *//
The trick is the column pattern \%>7c
that matches white spaces
*
only after the 7th column. Here foobar
is the longest variable name with 6
characters so we need 7
in the regex.