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

How do I swap two regions of text without using registers?

Answer

cx{motion} then cx{motion}

Explanation

vim-exchange (by Tom McDonald) lets you swap two text regions in two steps — no yank register manipulation, no cut-paste juggling. Press cx{motion} on the first region to mark it, then cx{motion} on the second region to complete the swap. The two regions exchange positions.

How it works

  1. cx{motion} — mark the first region (highlighted)
  2. cx{motion} — mark the second region → both regions instantly swap
  3. cxx — shorthand for cx{line} (exchange the current line)
  4. X in Visual mode — exchange the visual selection
  5. cxc — cancel a pending exchange

Install with: Plug 'tommcdo/vim-exchange'

Examples

Swap two words on a line:

foo bar    →    bar foo
  1. cxiw on foo (marked)
  2. cxiw on bar → swapped

Swap two lines:

cxx    " mark line 1
cxx    " mark line 2 → lines swap

Swap two arguments in a function call:

doSomething(alpha, beta)    →    doSomething(beta, alpha)
  1. cxi( ... (navigate) ... no, use cxi, if you have targets.vim
  2. Or: cxiw on alpha, then cxiw on beta

Tips

  • Works with any motion or text object: cxiw, cxi", cx3j, cxip, etc.
  • The visual X is the fastest for irregular selections
  • Unlike yank-delete-paste, vim-exchange preserves surrounding whitespace cleanly
  • No register is used — your yank register stays intact throughout

Next

How do I run a search and replace only within a visually selected region?