How do I swap a word with the contents of a register using visual mode?
Answer
viwp
Explanation
The viwp command visually selects the word under the cursor and replaces it with the contents of the unnamed register (your last yank or delete). The replaced word then goes into the unnamed register, effectively swapping the register contents with the word in the buffer. This is Vim's paste-over-selection trick and is essential for quick text swaps.
How it works
viwvisually selects the inner word under the cursorpin visual mode replaces the selected text with the contents of the unnamed register- The text that was selected (and removed) is placed into the unnamed register, replacing what was there before
- This means the old register contents go into the buffer, and the old buffer contents go into the register — a swap
Example
Given the text:
foo bar baz
Yank foo with yiw, then move the cursor to baz and press viwp:
foo bar foo
Now the unnamed register contains baz. Move back to the first foo and press viwp again:
baz bar foo
The two words have been swapped.
Tips
- The main pitfall: after
viwp, the unnamed register now holds the overwritten word, so a secondviwpelsewhere swaps again — this is a feature, not a bug, when you want to swap two words - To paste the same text repeatedly without losing it, yank into a named register first (
"ayiw) and useviw"ap— the"0(yank) register also preserves the original yank:viw"0p - Use
viw"0pwhen you want to paste-over multiple times without the register changing each time - This works with any visual selection, not just
iw:vi"preplaces the text inside quotes,Vpreplaces an entire line,vi(preplaces inside parentheses - Combine with the dot command: after
viwp, pressing.on another word replaces it with whatever is now in the register (the previously overwritten text) - For swapping two adjacent words without visual mode, use
dwwPor the classicdawwP(thoughviwpis more flexible for non-adjacent swaps)