vimtricks.wiki Concise Vim tricks, one at a time.

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:

  1. Press cx{motion} on the first text region to mark it
  2. 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
  1. Press cxiw on foo to mark it (no visible change yet)
  2. Move to baz and press cxiw to complete the swap:
baz bar foo

Example: swapping function arguments

Given:

process(input, output)
  1. Place cursor on input, press cxiw
  2. Move to output, press cxiw

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:

  1. On line 3, press cxx to mark the whole line
  2. Move to line 7, press cxx to swap the two lines

Visual mode exchange

For more complex regions that don't map cleanly to a text object:

  1. Visually select the first region, press X
  2. 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, cxip swaps 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

Next

How do I edit multiple lines at once using multiple cursors in Vim?