Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert spaces up to column X to line up things in columns?

Tags:

vim

I have my source code for copy operators written as follows.

foo = rhs.foo; foobar = rhs.foobar; bar = rhs.bar; toto = rhs.toto; 

I'd like to line things up as follows (more human readable, isn't it?).

foo    = rhs.foo; foobar = rhs.foobar; bar    = rhs.bar; toto   = rhs.toto; 

Is there a VIM magic insert-up-to-column-N, or something like that that would allow me to line things up using a couple of keystrokes per line?

like image 750
Didier Trosset Avatar asked May 27 '11 15:05

Didier Trosset


People also ask

How do you put a space on multiple lines at once?

Alt + click left mouse button in the place you want to set an additional cursor. Alt + Ctrl + up/down arrow (put a cursor above/below current one)

How do you put a space in every line?

Select the paragraphs you want to change. Go to Home > Line and Paragraph Spacing. Choose the number of line spaces you want or select Line Spacing Options, and then select the options you want under Spacing.


2 Answers

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:

  1. qa -- Record a macro in hotkey a
  2. 0 -- Go to the beginning of the line
  3. f= -- Go to the first equals sign
  4. 100i <Esc> -- (There's a single space after the i, and the <Esc> means press escape, don't type "<Esc>".) Insert 100 spaces
  5. 8| -- Go to the 8th column (sorry, you'll have to manually figure out which column to align to)
  6. dw -- Delete until the next non-space character
  7. j -- Go to the next line
  8. 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 
like image 82
TalkLittle Avatar answered Oct 14 '22 01:10

TalkLittle


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.

like image 39
evnu Avatar answered Oct 13 '22 23:10

evnu