How do I select an HTML tag and its contents in Vim?
Answer
vat
Explanation
The vat command visually selects the nearest enclosing HTML or XML tag and all of its contents, including the opening and closing tags themselves. It combines v (visual mode) with the at ("a tag") text object.
How it works
venters visual modeatis the "a tag" text object — it selects the opening tag, the closing tag, and everything in between
Example
Given the text with the cursor anywhere inside the <div> tag:
<div class="container">
<p>Hello, world!</p>
</div>
Pressing vat selects the entire block — from <div class="container"> through </div>, including the tags themselves and all inner content.
Compared to vit
vitselects the inner tag — only the content between the opening and closing tags, excluding the tags themselvesvatselects around the tag — the content plus both the opening and closing tags
For the HTML <p>Hello, world!</p>:
vitselectsHello, world!vatselects<p>Hello, world!</p>
Tips
- Use
datto delete the tag and its contents in one stroke - Use
catto change (replace) the entire tag and its contents - Use
yatto yank the full tag with its contents - Pressing
atmultiple times in visual mode expands the selection to the next enclosing tag — pressvatatatto select increasingly outer tags - Works with self-closing tags and nested tags — Vim finds the nearest matching pair
- Combine with
ditto delete only the content while preserving the tags themselves