vim_column_trick.md 3.4 KB


title: "Column formatting within Shell / Vim, e.g., for Neomutt and Abook" date: 2019-01-16

category: TechTips

The following is a micro-tip for formatting text in vim. If you are writing a document and want to have the text in neatly aligned columns, resembling a table, you can pipe text to the shell's column command.

To do so, select a range of text with visual mode (Shift-V), and then enter the following ex command:

:!column -t

So to demonstrate, you can go from having text that looks like this:

GNU Linux Parabola Gentoo Comfy Memes
RC 1337 N3rd Ghanoo Wizard SuperDuperLongWord
Apples Oranges Windoze 9000 Remainder Clutch

to text that looks like this:

GNU Linux Parabola Gentoo Comfy Memes
RC 1337 N3rd Ghanoo Wizard SuperDuperLongWord
Apples Oranges Windoze 9000 Remainder Clutch

I like using this command for managing my abook address book file that is used by neomutt. To illustrate: the raw text of the alias file, generated by calling abook from within neomutt, looks like this:

#<alias><nickname><fullaname><address>
alias bob bob jones <bobjones@fakemail.com>
alias joe joe bobs <joebobs@fakemail.com>
alias mimi mimi gator <mimigator@superfakemail.com>
alias sally sally sullen <ssullen@sallymail.com>
alias zeb zeb doolio <zd@doolmail.com>

This is pretty messy and hard to parse at a glance. So I occasionally open up the file and run the column command to clean it up, yielding this:

Three points to note. First, the "table" versions of the output above are rendered using html styling, and don't look as clean as I'd like. When you run the column command on plain text, it usually ends up looking neater.

Second, you can, of course, pipe the contents of the file directly through column without being in vim. The following command will do the trick:

$ cat mutt_aliases | column -t > mutt_aliases

Be careful, though, as this will overwrite your file, and you cannot undo the changes. That is one reason I like doing it within a vim buffer. You can output to a different file, say mutt_aliases_tmp, to eyeball it before replacing the old file, for some more protection.

And third, a note specific to abook alias files: if your aliases include nicknames with spaces in them, the outputted, columnar format will likely not be clean. column will break up the nicknames with spaces in them.

Conclusion

The column command is a handy way to format text when you're working in vim or on the terminal. It is a quick way to clean up messy files, and feels a little bit like magic when it works.

#\\\\
aliasbobbobjones
aliasjoejoebobs
aliasmimimimigator
aliassallysallysullen
aliaszebzebdoolio