How do I swap two text regions without using a temporary register in Vim?
Answer
cx{motion}
Explanation
The vim-exchange plugin by Tom McDonald provides the cx operator to swap two arbitrary text regions. Instead of the tedious dance of yanking to a named register, deleting one region, pasting, navigating to the other, and repeating — you simply mark two regions with cx and they swap places automatically.
How it works
The cx operator works in two steps:
- Press
cx{motion}on the first text region to mark it - Press
cx{motion}on the second text region to perform the swap
After the second cx, both regions exchange their content instantly.
Example: swapping two words
Given the text with cursor on foo:
foo bar baz
- Press
cxiwonfooto mark it (no visible change yet) - Move to
bazand presscxiwto complete the swap:
baz bar foo
Example: swapping function arguments
Given:
process(input, output)
- Place cursor on
input, presscxiw - Move to
output, presscxiw
Result:
process(output, input)
Operator variants
cx{motion} " mark/exchange using any motion or text object
cxx " mark/exchange the entire current line
cxc " cancel a pending exchange (clear the first mark)
X " exchange in visual mode (mark/swap the selection)
Swapping lines
Use cxx to swap entire lines:
- On line 3, press
cxxto mark the whole line - Move to line 7, press
cxxto swap the two lines
Visual mode exchange
For more complex regions that don't map cleanly to a text object:
- Visually select the first region, press
X - Visually select the second region, press
X
The two selections swap their content.
Canceling a pending exchange
If you mark the wrong region with the first cx, press cxc to clear the pending mark and start over.
Tips
- Works with any motion or text object:
cxi"swaps quoted strings,cxipswaps paragraphs,cxa)swaps parenthesized groups - Install vim-repeat alongside vim-exchange so the full swap operation is repeatable with
. - The plugin highlights the first marked region so you can see what is pending for exchange
- Unlike manual register-based swaps, vim-exchange handles overlapping or adjacent regions correctly
- Combine with targets.vim argument objects (
cxia) for lightning-fast argument reordering