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

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

  • viw visually selects the inner word under the cursor
  • p in 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 second viwp elsewhere 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 use viw"ap — the "0 (yank) register also preserves the original yank: viw"0p
  • Use viw"0p when you want to paste-over multiple times without the register changing each time
  • This works with any visual selection, not just iw: vi"p replaces the text inside quotes, Vp replaces an entire line, vi(p replaces 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 dwwP or the classic dawwP (though viwp is more flexible for non-adjacent swaps)

Next

How do I edit multiple lines at once using multiple cursors in Vim?