How do I tidy up an HTML file's indentation in VI?

后端 未结 11 1744
庸人自扰
庸人自扰 2020-11-29 15:02

How do I fix the indentation of his huge html files which was all messed up?

I tried the usual \"gg=G command, which is what I use to fix the indentation of code fil

相关标签:
11条回答
  • 2020-11-29 15:33

    The main problem using the smart indentation is that if the XML (or HTML) sits on one line as it may end up coming back from a curl request then gg=G won't do the trick. Instead I have just experienced a good indentation using tidy directly called from VI:

    :!tidy -mi -xml -wrap 0 %
    

    This basically tells VI to call tidy to cleanup an XML file not wrapping the lines to make them fit on the default 68 characters wide lines. I processed a large 29MB XML file and it took 5 or 6 seconds. I guess for an HTML file the command should therefore be:

    :!tidy -mi -html -wrap 0 %
    

    As mentioned in comments, tidy is a basic tool which you could find on many base Linux / MacOS systems. Here is the projet's page in case you wish you had it but don't: HTML Tidy.

    0 讨论(0)
  • 2020-11-29 15:40

    I use this script: https://github.com/maksimr/vim-jsbeautify

    In the above link you have all the info:

    1. Install
    2. Configure (copy from the first example)
    3. Run :call HtmlBeautify()

    Does the job beautifully!

    0 讨论(0)
  • 2020-11-29 15:41

    Have you tried using the HTML indentation script on the Vim site?

    • http://www.vim.org/scripts/script.php?script_id=2075
    0 讨论(0)
  • 2020-11-29 15:45

    You can integrate both tidy and html-beautify automatically by installing the plugin vim-autoformat. After that, you can execute whichever formatter is installed with a single keystroke.

    0 讨论(0)
  • 2020-11-29 15:47

    With filetype indent on inside my .vimrc, Vim indents HTML files quite nicely.

    Simple example with a shiftwidth of 2:

    <html>
      <body>
        <p>
        text
        </p>
      </body>
    </html>
    
    0 讨论(0)
  • 2020-11-29 15:48

    There's several things that all need to be in place. Just to summarize them all in one location:

    Set the following option:

    :filetype indent on
    :set filetype=html           # abbrev -  :set ft=html
    :set smartindent             # abbrev -  :set si
    

    Then either move the cursor to the top of the file and indent to the end: gg =G
    Or select the desired text to indent and hit = to indent it.

    0 讨论(0)
提交回复
热议问题