Bin Chen
Bin Chen

Reputation: 63369

How can I find the closing HTML tag quickly in Vim?

Just like editing C source files, I can press % to get the closing } for the current cursor's {.

How can I do this when editing HTML files? Are there any shortcuts?

To be clear, I want:

<html>
</html>

When the cursor moves to <html>, I want to press a key so that the cursor will jump to </html>.

Upvotes: 23

Views: 10767

Answers (5)

coderofsalvation
coderofsalvation

Reputation: 1803

I could not get the above working, so here's my attempt in my .vimrc :)

imap <expr> > getline('.')[col('.')-2] !~# '\s' ? '><Esc>bvwy/><CR>a</<Esc>p<Esc>bba' : '>'

it's a conditional mapping which ignores html-expansion if there's characters preceeding > (for example: if foo > 3 gets ignored)

What I like about this mapping is that it's filetype-agnostic (which is handy in case of writing html inside a js-file e.g.)

Upvotes: 0

png
png

Reputation: 6580

MatchTagAlways is a plugin that always highlights the XML/HTML tags that enclose your cursor location.

https://github.com/Valloric/MatchTagAlways

Upvotes: 0

kenorb
kenorb

Reputation: 166881

You can jump between tags using visual operators, in example:

  1. Place the cursor on the tag.
  2. Enter visual mode by pressing v.
  3. Select the outer tag block by pressing a+t or i+t for inner tag block.

Your cursor should jump forward to the matching closing html/xml tag. To jump backwards from closing tag, press o or O to jump to opposite tag.

Now you can either exit visual by pressing Esc, change it by c or copy by y.


To record that action into register, press qq to start recording, perform tag jump as above (including Esc), press q to finish. Then to invoke jump, press @q.


See more help at :help visual-operators or :help v_it:

at a <tag> </tag> block (with tags)

it inner <tag> </tag> block


Alternatively use plugin such as matchit.vim (See: Using % in languages without curly braces).


See also:

Upvotes: 31

Nick Knowlson
Nick Knowlson

Reputation: 7426

I have had problems with this is the past, even with the matchit plugin. The way I solved it was to modify b:match_words on xml-type files. Here is the relevant section from my .vimrc:

  autocmd FileType html let b:match_words = '<\(\w\w*\):</\1,{:}'
  autocmd FileType xhtml let b:match_words = '<\(\w\w*\):</\1,{:}'
  autocmd FileType xml let b:match_words = '<\(\w\w*\):</\1,{:}'

Try it out, see if it helps any.

Upvotes: 6

jmans
jmans

Reputation: 5658

You should be able to do this with the matchit plugin by typing % when your mouse is on the opening tag.

http://www.vim.org/scripts/script.php?script_id=39

Upvotes: 15

Related Questions