Sorting Org Mode lists using a sequence of regular expressions

| emacs, org

I manually categorize Emacs News links into an Org unordered list, and then I reorganize the list by using M-S-up (org-shiftmetaup) and M-S-down (org-shiftmetadown). I decide to combine or split categories depending on the number of links. I have a pretty consistent order. John Wiegley suggested promoting Emacs Lisp and Emacs development links at the top of the list. I like to sort the rest of the list roughly by interest: general links first, then Org, then coding, then other links at the bottom.

Here’s some code that sorts Org lists in a custom sequence, with unknown items at the bottom for easy re-ordering. It will take a list like:

- Other:
  - Link A
  - Link B
- Emacs development:
  - Link A
  - Link B
- Emacs Lisp:
  - Link A
  - Link B

and turn it into:

- Emacs Lisp:
  - Link A
  - Link B
- Emacs development:
  - Link A
  - Link B
- Other:
  - Link A
  - Link B
(defun my/org-sort-list-in-custom-order (order)
  "Sort the current Org list so that items are in the specified order.
ORDER is a list of regexps."
  (org-sort-list
   nil ?f
   (lambda ()
     (let ((case-fold-search t)
           (item
            (when (looking-at "[ \t]*[-+*0-9.)]+\\([ \t]+\\[[- X]\\]\\)?[ \t]+")
              (org-sort-remove-invisible (buffer-substring (match-end 0) (point-at-eol))))))
       (or (cl-position item order :test (lambda (a b) (string-match b a))) (1+ (length order)))))
   '<))

(defun my/emacs-news-sort-list ()
  (interactive)
  (my/org-sort-list-in-custom-order
   '("Emacs Lisp"
     "Emacs development"
     "Appearance"
     "Navigation"
     "Dired"
     "Org Mode"
     "Coding"
     "Calc"
     "Email and news"
     "Other"
     "Discussion"
     "Outside Emacs"
     "New packages?")))

One more little thing automated… The next thing would probably be to write some code that autocategorizes links based on an alist of (item . regexp) pairs, which would also reduce the need to re-sort the items afterwards. Still, this is good for dealing with manual categorization. =)

You can comment with Disqus or you can e-mail me at sacha@sachachua.com.