Fix indentation in the whole fileStart in the top of a file (to get there, press gg anywhere in the file.). Then press =G , and Vim will fix the indentation in the whole file. If you don't start in the beginning of the file, it will fix indentation from current line to the bottom of file.
Indent by two spaces per indentation level. Use all-lowercase for elements and attributes. Don't leave trailing spaces at the end of a line (except as needed for Markdown).
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.
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>
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.
As tylerl explains above, set the following:
:filetype indent on
:set filetype=html
:set smartindent
However, note that in vim 7.4 the HTML tags html
, head
, body
, and some others are not indented by default. This makes sense, as nearly all content in an HTML file falls under those tags. If you really want to, you can get those tags to be indented like so:
:let g:html_indent_inctags = "html,body,head,tbody"
See "HTML indenting not working in compiled Vim 7.4, any ideas?" and "alternative html indent script" for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With