2017-02-13 Sorting Org entries by most recent activity

As I mentioned a lot of times, I use Org-mode – and in particular, clocking – very heavily. Sometimes I have this Org entry with a lot of (clocked) subentries, and I’d like to see which ones of them I haven’t touched in a long time – and which ones I’ve been working recently.

I wanted to ask on the Org mailing list whether it was possible, but – taught by experience – I decided to check in the manual first. Unsurprisingly, the feature is (almost) already there. It’s called org-sort and is bound to C-c ^. You can invoke it on the “parent” entry and then choose the sorting order (it works differently on lists and tables, though). The one interesting here is T, which means “time”. The sorting key is the first active timestamp in the entry, and in case there are no active timestamps, the first inactive one. Since I usually don’t have active timestamps on things I clock, this is enough for me. In case this is a problem, org-sort also accepts an f (for function) and then asks for any Elisp function acting as a predicate; writing one treating active and inactive timestamps in the same way would most probably be very easy.

Interestingly enough, there is almost no need to write such a function. Deep in the Org-mode guts, in org-clock.el, there lies hidden a function called org-clock-get-last-clock-out-time. It’s almost never really used, but it does what we want. The only problem is that it returns a time value, i.e. not sth you can feed into org-sort. But this is easy to remedy:

(defun org-clock-get-last-clock-out-unix-time ()
  "Return the last clock-out time for the current sub-tree as
a Unix time."
  (time-to-seconds (org-clock-get-last-clock-out-time)))

Note also that lowercase letters in org-sort correspond to ascending order and uppercase ones to descending ones. It might also be interesting to know that org-sort is really kind of a “dispatcher”, calling org-table-sort-lines, org-sort-list or just org-sort-entries (depending on what the point is at).

CategoryEnglish, CategoryBlog, CategoryEmacs, CategoryOrgMode