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

How do I swap two characters in Vim?

Answer

xp

Explanation

The xp command swaps the character under the cursor with the character to its right. It is a classic two-keystroke idiom that combines two simple operations into an effective edit.

How it works

  • x deletes the character under the cursor and stores it in the default register
  • p pastes the deleted character after the cursor, which has now moved to the next character

The net effect is that the two adjacent characters trade places.

Example

Given the text with the cursor on the e in teh:

teh quick brown fox

Pressing xp results in:

the quick brown fox

The e and h are swapped, fixing the common typo.

Tips

  • Use Xp to swap the character under the cursor with the one to its left instead
  • Use ddp to swap the current line with the line below it (same principle, applied to whole lines)
  • Use dawwP or dawbP to swap two adjacent words
  • This trick is especially handy for fixing typos like tehthe or adnand
  • Position your cursor on the first of the two characters you want to swap

Next

How do I edit multiple lines at once using multiple cursors in Vim?