Vertical Alignment

4.4
(47)

Some weeks ago, I published a post where I demonstrated Undo from Insert Mode. In the accompanying video, the displayed Markdown file had a table which automatically reformatted to align itself when I edited it. Many of you asked how this magic worked, so I thought we should cover alignment in Vim with the Tabular plugin.

Tabular is an extensible plugin that will automatically align text vertically when its included function is invoked with a regular expression. Simply install the plugin, then select the text you wish to align and run the function with a pattern. For example, to align text vertically around the =

:Tabularize /=

You can shorten the function to :Tab and you don’t actually even need to select the lines. Tabular is clever enough to run the alignment on all the lines that match your pattern above or below your cursor. Here’s a quick demo. In it, I want to align the strings from these local variable assignments. Watch how easy it is, just by running the command above with my cursor somewhere in the list:

You can use this to align all kind of things: SQL queries, JSON, variables, hash keys, anything that might benefit from improved readability. There is ample debate about whether code should be aligned in this fashion, and I personally fall on the side of don’t align. Most of what I use Tabular for is the alignment of items in Markdown files, such as in my original post.

The magic of that automatic alignment comes from an additional extension that essentially runs :Tabularize whenever I type the | character from insert mode. The origin of that extension is a well-circulated Gist by Tim Pope. Just put this in your .vimrc:

The version of this function that I use comes from hashrocket.vim, a collection of Vim tweaks used by the software consultancy Hashrocket. It’s been tweaked a bit but does essentially the same thing: Every time I type a pipe character in a table form, the table aligns automatically. Here’s a demo of that in action:

How useful was this post?

Average rating 4.4 / 5. Vote count: 47

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

61 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts

Leave a reply

Your email address will not be published. Required fields are marked *