Skip to content

custom sort predicates for org-ql--sort-by? #366

@karlicoss

Description

@karlicoss

Apologies if it's a duplicate -- I searched over issues/prs and didn't find anything existing

I want to sort the results of org-ql-search by a "created" timestamp -- in my case it's either a CREATED property or just a first inactive timestamp in the outline (e.g. * [#B] [2022-08-01 Mon 00:38] some note).
I went through the source code

org-ql/org-ql.el

Lines 2400 to 2436 in eb53773

(defun org-ql--sort-by (items predicates)
"Return ITEMS sorted by PREDICATES.
PREDICATES is a list of one or more sorting methods, including:
`deadline', `scheduled', `closed' and `priority'."
;; MAYBE: Use macrolet instead of flet.
(cl-flet* ((sorter (symbol)
(pcase symbol
((or 'deadline 'scheduled 'closed)
(apply-partially #'org-ql--date-type< (intern (concat ":" (symbol-name symbol)))))
;; TODO: Rename `date' to `planning'. `date' should be something else.
('date #'org-ql--date<)
('priority #'org-ql--priority<)
('random (lambda (&rest _ignore)
(= 0 (random 2))))
;; NOTE: reverse and todo are handled below.
;; TODO: Add more.
(_ (user-error "Invalid sorting predicate: %s" symbol))))
(sort-by-todo-keyword (items)
(let* ((grouped-items (--group-by (when-let (keyword (org-element-property :todo-keyword it))
(substring-no-properties keyword))
items))
(sorted-groups (cl-sort grouped-items #'<
:key (lambda (keyword)
(or (cl-position (car keyword) org-todo-keywords-1 :test #'string=)
;; Put at end of list if not found
(1+ (length org-todo-keywords-1)))))))
(-flatten-n 1 (-map #'cdr sorted-groups)))))
(dolist (pred predicates)
(setq items (pcase pred
;; NOTE: Using `reverse' instead of `nreverse' because my gut
;; tells me that, while `nreverse' would be preferable and faster,
;; it would probably cause weird bugs, like items' order being
;; reversed every time a cached query is refreshed in a view.
('reverse (reverse items))
('todo (sort-by-todo-keyword items))
(_ (-sort (sorter pred) items)))))
items))
, and seems that it only supports predefined sorting predicates at the moment?

I'm happy to try and contribute support for custom predicates, just want to double check first that would fit into the library. E.g. I imagine it might have some impact on caching?

I imagine as a workaround I could abuse existing org-ql--date< sorting key and override it to extract the CREATED property or something like that.
Thanks!

Metadata

Metadata

Assignees

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions