How do I exchange two blocks of text using visual mode?
Answer
visual select + d, move, P
Explanation
To swap two pieces of text, delete the first selection, navigate to the second, select it, and paste. The second piece goes where the first was via the register.
How it works
- Select the first text and press
d(deletes to register) - Navigate to the second text
- Select the second text in visual mode
- Press
p(pastes first text, puts second into register) - Navigate back to the first location
- Press
P(pastes the second text)
Example
To swap foo and bar:
viwonfoo,d- Move to
bar,viwp(nowbaris in register,foois at that position) - Move back to where
foowas,P
Tips
- Using named registers makes this cleaner:
"adthen"ap - The vim-exchange plugin automates this with
cxmotions - For lines,
ddpswaps two adjacent lines - For characters,
xpswaps two adjacent characters