Hey, this function is nice, thanks! I’m using it on my website.
I’ve fixed a few bugs in the way it works below. Namely, a node’s end position isn’t necessarily the next node, but rather the next same-level headline (if there is one.) Also, I changed it to sort in decreasing order of the node’s end position (which removes the need for manually counting characters entirely,) and then insert backlinks in that order.
A couple other tweaks I added:
- the outline path, as is displayed in the org-roam-buffer. You can take this out if desired.
- backlinks link directly to the node ID, rather than to the source file.
(defun collect-backlinks-string (backend)
(let* ((source-node (org-roam-node-at-point))
(source-file (org-roam-node-file source-node))
(nodes-in-file (--filter (s-equals? (org-roam-node-file it) source-file)
(nodes-start-position (-map 'org-roam-node-point nodes-in-file))
;; Nodes don't store the last position, so get the next headline position
;; and subtract one character (or, if no next headline, get point-max)
(nodes-end-position (-map (lambda (nodes-start-position)
(if (org-before-first-heading-p) ;; file node
(if (> (point) nodes-start-position)
(- (point) 1) ;; successfully found next
(point-max)))) ;; there was no next
;; sort in order of decreasing end position
(nodes-in-file-sorted (->> (-zip nodes-in-file nodes-end-position)
(--sort (> (cdr it) (cdr other))))))
(dolist (node-and-end nodes-in-file-sorted)
(-let (((node . end-position) node-and-end))
(when (org-roam-backlinks-get node)
;; Add the references as a subtree of the node
(setq heading (format "\n\n%s References\n"
(s-repeat (+ (org-roam-node-level node) 1) "*")))
(setq properties-drawer ":PROPERTIES:\n:HTML_CONTAINER_CLASS: references\n:END:\n")
(dolist (backlink (org-roam-backlinks-get node))
(let* ((source-node (org-roam-backlink-source-node backlink))
(properties (org-roam-backlink-properties backlink))
(outline (when-let ((outline (plist-get properties :outline)))
(mapconcat #'org-link-display-format outline " > ")))
(point (org-roam-backlink-point backlink))
(text (s-replace "\n" " " (org-roam-preview-get-contents
(reference (format "%s [[id:%s][%s]]\n%s\n%s\n\n"
(s-repeat (+ (org-roam-node-level node) 2) "*")
(if outline (format "%s (/%s/)"
(s-repeat (+ (org-roam-node-level node) 3) "*") outline) "")