Advice to org-roam-dailies-goto-today

· back

Currently, when calling org-roam-dailies-goto-today, {C-c n d} for me, Emacs switches to the daily note buffer, but moves point to (point-min). I want to advice to first check if the buffer with "YYYY-MM-DD.org" (for today) already exists, and if so, switch to this buffer. Related to Org-roam.

Here's an advice function to achieve that:

(defun my-org-roam-dailies-goto-today-advice (orig-fun &rest args)
  "Switch to today's daily note buffer/window if it exists, otherwise create it.
Preserves point position if buffer already exists."
  (let* ((today (format-time-string "%Y-%m-%d"))
         (daily-buffer-name (concat today ".org"))
         (existing-buffer (get-buffer daily-buffer-name))
         (existing-window (and existing-buffer
                               (get-buffer-window existing-buffer t))))
    (cond
     ;; Buffer is already displayed in a window - switch to that window
     (existing-window
      (select-window existing-window))
     ;; Buffer exists but not displayed - switch to it in current window
     (existing-buffer
      (switch-to-buffer existing-buffer))
     ;; Buffer doesn't exist - create it
     (t
      (apply orig-fun args)))))

(advice-add 'org-roam-dailies-goto-today
            :around #'my-org-roam-dailies-goto-today-advice)

This advice:

  1. Checks for buffer by name (not file path)
  2. If the buffer is displayed in any window (even in another frame), selects that window
  3. If the buffer exists but isn't displayed, switches to it in the current window
  4. Otherwise calls the original function

To remove the advice later:

(advice-remove 'org-roam-dailies-goto-today
               #'my-org-roam-dailies-goto-today-advice)