vimtricks.wiki Concise Vim tricks, one at a time.

How do I copy the word under the cursor regardless of cursor position within it?

Answer

yiw

Explanation

How it works

The command yiw yanks (copies) the inner word under the cursor. It is composed of:

  • y the yank operator.
  • iw the inner word text object.

The key advantage of yiw over yw is that yiw copies the entire word regardless of where your cursor is positioned within it. With yw, only the text from the cursor to the end of the word is yanked. With yiw, the full word is always captured.

The inner word text object selects the word itself without any surrounding whitespace. If you want to include the trailing whitespace, use yaw (yank around word) instead.

Example

Consider this line with the cursor on the r in world:

hello world today
         ^  (cursor here)
  • yw yanks only rld (from cursor to end of word).
  • yiw yanks the complete word world.
  • yaw yanks world (the word plus the trailing space).

After yanking with yiw, you can paste the word anywhere with p or P.

Common patterns

The iw text object is one of the most frequently used text objects in Vim. Here are some common operator combinations:

  • yiw yank the word (copy it).
  • diw delete the word.
  • ciw change the word (delete it and enter insert mode).
  • viw visually select the word.
  • guiw lowercase the word.
  • gUiw uppercase the word.

All of these work the same way: they operate on the complete word under the cursor, no matter where the cursor sits within the word.

Next

How do you yank a single word into a named register?