How can one close HTML tags in Vim quickly?

Viewed 63510

It's been a while since I've had to do any HTML-like code in Vim, but recently I came across this again. Say I'm writing some simple HTML:

<html><head><title>This is a title</title></head></html>

How do I write those closing tags for title, head and html down quickly? I feel like I'm missing some really simple way here that does not involve me going through writing them all down one by one.

Of course I can use CtrlP to autocomplete the individual tag names but what gets me on my laptop keyboard is actually getting the brackets and slash right.

11 Answers

I find using the xmledit plugin pretty useful. it adds two pieces of functionality:

  1. When you open a tag (e.g. type <p>), it expands the tag as soon as you type the closing > into <p></p> and places the cursor inside the tag in insert mode.
  2. If you then immediately type another > (e.g. you type <p>>), it expands that into

    <p>

    </p>

and places the cursor inside the tag, indented once, in insert mode.

The xml vim plugin adds code folding and nested tag matching to these features.

Of course, you don't have to worry about closing tags at all if you write your HTML content in Markdown and use %! to filter your Vim buffer through the Markdown processor of your choice :)

I like minimal things,

imap ,/ </<C-X><C-O>

I find it more convinient to make vim write both opening and closing tag for me, instead of just the closing one. You can use excellent ragtag plugin by Tim Pope. Usage looks like this (let | mark cursor position) you type:

span|

press CTRL+x SPACE

and you get

<span>|</span>

You can also use CTRL+x ENTER instead of CTRL+x SPACE, and you get

<span>
|
</span>

Ragtag can do more than just it (eg. insert <%= stuff around this %> or DOCTYPE). You probably want to check out other plugins by author of ragtag, especially surround.

If you're doing anything elaborate, sparkup is very good.

An example from their site:

ul > li.item-$*3 expands to:

<ul>
    <li class="item-1"></li>
    <li class="item-2"></li>
    <li class="item-3"></li>
</ul>

with a <C-e>.

To do the example given in the question,

html > head > title{This is a title}

yields

<html>
  <head>
    <title>This is a title</title>
  </head>
</html>
Related