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
- Yank the text you want to put somewhere (
yiw,y$, etc.) - Visually select the text you want to replace
- 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 pressP— but note the register now holds B - Use
"0pinstead ofpto paste the last yanked text specifically, preserving register0through deletions and prior pastes - In line-wise visual mode (
V),preplaces 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:
"apreplaces the selection with registeraand puts the old text in"