Skip to content

Instantly share code, notes, and snippets.

@alphapapa
Forked from jwiegley/org-extra.el
Created November 5, 2024 05:00
Show Gist options
  • Save alphapapa/4b3368fd16d9b5037487648d339b829b to your computer and use it in GitHub Desktop.
Save alphapapa/4b3368fd16d9b5037487648d339b829b to your computer and use it in GitHub Desktop.
(defun org-extra-get-properties (&rest props)
(cons (org-current-level)
(mapcar #'(lambda (prop)
(if (string= "ITEM_BY_ID" prop)
(format "[[id:%s][%s]]"
(org-entry-get (point) "ID")
(org-entry-get (point) "ITEM"))
(org-entry-get (point) prop)))
props)))
(defun org-dblock-write:ql-columnview (params)
"Create a table view of an org-ql query.
Example:
#+begin: ql-columnview :query \"(and (tags \\\"John\\\") (todo))\" :properties \"TODO ITEM_BY_ID LAST_REVIEW NEXT_REVIEW TAGS\" :sort-idx 4
#+end:
The :sort-idx takes the 1-indexed column mentioned in
:properties, interprets it as an Org-time, and sorts the
resulting table on that column, ascending."
(let* ((columns (split-string (plist-get params :properties) " "))
(sort-index (plist-get params :sort-idx))
(table
(org-ql-select
'org-agenda-files
(read (plist-get params :query))
:action `(org-extra-get-properties ,@columns)
:sort
#'(lambda (x y)
(when sort-index
(time-less-p
(org-encode-time
(org-parse-time-string (nth sort-index x)))
(org-encode-time
(org-parse-time-string (nth sort-index y)))))))))
;; Add column titles and a horizontal rule in front of the table.
(setq table (cons columns (cons 'hline table)))
(let ((hlines nil)
new-table)
;; Copy header and first rule.
(push (pop table) new-table)
(push (pop table) new-table)
(dolist (row table (setq table (nreverse new-table)))
(let ((level (car row)))
(when (and (not (eq (car new-table) 'hline))
(or (eq hlines t)
(and (numberp hlines) (<= level hlines))))
(push 'hline new-table))
(push (cdr row) new-table))))
(save-excursion
;; Insert table at point.
(insert
(mapconcat (lambda (row)
(if (eq row 'hline) "|-|"
(format "|%s|" (mapconcat #'identity row "|"))))
table
"\n")))
(org-table-align)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment