Vim indent xml file

后端 未结 9 1763
北恋
北恋 2020-12-07 08:05

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

相关标签:
9条回答
  • 2020-12-07 08:28

    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
    
    0 讨论(0)
  • 2020-12-07 08:30

    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.

    0 讨论(0)
  • 2020-12-07 08:34

    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.

    0 讨论(0)
自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题