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

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
  • cxc clears a pending mark without swapping
  • In visual mode, X marks the selection instead of cx{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 cxx to exchange the current line with another line
  • Visual mode: select with v, then press X to mark; repeat on second region to swap
  • Install with: Plug 'tommcdo/vim-exchange' (vim-plug) or use 'tommcdo/vim-exchange' (packer)

Next

How do I rename a variable across all its case variants (camelCase, snake_case, SCREAMING_CASE) in one command?