Vim Autocomplete HTML Tags

4.3
(35)

Vim has a built in library for autocompleting HTML tags, but it needs to be enabled to work. To enable it, we just have to create a FileType AutoCommand in our .vimrc file, telling Vim to enable the completion function when we are in an HTML file:

autocmd FileType html set omnifunc=htmlcomplete#CompleteTags

If you use other templating languages with different file types, you can add those after html separated by commas. Run :set filetype to see the filetype of a given file if you’re unsure. For example, .erb files from Ruby on Rails are typically type eruby so you’d want autocmd FileType html,eruby.

Once that is enabled, Vim autocompletes HTML tags when you run <ctrl-x><ctrl-o> after typing < inside one of the chosen file types.

Vim will even auto complete HTML doctype strings, arguably the most useful HTML tag to autocomplete, because who wants to type all that? There is also some built in context detection. For example, inside an <html> tag, Vim will show only body and head completion options.

In the video below I show a short demonstration of Vim HTML tag auto-completion. You can see that after I type < I press <ctrl-x> followed by <ctrl-o> and Vim provides an autocomplete popup up with the valid HTML tags for that context.

Be sure to check out our post on Vim file templates using skeleton files if you want to have boilerplate HTML generated automatically.

Can Vim autocomplete HTML tags?

Yes, Vim can auto complete HTML tags inside any file as long as you have the option enabled with the following: set omnifunc=htmlcomplete#CompleteTags

Why doesn't Vim autocomplete HTML by default?

Vim ships without language-specific features, such as HTML autocompletion, enabled because each user might be using different languages. This allows for optimal performance and experiencing, not showing you languages which you might not use.

Can I autocomplete other language keywords in Vim?

Yes! Vim can autocomplete many other languages. Depending on your version of Vim, different languages might be shipped with your version. Vim calls this omnicomplete and these omni complete functions are available for many languages like CSS, HTML, Javascript, PHP, Python, Ruby, and more. Here's a full list from the latest Vim.

How do I enable Vim HTML autocomplete?

To enable auto completion of HTML tags in Vim, put this in your .vimrc file: autocmd FileType html set omnifunc=htmlcomplete#CompleteTags

How useful was this tip?

Average rating 4.3 / 5. Vote count: 35

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

101 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts