Despite not agreeing with all of it, “Just Use Sublime Text” (an invective against Vim — or, more accurately, against recommending Vim to anyone who isn’t already indoctrinated by it) by Andrew Ray is an interesting read. The section dealing with indenting in particular struck a chord with me:

Paste this into an empty buffer:

<div>
<p>
<span>foo</span>
</p>
</div>

:set ft=html and then gg=G. Let me know what you get. In all seriousness, never, ever tell me what you get.

As I said in a tweet, what I got didn’t offend me too much. But many people would argue that the <span> tag should be indented inside the <p> tag. I’d probably do this myself, actually — and there have been aspects of Vim’s indenting that irk me. So I set about finding a solution.

My first attempt was through othree‘s html5.vim plugin. Out of the box, however, this resulted in some truly weird indenting behavior:

I don’t know why this behaves this way, or whether it can be fixed, but I didn’t plan to find out. Vim plugins need to impress me pretty quickly before I decide to invest time in them.

Finally, after some Google searching, I stumbled across an answer on Stack Overflow. Vim’s native HTML indent file allows for adding or removing html tags from a list of those tags whose children ought to be indented. In the example given by Ray, a line break after a <p> didn’t result in an increased indent. The solution is to add the p tag to this list:

:let g:html_indent_tags .= '\|p'

This can be done manually after the html filetype is set, or can be set universally by placing that line (sans the initial colon) in ~/.vim/after/indent/html.vim. Despite the apparent obscurity of this option, it proves to be pretty popular in people’s dotfiles on GitHub.

The shipped html indent file was last updated in June, 2013, and still doesn’t include p as an “indenting” tag. It seems to me that this is intentional, rather than a “bug” in Vim’s html indenting. Somebody has made the choice not to include p among that list, which, while you may disagree with it, is a valid preference.

Leave a Comment or Subscribe