Dave Vogt
Dave Vogt

Reputation: 19502

Format text as blocks (aligning second column)

A lot of times, I have a list of initializers in some of my code, like this:

class Foo(object):
    def __init__(self, data):
        self.foo       = data.getFoo()
        self.bar       = data.getBar()
        self.something = data.getSomething()

As you can see, I like my code aligned like a table. In a lot of cases, the above code can be generated by scripting Vim, coming from the output of some other program (DESCRIBE "foo"; in a database for example). Unfortunately, the scripted output usually looks like this, first:

class Foo(object):
    def __init__(self, data):
        self.foo = data.getFoo()
        self.bar = data.getBar()
        self.something = data.getSomething()

So after the automatic generation of th assignment statements, I'll have to manually align all statements for the desired look.

Now: Is there a way to get vim to align those "second halves"of the statements automatically?

Upvotes: 3

Views: 579

Answers (3)

Magnun Leno
Magnun Leno

Reputation: 2738

The tabular plugin does exactly this. You can see it in action (and learn how to use it) here.

UPDATE: I'll give a brief explanation about the plugin usage, but no explanation will be better then Drew's video, so I strongly suggest everybody to watch it.

To use the plugin just call :Tab /= and it will align all the equal signs in the file. If you want to specify which line you want to align just give it a range :5,10Tab /= or use the visual mode (v or V) to select the desired lines, press : and insert the Tabularize command, your command line will look like this: :'<,'>Tab /=.

The argument in the Tabcommand is a Regular Expression, this means you can use this command to align many things. You'll be restricted only by your Regular Expression knowledge.

Sorry for any English mistake :D

Upvotes: 3

Ingo Karkat
Ingo Karkat

Reputation: 172530

An alternative to the already mentioned Tabular plugin is the venerable Align plugin.

Upvotes: 1

Dave Vogt
Dave Vogt

Reputation: 19502

One naive approach would be to first make enough space around the equal signs:

:s/=/                         =/

Then, block-selecting (Ctrl-V) so that all the = characters and everything that follows is selected. Yank(y) that, paste it somewhere else.

Next, un-indent the pasted lines (10< is usually sufficient) until they're aligned to the leftmost position. Then, block-select again and paste to where they were cut off.

This feels like a lot of work though, for the desired effect.

Upvotes: 0

Related Questions