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

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

  1. Position cursor on word A and type yiw — yanks word A into "" and "0
  2. Navigate to word B and type viwp — selects word B, pastes word A over it; word B is now in ""
  3. 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"p swaps quoted strings, vi(p swaps parenthesized groups
  • The second viwp must 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: qqyiwwviwpbviwpq and replay with @q

Next

How do I add a visual indicator at the start of soft-wrapped continuation lines to tell them apart from real line starts?