Keep .org File Outline Items Sorted Alphabetically

org-mode files can be used for any kind of outline, including makeshift calendars and makeshift address books.

To make this work with org-capture to insert a new thing into such files, which always just appends, you can auto-sort a file e.g. before saving. That guarantees that the file is in a consistent state (sorted alphabetically) without you having to be clever about finding the corrent insertion point.

With Emacs, you can create file-local variables to set a before-save-hook (which usually is nil, so you don’t lose anything) to keep an org-mode file sorted at all times automatically, so there’s not much you need to do!

Create a file with this content to test:

# -*- before-save-hook: (my/org-sort); -*-

* Z
* B
* A
* D
* C

Then evaluate this snippet to add the function that accomplishes alphabetical sorting:

(defun my/org-sort ()
  (mark-whole-buffer)
  (org-sort-entries nil ?a))

Now when you have my/org-sort in your Emacs Lisp environment, reload the file so that it asks whether you want to apply any local variables. Confirm. Then edit it and save.

Expected output, in case you’re not sure:

# -*- before-save-hook: (my/org-sort); -*-

* A
* B
* C
* D
* Z

Now if you need more complex sorting, you can implement a sort function that does whatever you need to accomplish based on the transformation of an unsorted buffer into a sorted one. The setup remains equally simple. You still don’t need to tweak the org-capture insertion point.

That’s the power of robust (and idempotent, in case of already sorted) algorithms for you.