12

I have a buffer of words and phrases in sorted order and I would like to have the lines sorted in a random order. How would I do this with either an emacs builtin function or with elisp?

For example, given

bar
elisp
emacs
foo
hello world
the quick brown fox

I would like some completely random result like:

foo
the quick brown fox
hello world
elisp
emacs
bar

or ...

hello world
elisp
bar
the quick brown fox
foo
emacs

Drew
  • 29,895
  • 7
  • 74
  • 104

4 Answers4

23

Using Bash on GNU/Linux:

Similar to Sean's solution, select the region and then:

C-u M-| shuf

Explanation:

M-| pipes the content of selected region to the bash command shuf. shuf shuffles the lines. The prefix C-u takes the output of shuf and uses it to overwrite the selected region.

user2548343
  • 731
  • 5
  • 12
9

Alternatively, here is sort-lines adapted to this requirement.

I've removed the reverse argument (obviously not relevant here), and simply supplied a 'comparison' function returning a random result to sort-subr.

(defun my-random-sort-lines (beg end)
  "Sort lines in region randomly."
  (interactive "r")
  (save-excursion
    (save-restriction
      (narrow-to-region beg end)
      (goto-char (point-min))
      (let ;; To make `end-of-line' and etc. to ignore fields.
          ((inhibit-field-text-motion t))
        (sort-subr nil 'forward-line 'end-of-line nil nil
                   (lambda (s1 s2) (eq (random 2) 0)))))))

For the original:
M-x find-function RET sort-lines RET

phils
  • 71,335
  • 11
  • 153
  • 198
6

randomize-region.el seems to do what you want.

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • 1
    @Geremia: Easiest approach is probably just to cut&paste the code into your .emacs file. – Nemo Sep 03 '14 at 19:21
4

If you don't mind shelling out to Perl, you can select the region you want to randomize, and then type C-u M-| perl -MList::Util=shuffle -e 'print shuffle <STDIN>'.

I'm sure many other popular programming languages offer similar facilities.

Sean
  • 29,130
  • 4
  • 80
  • 105