Transpose characters

You can use C-t to run transpose-chars to switch the character at the cursor position with the previous character. Repeated uses have the effect of dragging the character behind the point to the right.

I have found that I prefer the behaviour to be that the previous two characters before the point are switched, as I usually want to do this if I spot I have just made a typo. This is what transpose-chars does if you are at the end of a line, but not if you are somewhere in the middle of the line. To modify the behaviour in this way, I use

;; adjust transpose-chars to switch previous two characters
(global-set-key (kbd "C-t")
                (lambda () (interactive)
                  (backward-char)
                  (transpose-chars 1)))

As an example, with the modified behaviour, using C-t with the point at the end of the string teh changes it to the, while the original behaviour gives you te h (unless you are at the end of a line, in which case you get the). Repeated use of the modified version simply toggles back and forth.

  • Alan Shutko

    One minor correction: transpose-chars will transpose the previous two characters by default if you are at the end of a line, whether that is at the end of the buffer or not.

  • nitishch

    Modifying “M-t” shortcut to work this way would be useful too. Just replace “C-t” with “M-t” and “transpose-chars” with “transpose-words”.

    • This is a good suggestion, but note that transpose-words is replaced by org-transpose-words on M-t in org-mode so you would have to adjust that too.