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

How do I exchange two blocks of text using visual mode?

Answer

visual select + d, move, P

Explanation

To swap two pieces of text, delete the first selection, navigate to the second, select it, and paste. The second piece goes where the first was via the register.

How it works

  1. Select the first text and press d (deletes to register)
  2. Navigate to the second text
  3. Select the second text in visual mode
  4. Press p (pastes first text, puts second into register)
  5. Navigate back to the first location
  6. Press P (pastes the second text)

Example

To swap foo and bar:

  1. viw on foo, d
  2. Move to bar, viwp (now bar is in register, foo is at that position)
  3. Move back to where foo was, P

Tips

  • Using named registers makes this cleaner: "ad then "ap
  • The vim-exchange plugin automates this with cx motions
  • For lines, ddp swaps two adjacent lines
  • For characters, xp swaps two adjacent characters

Next

How do you yank a single word into a named register?