Vi Tip of the Week: Transpose characters

This is part of a series of tips on using Vi.  To see the complete series, click here.

OK, this is my favourite command in vi, not because it’s especially useful, just because I think it’s neat.  If you make a typing mistake and get two characters switched around, it’s easy to fix.  For example, if I want to type “Linux”, but I mistakenly type “Liunx”, all I have to do is place my cursor on the “u”, use the “xp” (transpose) command, and it swaps the “u” and the “n” around, making “Linux” as I originally wanted.

I sort of lied; this isn’t a single command — it’s two commands that result in transposing the characters.  The first command, x, deletes the character under the cursor and saves it in vi’s “unnamed” buffer.  Then, the second command, p, spits out what’s in that buffer, placing it after the cursor.  So, the result is that the two characters are transposed (fancy word for switched around).  What I think is cool is that these two separate commands, x and p, when combined as xp, perform an operation that is easy to remember: xp = transpose!  Cool!!!