How to jump between matching tags (such as <div>
, <span>
, etc.) when editing HTML/XHTML/XML documents similarly as % is used to jump between matching parentheses?
4 Answers
Vim ships with a macro called matchit that does this for you; all you need to do is activate it with runtime macros/matchit.vim
in your vimrc. This will enable you to jump from, eg, a <div>
to its </div>
. Note that your cursor will have to be inside the angle brackets; if you're on the angle brackets, % will jump from one bracket to the other as normal.
-
4I had to
set filetype=html
for my php file. Inspired by stackoverflow.com/questions/7281459/…– aswineCommented Dec 6, 2019 at 15:44
You can jump between tags using visual operators, for example:
- Place the cursor on the tag.
- Enter visual mode by pressing v.
- 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 or surround.vim.
See also:
- Using % in languages without curly braces
- Jump to matching XML tags in Vim at stackoverflow SE
- How can I find the close html tag quickly in vim? at stackoverflow SE
- Navigating HTML tags in Vim at stackoverflow SE
- How to navigate between begin and end html tag? at superuser SE
- VIM jump from one xml tag to the closing one at Unix SE
- How can I select an html tag's content in Vim? at superuser SE
The xmledit
(http://vimawesome.com/plugin/xmledit) plugin allows to jump between open and close tags using
- <localleader>%
Often <localleader> will be \, so you can jump with
- \%
NOTE: Unlike matchit
, you don't have to put your cursor inside the tag. Placing it right on the <
or >
is perfectly fine for the xmledit
plugin. :)
NOTE 2: A drawback here is, that you can't use it in the visual mode. But this isn't a big deal, since you can always select the entire tag with at.
A relatively new and popular plugin vim-matchup provides quite extensive support as long as there is syntax highlighting for the language, HTML included.
>
it will work like before, if you're on thediv
it will work like you want).