Pretty format XML in Vim
Vim lets you set equalprg option for each filetype. From Vim docs:
External program to use for "=" command. When this option is empty the internal formatting functions are used; either 'lisp', 'cindent' or 'indentexpr'. When Vim was compiled without internal formatting, the "indent" program is used. ...
Install xmllint
command (on Unix-like systems it comes with libxml
package). Then add following line to you .vimrc:
au FileType xml setlocal equalprg=xmllint\ --format\ --recover\ -\ 2>/dev/null
Now, to pretty format your XML just type gg=G
.
Written by Marcin Kulik
Related protips
4 Responses
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/52376/2aaae7041aca85da930bcaf14d6768d2.jpeg)
Why not gg:=$
? :-)
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/21446/IMG_20180309_172925_-_Cropped_and_Cleaned_and_Flipped_and_Stylized__Square_Crop_Optimized_.jpg)
@jan0sch
gg=G
is one less keystroke, and actually doesn't require holding shift twice (for the colon and dollar sign). :)
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/52376/2aaae7041aca85da930bcaf14d6768d2.jpeg)
@rican7
I meant the whole setup. As long as i've used vim it always indented xml correctly without having to setup xmllint
. Or am I missing something? :-?
![](https://coderwall-assets-0.s3.amazonaws.com/uploads/user/avatar/21446/IMG_20180309_172925_-_Cropped_and_Cleaned_and_Flipped_and_Stylized__Square_Crop_Optimized_.jpg)
@jan0sch
Yea, I'm honestly not sure what the benefit is here. Maybe it has support for more modern styling or attributes. Otherwise, not sure. :/