Pretty-printing in vim

Vim’s ability to call external process, allows you to quickly integrate some Python code snippets to do some work for you, e.g., for pretty-printing JSON and XML. Of course, for this to work, your Python 3 interpreter needs to be on the PATH variable. The following snippets only rely on the standard libraries, so no need to install anything else.

By adding the following lines to your $HOME/.vimrc you get the commands :FormatJSON and :FormatXML to pretty-print the current buffer:

" pretty print json
com! FormatJSON :%!python3 -c "import json, sys; obj = json.load(sys.stdin); print(json.dumps(obj, indent=2, sort_keys=True))"
nnoremap = :FormatJSON<Cr>

" pretty print xml
com! FormatXML :set tabstop=2 | :%!python3 -c "import xml.dom.minidom, sys, os; dom = xml.dom.minidom.parse(sys.stdin); pretty_xml = dom.toprettyxml(); pretty_xml = os.linesep.join([s for s in pretty_xml.splitlines() if s.strip()]); print(pretty_xml)"
nnoremap = :FormatXML<Cr>

These commands were inspired by: