How do I replace a visual selection with yanked text in Vim?
Answer
p (in visual mode)
Explanation
In visual mode, pressing p replaces the selected text with the contents of the default register. Unlike deleting and then pasting, this is a single atomic operation — and it has a useful side effect: the replaced text is stored in the default register, which enables text swaps.
How it works
- Yank the replacement text (e.g.,
yiwto yank a word) - Visually select the target text you want to replace (
viw,V,<C-v>, etc.) - Press
p— the selection is replaced by the yanked text, and the replaced text enters the default register"
Example
Starting with:
foo bar
- Place cursor on
foo, yank it:yiw - Move to
bar, select it:viw - Press
p
Result:
foo foo
bar is now in register ", so pressing p elsewhere pastes bar — enabling a complete word swap in just a few keystrokes.
Tips
- To always paste from the yank register (unaffected by the swap), use
"0pin visual mode:viw"0p - In Neovim,
Pin visual mode pastes without overwriting the register — the selection is replaced but your yank stays intact - Works with any visual mode: characterwise (
v), linewise (V), or blockwise (<C-v>) - Map
xnoremap <Leader>p "0pto make visual paste always use the yank register