Swap two characters in Vim


Here’s a quick trick that requires no plugins. You probably already know both of these commands but many people, including myself, might not have internalized the combination. A little reminder is sometimes all we need.

Use xp to swap the character under your cursor with the one to its right.

For example, suppose you have a misspelled word like so:

puts "Hlelo world!"

With your cursor on the misplaced l in Hlelo, type xp:

puts "H█elo world!"

The x deletes the character under the cursor and puts it in a register and p pastes that register to the right of the cursor. You end up with:

puts "Hello world!"

Just internalize xp for swapping characters and stop going in and out of insert mode to make small edits. And to swap backwards instead of forwards, use Xp.

How useful was this tip?

Average rating 3.4 / 5. Vote count: 369

No votes so far! Be the first to rate this tip.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Written by

Colin Bartlett

105 Posts

Vim enthusiast and software developer for more than 20 years.
View all posts