Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Is there an easy way within vi to make your XML text "pretty"?

For example:

I want this..


to be this...

share|improve this question
If all else fails, there's always macros. qq0dt<jq and then 3@qj@@5k4I<space><esc>j.j.j.. Wow, that looks pretty cryptic. – Braden Best Dec 13 '13 at 0:03
up vote 20 down vote accepted

I've had the most luck with this:

:%!xmllint --format %

It's strict about your tags, though, so it will error out if your opening and closing tags don't match. It also adds an XML declaration at the top of your file, if you don't have one as well.

This page recommends the following, although I can't get it to work:

:set filetype=xml
:filetype indent on

I tested it out, and it seems to work, somewhat. Not perfectly, but it gets the job done.

If that doesn't work well, you could use minidom in Python to format it for you.

import xml.dom.minidom

xml = xml.dom.minidom.parse(filename)
formatted_xml = xml.toprettyxml()
share|improve this answer
That gg=G command didn't really work. Instead, it just removed all the previous indentations I had. – Rob Avery IV Jan 24 '13 at 20:10
Yeah, I've found the same thing. It seems to work when I have a specific type of formatting already, but usually not. I'll have to test it out a bit more. – Nate Jan 24 '13 at 20:14
:%!xmllint --format % seems to work well, so I've added that to the post. – Nate Jan 24 '13 at 20:20
Do you if you can set the tab indent size? For example: A parent's children will be 1 tab instead of 3 spaces, etc. – Rob Avery IV Jan 25 '13 at 13:40
@RobAveryIV you can set the indentation by setting the environment variable XMLLINT_INDENT. Default is two spaces, and you can set it to anything you want: export XMLLINT_INDENT=" " for four spaces, for example. See also this answer on StackOverflow. – Neftas Dec 15 '15 at 11:23

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.