When typing an html document, you can automatically close html tags using omni completion. For example, you may type
example then press Ctrl-x Ctrl-o to automatically finish typing the tag so the text reads example.With the following abbreviation in your vimrc, you can simplify this process:
:iabbrev
With this abbreviation, you can simply type then press Space to automatically complete the tag.
You may find that sometimes you want to type without invoking the abbreviation. If that happens a lot, you may prefer the following abbreviation so you have to enter / to invoke tag completion:
:iabbrev /
Also you can remap Ctrl-x Ctrl-o to Ctrl-Space using:
:imap
This autocmd and insert mode mappings will cause > to auto-complete the tag in insert mode, > to auto-complete and put your cursor on an indented new line, and > to cancel autocompleteion for those special times.
function s:CompleteTags()
inoremap > >:startinsert!?
inoremap > >
inoremap > >:startinsert!?$
endfunction
autocmd BufRead,BufNewFile *.html,*.js,*.xml call s:CompleteTags()
I suspect the abbreviation is not very helpful in practice because it won't work if you type, for example, abc (it only works if you enter insert mode to type the abbreviation, or if the abbreviation follows whitespace. Perhaps a mapping like:inoremap
might be more helpful? You would press F8 to add a closing tag while in insert mode. JohnBeckett 10:25, April 26, 2010 (UTC)
Hmm, but it would work if you end your tag on a new line by itself. I agree this is not very useful though for the reason you give. To stay more in the spirit of the original, perhaps :inoremap / would be better? This would always fire when closing a tag of course, which could be annoying to some. --Fritzophrenic 13:54, April 26, 2010 (UTC)
Use instead to avoid conflicts (learn more about Leader key in ":help leader")--Devgutt28 (talk) 15:11, August 2, 2012 (UTC)
I know I'm a bit late to the party, but I added on to Fritzophrenic's version with :inoremap / ==gi so the new tag properly indents itself. == re-indents the current line (also moving the cursor), and gi returns the cursor to its location before the re-indent and enters insert mode. (September 2, 2017)