How do I swap two words in Vim using visual paste without any plugins?
Answer
yiw{nav}viwp{nav}viwp
Explanation
When you paste over a visual selection in Vim, the displaced text is moved into the unnamed register "". This behavior enables a clean two-word swap workflow using only built-in registers: yank the first word, paste it over the second (which sends the second word to ""), then paste the second word back over where the first was.
How it works
- Position cursor on word A and type
yiw— yanks word A into""and"0 - Navigate to word B and type
viwp— selects word B, pastes word A over it; word B is now in"" - Navigate back to word A (now unchanged) and type
viwp— selects word A, pastes word B from""over it
The key insight: pasting in visual mode is a swap, not a one-way copy. Each viwp exchanges the selection with the register.
Example
Buffer: The quick brown fox
↑ cursor on "quick"
yiw → yank "quick"
w → move to "brown"
viwp → paste "quick" over "brown"; "brown" is now in ""
b → move back to "quick" (now shows "quick" still)
viwp → paste "brown" over "quick"
Result: The brown quick fox
Tips
- This technique works with any text objects, not just words:
vi"pswaps quoted strings,vi(pswaps parenthesized groups - The second
viwpmust happen before any other yank or delete, since""holds word B only until it is overwritten - For non-adjacent words, record this as a macro:
qqyiwwviwpbviwpqand replay with@q