Vim indent xml file Vim indent xml file xml xml

Vim indent xml file


I like Berei's answer. However, I think the following is a little more flexible in that you don't have to alter your vimrc file. Plus it is easier to format select portions of the XML file (something I happen to do a lot).

First, highlight the XML you want to format.

Then, in normal mode, type ! xmllint --format -

Your command-line at the bottom will look like this:

:'<,'>!xmllint --format -

Then hit enter.

Technical Explanation

The selected text is sent to the xmllint command, then --format'ed, and the results of xmllint are placed over your selected text in vim. The - at the end of the command is for receiving standard input - which, in this case, is the selected text that vim sends to xmllint.


Use an external program to indent your xml files. In this case I've choosen xmllint, so set the command to the equalprg option:

:set equalprg=xmllint\ --format\ -

Now you can execute

gg=G

to let xmllint format your xml files.

To get it every time you use , use an autocommand to set it.

autocommand from a comment below

au FileType xml setlocal equalprg=xmllint\ --format\ --recover\ -\ 2>/dev/null


A simple solution that I like which doesn't require any 3rd party tool is to insert a newline before each opening tag '<...>'. Then you can use standard vim auto-indentation. In short:

  1. %s/</\r</g
  2. gg=G to auto indent