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

How do I paste over a visual selection and automatically save the replaced text to a register?

Answer

{visual}p

Explanation

When you visually select text and press p, Vim replaces the selection with the contents of the default register and saves the replaced text into the unnamed register ". This two-way swap is one of Vim's most useful but frequently overlooked behaviors — it lets you exchange two pieces of text without any temporary marks or registers.

How it works

  1. Yank the text you want to put somewhere (yiw, y$, etc.)
  2. Visually select the text you want to replace
  3. Press p

Result:

  • The selection is replaced with the yanked text
  • The previously selected text is now in the unnamed register "

Example

foo bar baz

Yank foo with yiw. Then visually select baz (viw with cursor on baz). Press p:

foo bar foo

Now baz is in register " — press p again anywhere to place it.

Tips

  • To swap two words: yank word A, select word B, press p, move cursor to where A was and press P — but note the register now holds B
  • Use "0p instead of p to paste the last yanked text specifically, preserving register 0 through deletions and prior pastes
  • In line-wise visual mode (V), p replaces whole lines and puts the replaced lines into the register
  • To prevent the replacement from overwriting your yank register, paste from register 0: "0p (register 0 always holds the last explicit yank, not deletions)
  • Works with named registers too: "ap replaces the selection with register a and puts the old text in "

Next

How do I rename a variable across all case variants (snake_case, camelCase, MixedCase) at once?