emacs: transposing text
Transposing text is the act of swapping two syntactic units of text with one another.
Key Binding | Purpose |
---|---|
C-t | Transpose characters |
M-t | Transpose words |
C-M-t | Transpose s-expression |
C-x C-t | Transpose lines |
M-x transpose-paragraphs | Transpose paragraphs |
M-x transpose-sentences | Transpose sentences |
C-t: Transpose Characters
1 | A█BC |
After C-t:
1 | BA█C |
Note that the point moved forward one character so you can repeat calls to C-t to “pull” the character to the right:
1 | BCA█ |
When you are at the end of a line. C-t will swap the two characters to the left of the point:
1 | BCA█ |
After C-t:
1 | BAC█ |
This asymmetry is a surprisingly useful way of fixing typos as they occur. Fixing mistyped characters with C-t is a useful time saver as it saves you the effort of deleting both characters and retyping them.
M-t: Transpose Words
Transposing two words with M-t works as you would expect when the words are plain text, like this:
1 | Hello █World |
After M-t:
1 | World Hello█ |
Consider this example Python code where we have a dictionary (a key-value hash map):
1 | names = { |
With the point between the key and value, a call to M-t is pure magic:
1 | names = { |
C-M-t: Transpose S-expressions
Consider what happens if we mix a balanced expression with a word:
1 | Hello,█ (insert name here)! |
After C-M-t:
1 | (insert name here), Hello█! |
Other Transpose Commands
Transposing lines with C-x C-t is useful however. I use it frequently to re-order newline-based lists and it’s also useful for swapping around variable assignments; changing the order functions are called, and so on.