Exchange text in Vim, with no plugins

Here’s a way to exchange the positions of two pieces of text in Vim, without the use of specialized plugins.

  • Delete one of the texts, using a text object or a motion. di(
  • Go to othe other text /de
  • Select the other text in visual mode. vi(
  • Paste the initial text using p. The visually selected text will be overwritten, and also copied into the the unnamed register.
  • Jump to the penultimate change in the changelog using 2g;. This brings us back to where the original text was deleted.
  • Paste with P.

There is a small quirk when the two texts lie close together. In that case, typing 2g; won’t bring us back to the exact position of the first change. See :help changelist for the details.


Perhaps it would be worth it to define a shortcut for the p2g;P sequence. Something like:

vnoremap <script> <silent> <unique> <Leader>e p2g;P
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade