How do I replace a visual selection with yanked text without losing my clipboard?
Answer
"0p in visual mode
Explanation
When you paste over a visual selection with p, Vim replaces the selection with the register contents — but it also puts the deleted selection into the unnamed register, overwriting your yank. Using "0p instead always pastes from the yank register, which is never affected by deletes.
The problem
yiw " Yank 'foo'
viwp " Select 'bar' and paste 'foo' — but now 'bar' is in your register!
viwp " You wanted 'foo' again, but you get 'bar' instead
The solution
yiw " Yank 'foo'
viw"0p " Select 'bar', paste from yank register — 'foo' replaces it
viw"0p " Works again! Still pastes 'foo'
viw"0p " And again!
Why this works
"0(register 0) always holds the last yank — it's never overwritten by visual put""(unnamed register) gets the deleted text from the visual put, losing your yank- By using
"0p, you bypass the unnamed register entirely
Useful mapping
Many users add this to their vimrc to make visual paste always use the yank register:
vnoremap p "0p
vnoremap P "0P
Tips
- This is the single most common Vim frustration for users who don't know about
"0 - The
"0register is your safe haven — deletes, changes, and visual puts never touch it - Use
:reg 0to inspect what's in the yank register - Alternative: use
"_dPto delete to the black hole register first, then paste - For a full understanding, read about Vim's register hierarchy: unnamed, yank, numbered, named