How do I swap two regions of text without a complex yank-delete-paste workflow?
Answer
cx{motion} … cx{motion} (vim-exchange)
Explanation
The vim-exchange plugin provides cx{motion} to mark a region, then cx{motion} again on a second region to swap them in place. It eliminates the mental overhead of temporary registers when you want to transpose words, arguments, or any two text objects.
How it works
cx{motion}marks the first region (highlighted with a pending indicator)cx{motion}on the second region swaps the two marked regions- If both regions are the same size, they swap exactly. If different sizes, the surrounding text adjusts
cxcclears a pending mark without swapping- In visual mode,
Xmarks the selection instead ofcx{motion}
Example
Given:
getUser(userId, options)
To swap the two arguments, place the cursor on userId and run cxiw, then move to options and run cxiw:
getUser(options, userId)
Tips
- Works with any motion or text object:
cxiw(inner word),cxi"(inside quotes),cxap(a paragraph) - Use
cxxto exchange the current line with another line - Visual mode: select with
v, then pressXto mark; repeat on second region to swap - Install with:
Plug 'tommcdo/vim-exchange'(vim-plug) oruse 'tommcdo/vim-exchange'(packer)