Vim Tips Wiki
Register
Advertisement
Tip 1366 Printable Monobook Previous Next

created October 20, 2006 · complexity intermediate · author Cory · version n/a


Add this to your vimrc so you can type :PrettyXML and automatically pretty-format XML. Requires the command 'xmllint' in your PATH.

Note that this ignores significant whitespace! The result will be more readable, but it may not be semantically identical. I use this to read badly-formatted XML documents, not to save them.

fu! DoPrettyXML()
  " save the filetype so we can restore it later
  let l:origft = &ft
  set ft=
  " delete the xml header if it exists. This will
  " permit us to surround the document with fake tags
  " without creating invalid xml.
  1,1s/<?xml .*?>//
  " insert fake tags around the entire document.
  " This will permit us to pretty-format excerpts of
  " XML that may contain multiple top-level elements.
  1
  exe "norm! O<PrettyXML>"
  exe "norm! Go</PrettyXML>"
  silent %!xmllint --format -
  " xmllint will insert an <?xml?> header. it's easy enough to delete
  " if you don't want it.
  " delete the fake tags
  2
  exe "norm ddGdd"
  " restore the 'normal' indentation, which is one extra level
  " too deep due to the extra tags we wrapped around the document.
  silent %<
  " back to home
  1
  " restore the filetype
  exe "set ft=" . l:origft
endfu
command! PrettyXML call DoPrettyXML()

Comments

I tried it on http://www.hab.de/bibliothek/wdb/emblematica/emblemsample.xml

Buffer was empty after that.


The following is my solution. gvim 7.0 on Windows XP. Ruby must be installed.

# download xmlformat
# copy xmlformat.rb to a folder, d:\bin for exmaple
# open the xml document to be formated in Vim
# type command
:% !ruby d:\bin\xmlformat.rb

From Automatically indent an XML file using XSLT comes this solution, which I prefer:

:%s/></>\r</g
:0
=:$

Hi, when I run this script I always get:

Error detected while processing function DoPrettyXML:
line    7:

Any ideas?


Advertisement