[TIPS] dynamically add Org-roam files to your agenda file

Dear folks:

An org-roam user (lld2001) post a very useful function to dynamically
add Org-roam files that contain TODO to your agenda files.

(defvar dynamic-agenda-files nil
  "dynamic generate agenda files list when changing org state")

(defun update-dynamic-agenda-hook ()
  (let ((done (or (not org-state) ;; nil when no TODO list
                  (member org-state org-done-keywords)))
        (file (buffer-file-name))
        (agenda (funcall (ad-get-orig-definition 'org-agenda-files)) ))
    (unless (member file agenda)
      (if done
          (save-excursion
            (goto-char (point-min))
            ;; Delete file from dynamic files when all TODO entry changed to DONE
            (unless (search-forward-regexp org-not-done-heading-regexp nil t)
              (customize-save-variable
               'dynamic-agenda-files
               (cl-delete-if (lambda (k) (string= k file))
                             dynamic-agenda-files))))
        ;; Add this file to dynamic agenda files
        (unless (member file dynamic-agenda-files)
          (customize-save-variable 'dynamic-agenda-files
                                   (add-to-list 'dynamic-agenda-files file)))))))

(defun dynamic-agenda-files-advice (orig-val)
  (union orig-val dynamic-agenda-files :test #'equal))

(advice-add 'org-agenda-files :filter-return #'dynamic-agenda-files-advice)
(add-to-list 'org-after-todo-state-change-hook 'update-dynamic-agenda-hook t)

I find it is useful and hope it can be useful to you as well.

2 Likes

Thank you for sharing it. The problem with this approach is that (a) you can’t plug it into existing pile of notes and (b) messing up with your customize file leads to broken agenda.

This post motivated me to share how I approach this problem that I am using for a month already and super happy about it’s performance. You can read detailed description on my blog. The code is available as a GitHub Gist.

TL;DR - in the before-save-hook current buffer is traversed for existence of any TODO entires and Project tag is either added or removed from #+ROAM_TAGS property. Now, org-agenda is adviced before to set the value of org-agenda-files to the list of files with Project tag (quieried from db, which is enourmously fast).

There is also a snipped to use for migration. This way all required information is always there, in your files and can be easily reconstructed. That being said, proposed solution can be easily adapted to dynamic-agenda-files approach.

Hope someone finds it useful :slight_smile:

2 Likes