Exchange text in Vim, with no plugins

Daniel Díaz Carrete
1 min readJul 30, 2017

--

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

--

--

No responses yet