Vim Recipes Editing Formatting with an External Program

Formatting with an External Program

Problem

You want to reformat text with a program other than Vim. For example, you want to use the W3C's 'tidy' utility to format HTML.

Solution

Set the equalprg option to the name of the program you want to use, along with any arguments it should be passed. For example:

:set equalprg=tidy\ -indent\ -q

You can now select the text you want to format, then hit =. You can reformat the entire file with 1G=G.

Discussion

The formatter that you use depends on the type of content you are producing. Here are a couple of suggestions of programs to use for specific file types:

Text

If you want to format normal text using an external program, par is a popular choice. It can wrap, align, justify, and quote text in every conceivable way, and many more aside.

HTML/XHTML

Use HTML Tidy. You can specify options on the command line, as shown in the example above. If you want to specify a lot of options, put them into a config file, and point tidy to it: tidy --config file. At a minimum you probably want to use:

:setlocal equalprg=tidy\ -utf8\ -indent\ -q\ -f\ /tmp/err

Then you can reformat your file with 1G=G. One caveat is that this won't work correctly for reformatting a specific section of the file. You can use the --show-body-only true option if you want to be able to do this, but like many formatters of markup languages, Tidy doesn't perform as well on fragments because of lack of context.

XML

HTML Tidy can be used to format XML as well by passing it the -xml option. Alternatively, you can use xmllint:

:set equalprg=xmllint\ --format\ -