How do I select or operate on the content of an HTML or XML tag using text objects?
Answer
it and at
Explanation
Vim provides two built-in text objects for HTML and XML tags: it (inner tag) and at (a tag). Like all Vim text objects, they work with any operator — d, c, y, v, =, <, >, and more — making them far more efficient than manually positioning the cursor and visually selecting.
How it works
itselects the text inside the tag, excluding the opening and closing tags themselvesatselects the text plus the surrounding opening and closing tags- The cursor can be anywhere inside the tag — at the start, middle, or end of the content
- Nested tags work as expected: Vim targets the innermost tag containing the cursor
Example
Given the buffer:
<p>Hello <em>world</em> today</p>
With the cursor inside <em>world</em>:
vit→ selectsworldvat→ selects<em>world</em>dit→ deletesworld, leaving<em></em>dat→ deletes<em>world</em>entirely, leaving<p>Hello today</p>
Tips
- Use
citto replace tag contents: delete the contents and drop into Insert mode in one stroke - Use
yatto yank an entire tag with its content — useful before pasting or wrapping - Combine with counts:
2datcan delete the outer tag after the inner one is gone - These text objects require filetype detection to be active. Run
:filetype detector ensurefiletype plugin onis in your config if they are not working