6

How can one reverse the letters/characters in a selected region?

xyz --> zyx

ab cde --> edc ba

2 Answers 2

13

Emacs doesn't seem to provide any function to do this out of the box, but implementing one isn't that hard:

(defun my-reverse-region (beg end)
 "Reverse characters between BEG and END."
 (interactive "r")
 (let ((region (buffer-substring beg end)))
   (delete-region beg end)
   (insert (nreverse region))))
7
  • 1
    Perfect, works well.
    – Name
    Jan 17, 2018 at 16:23
  • 2
    Mark my answer as an solution if it helped you.
    – user12563
    Jan 17, 2018 at 16:38
  • Of course. Usually I wait for a while for alternative solutions, then mark it as accepted.
    – Name
    Jan 17, 2018 at 16:43
  • 4
    You can also use delete-and-extract-region, i.e., (insert (nreverse (delete-and-extract-region beg end))).
    – xuchunyang
    Jan 17, 2018 at 19:32
  • How do you use it with Meta + x? If I highlight a region (e.g. the abc string) and then execute it, I get the following error: Wrong type argument: listp, #("abc" 0 3 (fontified t)) Sep 14, 2019 at 20:47
1

Since emacs can call the shell on a region of text, and since shell can reverse text I believe there's an alternative/elegant(?) solution to the OPs problem,.

That's a comment but not an answer

okay how about

    ;; select the region, then
    C-u M-|
    ;; Shell command on region:
    rev<enter>
1
  • ... although it reverses lines, not the region.
    – NickD
    Jun 27, 2022 at 19:03

This site is temporarily in read-only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .