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)
ywyanks onlyrld(from cursor to end of word).yiwyanks the complete wordworld.yawyanksworld(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:
yiwyank the word (copy it).diwdelete the word.ciwchange the word (delete it and enter insert mode).viwvisually select the word.guiwlowercase the word.gUiwuppercase 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.