1

Given I have a string that maybe came from a buffer, or a clipboard, or wherever; how do I sort-lines in it? Given that sort-lines only works with a region, I assume I have to put it to a temporary buffer, but I'm not aware of a common way of dealing with such tasks.

Googling the topic doesn't give anything relevant.

1
  • I'd put it in a temporary buffer and then use sort-lines (if applicable) - yes. But see the Elisp manual, node Sorting for other sort functions etc.
    – Drew
    Commented Apr 8, 2019 at 1:00

2 Answers 2

3

I'm not aware of a common way of dealing with such tasks.

with-temp-buffer and buffer-string are nice general helpers here.

(setq SORTED (with-temp-buffer
               (insert UNSORTED)
               (sort-lines nil (point-min) (point-max))
               (buffer-string)))
4

Here is one possible way to implement this using a temporary buffer:

(defun sort-string (string &optional reverse)
  "sorts an input string, using a temporary buffer"
  ;;(interactive "sto be sorted multiline string: ")
  (with-temp-buffer
    (insert string)
    (let ((beg (point-min))
      (end (point-max)))
      (sort-lines reverse beg end)
      (buffer-string)) ))

First a temprary buffer is created, then the given string is inserted, then the whole buffer is sorted, then the whole buffer is returned as a new string.

The additional parameter reverse can change the sort order.
To make this function a command, which you can call via M-x, uncomment the (interactive) line, but then you have to grab the output of the function in a useful way.


Evaluating following code pieces in the given order, results in the following output:

(setq my-string "zzzz\ndddd\nhhhhh\naaaaa")

"zzzz
dddd
hhhhh
aaaaa"

(setq my-string (sort-string my-string))

"aaaaa
dddd
hhhhh
zzzz"

my-string

"aaaaa
dddd
hhhhh
zzzz"

(setq my-string (sort-string my-string 'reverse))

"zzzz
hhhhh
dddd
aaaaa"

my-string

"zzzz
hhhhh
dddd
aaaaa"

2
  • Upvoted -- you clearly started typing before me :)
    – phils
    Commented Apr 8, 2019 at 9:36
  • @phils thanks, yours looks more lispy. :)
    – jue
    Commented Apr 8, 2019 at 9:37

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.