Skip to content

Instantly share code, notes, and snippets.

@alanz
Created March 20, 2021 15:46
Show Gist options
  • Save alanz/b4d5389dd88389571e99e8471cc505d5 to your computer and use it in GitHub Desktop.
Save alanz/b4d5389dd88389571e99e8471cc505d5 to your computer and use it in GitHub Desktop.
org-roam todo's in agenda
;;----------------------------------------------------------------------
;; Picking up TODO items from org-roam notes
;; Via https://magnus.therning.org/2021-03-14-keeping-todo-items-in-org-roam.html
(defun roam-extra:todo-p ()
"Return non-nil if current buffer has any TODO entry.
TODO entries marked as done are ignored, meaning the this
function returns nil if current buffer contains only completed
tasks."
(org-element-map
(org-element-parse-buffer 'headline)
'headline
(lambda (h)
(eq (org-element-property :todo-type h)
'todo))
nil 'first-match))
(defun roam-extra:update-todo-tag ()
"Update TODO tag in the current buffer."
(when (and (not (active-minibuffer-window))
(org-roam--org-file-p buffer-file-name))
(let* ((file (buffer-file-name (buffer-base-buffer)))
(all-tags (org-roam--extract-tags file))
(prop-tags (org-roam--extract-tags-prop file))
(tags prop-tags))
(if (roam-extra:todo-p)
(setq tags (seq-uniq (cons "todo" tags)))
(setq tags (remove "todo" tags)))
(unless (equal prop-tags tags)
(org-roam--set-global-prop
"roam_tags"
(combine-and-quote-strings tags))))))
(defun roam-extra:todo-files ()
"Return a list of note files containing todo tag."
(seq-map
#'car
(org-roam-db-query
[:select file
:from tags
:where (like tags (quote "%\"todo\"%"))])))
(defvar roam-extra-original-org-agenda-files nil
"Original value of `org-agenda-files'.")
(defun roam-extra:update-todo-files (&rest _)
"Update the value of `org-agenda-files'."
(unless roam-extra-original-org-agenda-files
(setq roam-extra-original-org-agenda-files org-agenda-files))
(setq org-agenda-files (append roam-extra-original-org-agenda-files (roam-extra:todo-files))))
;; To ensure that the todo tag is correct in all org-mode files I've
;; added roam-extra:update-todo-tag to hooks that are invoked on
;; opening an org-ram file and when saving a file. (I would love to
;; find a more specialise hook than before-save-hook, but it works for
;; now.)
(add-hook 'org-roam-file-setup-hook #'roam-extra:update-todo-tag)
(add-hook 'before-save-hook #'roam-extra:update-todo-tag)
;; To ensure that the list of files with TODO items is kept up to date
;; when I open I also wrap org-agenda in an advice so
;; roam-extra:update-todo-files is called prior to the agenda being
;; opened.
(advice-add 'org-agenda :before #'roam-extra:update-todo-files)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment