125

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.

0

11 Answers 11

78

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 :)

7
  • 2
    Can this plugin auto-close tags when '</' is typed? Or just insert closing tag with some keystroke? Sometimes you delete the closing tag and want it inserted afterwards...
    – bzx
    Jun 24, 2011 at 23:16
  • 9
    I don't like this plugin because it doesn't provide an easy way to get your cursor past of the generated tag. For example, if you want to write "Have a <b>nice</b> day", you start off by typing "Have a <b>nice", which renders as "Have a <b>nice|</b>". You then need to either right-arrow across or exit insert mode to continue with the rest of the sentence. That's why a solution where you press a key to insert the end tag is better.
    – exclipy
    Oct 9, 2011 at 6:00
  • 2
    @exclipy Vim has plenty of built-in ways to do this. Try the the 'E', 'f', and 'A' commands for starters.
    – user456584
    Nov 14, 2013 at 21:10
  • 3
    I installed xmledit plugin with git clone https://github.com/sukima/xmledit.git ~/.vim/bundle/xmledit. But it only works when editing .xml files. When the file ext is .html or .htm, it doesn't works.
    – Leo
    Nov 27, 2014 at 5:58
  • 3
    @Chad currently, the my solution was to copy paste the file in the same directory exact rename it to "html.vim" so that it will effect HTML files as well. Now, I have two of the exact same files in ~/.vim/ftplugin (xml.vim and html.vim).
    – SilentDev
    Jun 11, 2015 at 19:55
58

I like minimal things,

imap ,/ </<C-X><C-O>
9
  • 4
    What does <C-X><C-O> do? It doesn't do anything for me.
    – exclipy
    Oct 9, 2011 at 6:01
  • 9
    There are cases where one would like to write ",/", so I'd rather user a different shortcut. Another detail is that the omni-completion should be closed, not waiting for additional input. So: imap <silent> <C-c> </<C-X><C-O><C-X>
    – user699082
    Dec 12, 2012 at 18:18
  • 1
    Very cool. Also added <Esc>F<i to the end of this so it puts the cursor back inside the tag.
    – mVChr
    May 4, 2017 at 19:40
  • to use this command be in insert mode, then hit ,/ to close the tag
    – thedanotto
    Aug 7, 2017 at 4:09
  • 3
    The above solution has a lot of upvotes but it lacks explanation especially for a beginner like me. How does it work and how does one use it? May 4, 2020 at 4:58
53

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.

2
38

Check this out..

closetag.vim

Functions and mappings to close open HTML/XML tags

https://www.vim.org/scripts/script.php?script_id=13

I use something similar.

1
  • I have installed this. It doesn't completed close tag automatically.What is the shortkey? I try Ctrl-_, but this make small font of my terminal.
    – alhelal
    Apr 3, 2018 at 1:25
24

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>
3
  • Thank you sooooo much! This is cooler than anything I've seen before, not only Vim but among any other editors! Super!
    – Chris
    Sep 6, 2011 at 7:12
  • This is a great plugin Feb 10, 2017 at 19:09
  • This plugin evolved from zen-coding. The latter is now known as emmet and has a slightly larger feature set.
    – chb
    Aug 16, 2018 at 7:46
19

There is also a zencoding vim plugin: https://github.com/mattn/zencoding-vim

tutorial: https://github.com/mattn/zencoding-vim/blob/master/TUTORIAL


Update: this now called Emmet: http://emmet.io/


An excerpt from the tutorial:

1. Expand Abbreviation

  Type abbreviation as 'div>p#foo$*3>a' and type '<c-y>,'.
  ---------------------
  <div>
      <p id="foo1">
          <a href=""></a>
      </p>
      <p id="foo2">
          <a href=""></a>
      </p>
      <p id="foo3">
          <a href=""></a>
      </p>
  </div>
  ---------------------

2. Wrap with Abbreviation

  Write as below.
  ---------------------
  test1
  test2
  test3
  ---------------------
  Then do visual select(line wize) and type '<c-y>,'.
  If you request 'Tag:', then type 'ul>li*'.
  ---------------------
  <ul>
      <li>test1</li>
      <li>test2</li>
      <li>test3</li>
  </ul>
  ---------------------

...

12. Make anchor from URL

  Move cursor to URL
  ---------------------
  http://www.google.com/
  ---------------------
  Type '<c-y>a'
  ---------------------
  <a href="http://www.google.com/">Google</a>
  ---------------------
1
  • whoa, is that by the creator of ruby?
    – tjklemz
    Jul 11, 2013 at 22:29
16

Mapping

I like to have my block tags (as opposed to inline) closed immediately and with as simple a shortcut as possible (I like to avoid special keys like CTRL where possible, though I do use closetag.vim to close my inline tags.) I like to use this shortcut when starting blocks of tags (thanks to @kimilhee; this is a take-off of his answer):

inoremap ><Tab> ><Esc>F<lyt>o</<C-r>"><Esc>O<Space>

Sample usage

Type—

<p>[Tab]

Result—

<p>
 |
</p>

where | indicates cursor position.

Explanation

  • inoremap means create the mapping in insert mode
  • ><Tab> means a closing angle brackets and a tab character; this is what is matched
  • ><Esc> means end the first tag and escape from insert into normal mode
  • F< means find the last opening angle bracket
  • l means move the cursor right one (don't copy the opening angle bracket)
  • yt> means yank from cursor position to up until before the next closing angle bracket (i.e. copy tags contents)
  • o</ means start new line in insert mode and add an opening angle bracket and slash
  • <C-r>" means paste in insert mode from the default register (")
  • ><Esc> means close the closing tag and escape from insert mode
  • O<Space> means start a new line in insert mode above the cursor and insert a space
4
  • @wds Wow, yeah, I never thought about the fact that l meant "right" and not "left," haha... what a funny error. What did you think of my post? I noticed you didn't upvote. Aug 23, 2012 at 20:25
  • Nice for sure. I've taken to using the xml.vim plugin recently (it does work quite nicely). I would suggest adding it to your .vimrc with a filetype-specific autocommand, i.e.: au filetype html inoremap <buffer> ...
    – wds
    Aug 24, 2012 at 12:31
  • 1
    Finally an Autoclose command that works exactly as it should --simply!
    – cnp
    Jan 15, 2015 at 1:11
  • 1
    I like to keep my cursor in between tags. So I modified it to suit my need. inoremap ><Tab> ><Esc>F<lyt>o</<C-r>"><Esc>kJxi I remove 0<Space> and added kJxi. Go 1 step up, concatenate two lines, remove one character then go into insert mode.
    – Samundra
    Jun 19, 2020 at 7:31
11

Check out vim-closetag

It's a really simple script (also available as a vundle plugin) that closes (X)HTML tags for you. From it's README:

If this is the current content:

<table|

Now you press >, the content will be:

<table>|</table>

And now if you press > again, the content will be:

<table>
   |
</table>

Note: | is the cursor here

7

Here is yet another simple solution based on easily foundable Web writing:

  1. Auto closing an HTML tag

    :iabbrev </ </<C-X><C-O>

  2. Turning completion on

    autocmd FileType xml set omnifunc=xmlcomplete#CompleteTags

2
  • 1
    Awesome response!!! with no plugin!!! (2nd item has linkrot) still perhaps best answer of all, because it seems quicker to modify the .vimrc rather than handling plugins. Plus most minimalist response
    – nilon
    Jul 12, 2017 at 15:07
  • This adds space after closed tag :( Apr 24, 2018 at 9:44
6

allml (now Ragtag ) and Omni-completion ( <C-X><C-O> ) doesn't work in a file like .py or .java.

if you want to close tag automatically in those file, you can map like this.

imap <C-j> <ESC>F<lyt>$a</^R">

( ^R is Contrl+R : you can type like this Control+v and then Control+r )

(| is cursor position ) now if you type..

<p>abcde|

and type ^j

then it close the tag like this..

<p>abcde</p>|

1
  • with imap <C-j> <ESC>mfF<lyt>`fa</<C-R>"> the clonsing tag is where the cursor was when you typed ^j instead of the end of line ($)
    – Pietro
    Aug 7, 2014 at 12:45
5

Building off of the excellent answer by @KeithPinson (sorry, not enough reputation points to comment on your answer yet), this alternative will prevent the autocomplete from copying anything extra that might be inside the html tag (e.g. classes, ids, etc...) but should not be copied to the closing tag.

UPDATE I have updated my response to work with filename.html.erb files.
I noticed my original response didn't work in files commonly used in Rails views, like some_file.html.erb when I was using embedded ruby (e.g. <p>Year: <%= @year %><p>). The code below will work with .html.erb files.

inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwo</<C-r>"><Esc>O

Sample usage

Type:

<div class="foo">[Tab]

Result:

<div class="foo">
  |
<div>

where | indicates cursor position

And as an example of adding the closing tag inline instead of block style:

inoremap ><Tab> ><Esc>?<[a-z]<CR>lyiwh/[^%]><CR>la</<C-r>"><Esc>F<i

Sample usage

Type:

<div class="foo">[Tab]

Result:

<div class="foo">|<div>

where | indicates cursor position

It's true that both of the above examples rely on >[Tab] to signal a closing tag (meaning you would have to choose either inline or block style). Personally, I use the block-style with >[Tab] and the inline-style with >>.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.