Search code examples
vimtext-formatting

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?


Solution

  • 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