alphapapa / org-ql

A searching tool for Org-mode, including custom query languages, commands, saved searches and agenda-like views, etc.
GNU General Public License v3.0
1.43k stars 110 forks source link

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

Open karlicoss opened 1 year ago

karlicoss commented 1 year ago

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 https://github.com/alphapapa/org-ql/blob/eb5377320fcfd38354d6e9e3e655969ae3c0e052/org-ql.el#L2400-L2436 , 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!

karlicoss commented 1 year ago

ended up with something like this for now..

(defun --my/org-get-created-ts (item)
  (let* ((created-prop-s (org-element-property :CREATED item))
         (created-prop-ts (when created-prop-s (ts-parse-org created-prop-s))))
    (if created-prop-ts created-prop-ts
      (let* ((created-title-el (car (org-element-map (org-element-property :title item) 'timestamp 'identity)))
             (created-title-ts (when created-title-el (ts-parse-org-element created-title-el))))
         created-title-ts))))

(defun --my/org-ql--created-date< (a b)
  (ts<
   ;; if we get nil, ts< will complain
   (or (--my/org-get-created-ts a) (make-ts :unix 0))
   (or (--my/org-get-created-ts b) (make-ts :unix 0))
))

(advice-add #'org-ql--date< :override #'--my/org-ql--created-date<)
alphapapa commented 1 year ago

Hi,

Yes, unlike search predicates with org-ql-defpred, there isn't yet support for easily adding custom sorters. However, there is a WIP branch that would make it easier: https://github.com/alphapapa/org-ql/blob/e8eff5d798bcdb3124b1e1f147dc871b0c313cd6/org-ql.el#L412-L423 The disadvantage is possibly providing less useful error messages if a user makes a mistake, but the additional flexibility would probably be worth it, so I'll probably merge something like that eventually.