Echo Area

Emacs Hack: Showing a Random Note From My Org Roam Database

13 March 2025 7:18 AM (emacs)

I use org-roam for my note taking (at the moment, but it's quite volatile) and to make sure I don't just write something and forget about it I thought it would be nice to add an item to my emacs-dashboard that adds a link to a random note every time I load it (which is usually once per day).

I wrote about my hack to show a random EmacsWiki page just the other day and this one is basically the same, but simpler because no asynchronous fetching of a URL is going on. This is all local:

 1: (defun oni-dashboard-insert-random-note (_)
 2:   "Insert a link to a random note from my Roam database."
 3:   (dashboard-insert-heading "Today's Note:" "n")
 4:   (insert "\n    ")
 5:   (dashboard-insert-shortcut 'random-note "n" "Today's Note:")
 6:   (let ((element (seq-random-elt (org-roam-node-read--completions))))
 7:     (widget-create 'link
 8:                    :notify (lambda (&rest _)
 9:                              (find-file (org-roam-node-file (cdr element)))
10:                              (goto-char (org-roam-node-point (cdr element))))
11:                    :button-prefix ""
12:                    :button-suffix ""
13:                    (string-trim-right (car element)))))
14: 
15: (add-to-list 'dashboard-item-generators '(random-note . oni-dashboard-insert-random-note))
16: (add-to-list 'dashboard-items '(random-note))

This one is quite easy. Line 3 just inserts a heading into the dashboard. Line 5 sets up a shortcut key to make navigating to the section easy. Then line 6 does the hard work, it actually selects a random not by getting the list of all known nodes and just picking any random one. Line 7 inserts the actual link. This uses the widget.el library to display a clickable element that looks like a link. Once it's been clicked the lambda passed in as the :notify option will get called. This needs lexical binding to be true, otherwise the lambda can't create a closure with the element variable and the whole thing falls apart.

Comments are closed.