Monday, June 16, 2008

Text Formatting Features

A friend of mine contributed the following tip. I was going to rewrite it, but he explained it very clearly, so here it is verbatim:

I've been editing a plain text latex input file and am using vim's text formatting features for the first time. First useful item is :set textwidth=80 (or your preferred column width) which auto-wraps lines as you type. This is great, unless you edit part of the file before the end and mess up the text width. I discovered through the glorious vim help system the normal command gq which auto-formats a range of text. Its default behavior is a bit weird if you use it on the whole file (like gg=G for auto-indenting code), but you can do nifty things like:

format the current paragraph: {V}gq ( { = go to previous white-space-only line V=visual line select }=go to next white-space-only line )

here's how to apply formatting to all "paragraphs" using the :global command:

:%g/^\s*$\n\s*[A-Za-z]/normal V}gq

This is really specific to LaTeX, since "paragraphs" are divided by white space lines. This pattern will match any whitespace-only line, followed by a line starting with (possibly) whitespace, then an [A-Za-z].

Thanks Chris for the great tip!


Unknown said...

Vim has a built-in paragraph text object, so the paragraph-formatting command can be simplified to gqap -- format (gq) (a) (p)aragraph.

Unknown said...

nice! i figured there was something like that in there - i tried gqa{ but that didn't do it. i <3 text objects