I am learning Vim but I thought this was a simple task but I cannot get it to work. I have browser SO but the solutions are not working for me.
I am trying to correc
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 vim, use an autocommand to set it.
autocommand from a comment below
au FileType xml setlocal equalprg=xmllint\ --format\ --recover\ -\ 2>/dev/null
Short answer: Turn on matchit.vim. You can add packadd matchit to your .vimrc, or use vim-sensible, which enables it by default.
Long answer: I have tried many strategies to auto-indent XML in Vim, including the xmllint approach discussed on the Vim wiki. The problem with xmllint (and the same approach with other external CLI tools such as xmlformat and tidy, too) is that they all insist on squeezing out blank newlines. If all you want is to indent your XML, without removing blank lines, comments and/or other intentional formatting, then xmllint is not the best choice.
It turns out that Vim's equals (=) command already supports XML, as long as the matchit.vim script is enabled. One super easy way to enable it is to adopt tpope's vim-sensible. Another is to add packadd matchit to your .vimrc. Then, XML formatting will "just work" out of the box.
Jesse Hogan's answer is good, but I'd rather more simple answer:
While you are in vim and your XML file is opened, in normal mode write this:
:%!xmllint --format %
then press Enter. All of your XML file will be formatted.
remember you should have installed xmllint before.