Text objects: iw, i", a(, it

Vim · Practical · 10 min

Text objects make edits like 'change inside quotes' one fluent command that also repeats cleanly with dot.

After an operator (or in Visual mode) you can use a text object instead of a motion. A text object selects a whole thing around the cursor, regardless of where in it you are. They come in two flavours:

  • i = inner: just the contents.
  • a = a / around: the contents plus the surrounding delimiters or whitespace.

The common objects:

  • iw / aw a word, iW / aW a WORD
  • is / as a sentence, ip / ap a paragraph
  • i" i' ` i `` quoted strings
  • i( (or ib), i[, i{ (or iB), i< brackets
  • it / at an XML/HTML tag's contents or whole element

So with the cursor anywhere inside "hello world", ci" deletes hello world and drops you into Insert mode between the quotes. da( deletes a parenthesised expression including the parentheses; yi{ yanks a function body; dap deletes a paragraph and the blank line after it.

For quotes, Vim even searches forward on the line: ci" works when the cursor is before the first quote. Because a text object does not depend on cursor position, edits made with them are perfect for the dot command: ciwnew<Esc> on one word, then * and . on the next.

Example

" cursor anywhere inside: print("hello world")
ci"     " -> print("|")       change the string contents
da(     " -> print            delete the parens and contents
yi(     " yank "hello world" with its quotes
diw     " delete the word under the cursor
cit     " <b>bold</b> -> <b>|</b>  change tag contents
dap     " delete the paragraph plus trailing blank line
vi{     " visually select a block's contents

Remember

  • i = inside, a = around (includes delimiters/whitespace)
  • w, s, p, quotes, brackets and t (tags) are all objects
  • Text-object edits repeat well with .

Watch out for

  • Using cw in the middle of a word only changes from the cursor onward; ciw changes the whole word.

Check yourself

  1. Cursor is on `x` in `f(a, x)`. What does `di(` leave?
  2. What is the difference between `daw` and `diw`?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: vimhelp.org/motion.txt.html#text-objects