Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert variable number of spaces necessary to align textual columns in Vim?

I’m a fan of Visual mode in Vim, as it allows to insert text before any given column.

For example, insertion of spaces after the quotation leaders below:

> one
> two
> three

can be done via <Ctrl-V>jjI <Esc>:

>   one
>   two
>   three

as follows:

  1. Start Visual mode with Ctrl-V.
  2. Extend visual selection with jj.
  3. Insert some spaces with I__.
  4. Propagate the change to all the lines of the block selection with Esc.

Now I have a text file that needs some formatting. This is what it looks like:

start() -- xxx
initialize() -- xxx
go() -- xxx

Now I want to align part of this text to arrange it into columns like this:

start()       -- xxx
initialize()  -- xxx
go()          -- xxx

The problem I have is that I cannot insert a different amount of indentation into each line and merely indenting a fixed amount of spaces/tabs is insufficient. How can you do an indentation where all indented text will have to be aligned at the same column?

Update

I only figured out a rather verbose and unwieldy method:

  1. Find the string position to indent from: \--.
  2. Insert n (let's say 20) spaces before that: 20i <Esc>.
  3. Delete a part of those spaces back to a certain column (let's say 15): d|15.
  4. Save those steps as a macro and repeat the macro as often as necessary.

But this approach is very ugly, though!

like image 275
oliver Avatar asked Sep 23 '11 12:09

oliver


2 Answers

I'm much better off without any vim plugins. Here is my solution:

<Shift-V>jj:!column -ts --

Then insert -- into multiple lines just as you wrote in the question.


You can also append a number of comments at insertion time.

:set virtualedit=all

<Ctrl-V>jjA-- xxx<Esc>

like image 194
ernix Avatar answered Sep 19 '22 00:09

ernix


You have to use a specific plugin, you can use either Tabular or Align plugin in this case.

They both allow you to align text on specific characters, like -- in your example. Their syntax is a bit different though. Pick the one that suit you the most.

like image 35
Xavier T. Avatar answered Sep 21 '22 00:09

Xavier T.