← back to latest

Change a word without aiming at its edges

NORMALciwChange a word without aiming at its edges

anatomy

c
Change. Deletes whatever the following motion covers and drops you into insert mode.
i
Inner. Acts on the contents of the object, leaving surroundings alone.
w
Word. The object itself. Cursor can sit anywhere inside it.

In the buffer

Before:

The quick brown fox jumps over the lazy dog.
       ^

After typing ciw and then slow:

The quick slow fox jumps over the lazy dog.
           ^

When you would reach for it

You are sitting somewhere inside a word you want to replace. Not at the beginning, not at the end. Just somewhere in the middle. The old way: figure out where you are, move to the start, delete to the end, enter insert mode. The new way: ciw, type the replacement, done.

This is the text object advantage. You describe the boundary by what it is, not by where the cursor happens to be.

Gotchas

  • ciw respects Vim’s definition of a word, which includes alphanumerics and underscores. Punctuation marks are not part of words. If you are sitting on punctuation, ciw will change only that punctuation sequence, not the adjacent word.
  • If the cursor is on whitespace, ciw changes the whitespace, not the surrounding words.
  • For programming contexts where you want to include dashes or other characters in the word boundary, consider caw (change a word including surrounding space) or configure iskeyword to adjust what counts as a word.

Variants

Change around a word (caw): Deletes the word and one adjacent space, then enters insert mode. Useful when you want to remove the word entirely without leaving awkward double spaces.

Before: The quick brown fox
             ^
After caw: The quick fox

Change inside a sentence (cis): Same principle, different boundary. Deletes everything inside the current sentence and enters insert mode.

Change inside quotes (ci"): Deletes everything between the nearest pair of double quotes and enters insert mode. The quotes remain.

Before: He said "hello world" and left.
                  ^
After ci" and typing 'goodbye': He said "goodbye" and left.

All text objects follow the same grammar: an operator (c, d, y) + a scope modifier (i for inner, a for around) + the object itself (w, s, ", (, {, etc.). Once you learn one, you know them all.

lineage

Text objects were not part of the original vi. They appeared in Vim 5.0 (1998) as a way to express scope without counting characters or reaching for the mouse.

-- INSERT --vim-hacks.com016-016-change-a-word-without-aiming.html
utf-81,1All