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
xdeletes the character under the cursor and stores it in the default registerppastes 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
Xpto swap the character under the cursor with the one to its left instead - Use
ddpto swap the current line with the line below it (same principle, applied to whole lines) - Use
dawwPordawbPto swap two adjacent words - This trick is especially handy for fixing typos like
teh→theoradn→and - Position your cursor on the first of the two characters you want to swap