transpose two words as in Sublime Text

emacs, emacs24, sublimetext2

Solution

As @artscan says, the command you are looking for is `transpose-words`. It is bound to `M-t` by default. It works without a region (i.e., you don't have to "mark" anything for it to work). To transpose `foo` and `bar`, point can be on any of the following characters:

`oo", "b`

Putting point before them will transpose `list` and `foo`; putting it after them will transpose `bar` and `hello`.

Related commands for transposing other units of text, along with their default key bindings (if any):

`transpose-chars` (C-t)

`transpose-lines` (C-x C-t)

`transpose-paragraphs`

`transpose-sentences`

`transpose-sexps` (C-M-t)

Going Beyond Built-Ins

If you want to transpose words that are not adjacent (e.g., `foo` and `hello`) with a single keystroke, you can define a keyboard macro or a custom command and bind it to a key:

(defun hop-one-transpose ()
  "Transpose words that are separated by a single word."
  (interactive)
  (transpose-words 2)
  (backward-word 3)
  (forward-char)
  (transpose-words 1))

(global-set-key (kbd "C-x M-t") 'hop-one-transpose)

Appendix: Let Emacs Help You Discover Emacs

If you find yourself wondering whether Emacs has a command for some type of action, try using `command-apropos` to find it:

C-h a `<action>` RET

Problem

I was watching a online class of Django and the teacher did a nice trick in Sublime Text with two values of a list, it transpose each to the position of the other, for instance: ``` list = ("foo", "bar", "hello") ``` marked `foo` and `bar` with the mouse and then did the transpose, getting the following: ``` list = ("bar", "foo", "hello") ``` How that can be achieve in Emacs?

Original source