Emacs 26.1

I have this text:


I want to swap text in all these lines. The result must be like this:


How I can do this?


5 Answers 5


Another option: using Multiple Cursors you can do it with three commands!

Starting with point (the cursor) on the first hyphen -:

  1. Mark the hyphen with Shift right-arrow or C-space C-f
  2. Mark all hyphens with M-x mc/mark-all-like-this or C-c C-<
  3. Transpose words with M-x transpose-words or M-t

I personally think the query-replace-regexp solution is better, but just for fun here is another solution with macros:

;; Move cursor to start of first line
<f3>      ;; kmacro-start-macro-or-insert-counter
M-f       ;; forward-word
M-t       ;; transpose-words
C-n       ;; next-line
C-a       ;; move-beginning-of-line
<f4>      ;; kmacro-end-or-call-macro
;; Select remaining lines
C-x C-k r ;; apply-macro-to-region-lines
  • Executing your macro with numeric argument 0 should also work as intended, as going past the last line in a buffer errors out and terminates execution.
    – user12563
    Commented Jan 11, 2019 at 21:26

You can do it with C-M-% (running query-replace-regexp): Give it the string "\([A-Z]+\)-\([A-Z]+\)" (quotes included) for the text to replace, and "\2-\1" for the replacement.


You can simply use query-replace-regexp (default key C-M-%) for this. search pattern would be something like


and the replacement would look like this then


replace-regexp is great for such things, check the emacs wiki for mor information about that emacs regexp


Regexps are an overkill in this case since emacs has a built-in command transpose-words that is bound to M-t by default. This command, combined with isearch are enough to solve the problem when linked together with emacs keyboard macros.


Learn to use keyboard macros and you can solve most repetative text editing tasks.

Place the cursor before the first line, start recording the keyboard macro, press C-s and - to move the cursor to the next hyphen, press M-t to transpose the words, stop recording. Then repeat the macro as many times as needed. Alternatively, you can apply the macro to a region of lines.

  • See also @0x5453's answer, which likewise used transpose-words in a keyboard macro.
    – phils
    Commented Jan 9, 2019 at 21:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.