Vim 101: Efficient HTML Editing with Text Objects

Alex R. Young
usevim
Published in
2 min readMar 31, 2013

If you’re working with XML or HTML, then the at and it text objects are useful. You can remember at with the mnemonic "a tag block", and it as "inner tag block". The difference is that at includes the tags.

Consider the following example:

<p><a href="http://example.com/1">This is a link</a> and <em>this is an emphasis</em>.
<a href="http://example.com/2">This is another link</a>, which points to another page.</p>

If I position the cursor anywhere inside the <em> tags and type dat, it'll remove the text and tags, because it means "delete a tag block":

<p><a href="http://example.com/1">This is a link</a> and .
<a href="http://example.com/2">This is another link</a>, which points to another page.</p>

What’s probably more useful is replacing the text inside the <em>. Typing dit will delete the inner tag block, meaning the text content in this case:

<p><a href="http://example.com/1">This is a link</a> and <em></em>.
<a href="http://example.com/2">This is another link</a>, which points to another page.</p>

In most cases you don’t want to just delete the text, you want to change it. That’s where the “change” operator comes in handy. Rather than typing dit, cit is more useful because it'll leave the editor in Insert mode:

Editing text content using cit.

If I wanted to change the inner text of that anchor tag, cit would even work if the cursor was inside the href attribute, or the tag itself.

Changing inner tags from inside an element.

That’s the main difference between movement commands and text objects: movements (with operators) apply from the cursor to the point the cursor will move to, while objects are less dependent on cursor location.

Another common HTML editing task is changing the text within quotes. Vim has text objects that are perfect for this task: a", a', i", and i'. If I moved the cursor inside of of the href attributes and typed ci", the URL would disappear and Vim would enter Insert mode so a new URL can be entered.

Sometimes you want to change the tag to another element. If I wanted to change <em> to <strong>, then I could move the cursor to the tag and type ci>.

--

--