I have a document whose paragraphs start with a number like this:

101 kjwdujd dkjcjiekrd wekdhehwrd kwedhiehrc wekdhchjedc kjdchhedch .

99 dsjcoiedc wdhiwedc wedhiuwhediuhewdkdeh wedghiuwghediughedc wejgdugwed 

5 kdjewde3 diwedeoi.

I would like to sort the paragraphs according to these numbers, so ideally the ordering should be 5, then 99 then 101. But given the fact that the function sort-paragraphs sorts the paragraphs lexicographically, the sorting would be 101 then 5 then 9.

Is there a way to sort the paragraphs by the paragraph numbers?

2 Answers 2


Like sort-paragraphs but set sort-subr's PREDICATE argument to meet your needs

(defun my-sort-paragraphs (reverse beg end)
  (interactive "P\nr")
      (narrow-to-region beg end)
      (goto-char (point-min))
      (sort-subr reverse
                  (lambda ()
                    (while (and (not (eobp)) (looking-at paragraph-separate))
                      (forward-line 1))))
                 'forward-paragraph nil nil
                 (lambda (a b)
                   (< (string-to-number (progn (goto-char (car a))
                      (string-to-number (progn (goto-char (car b))

For a short document, sort-numeric-fields might work here, with two pre-requisites. First, you need each paragraph to be on a single line. This is not so awkward if you use visual-line-mode. Then, you need to remove all blank lines. You can do this with M-x flush-lines, and enter ^\s *$.

After this, M-x sort-numeric-fields will reorder your lines according to the number at the beginning.

Obviously, it would be much nicer to have this work on normally formatted paragraphs with blank lines between. I'm not sure that's available without writing your own functions.

  • Thanks for introducing M-x sort-numeric-fields. This does not completely solve the question but is a good step toward it.
    – Name
    Jul 4, 2016 at 14:30

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.