Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Insert org-roam link using a footnote style
;; First implementation by lejon
(defun footnote/org-roam-insert (&optional lowercase completions filter-fn description link-type)
"Find an Org-roam file, and insert a relative org link to it at point.
Return selected file if it exists.
If LOWERCASE is non-nil, downcase the link description.
LINK-TYPE is the type of link to be created. It defaults to \"file\".
COMPLETIONS is a list of completions to be used instead of
FILTER-FN is the name of a function to apply on the candidates
which takes as its argument an alist of path-completions.
If DESCRIPTION is provided, use this as the link label. See
`org-roam--get-title-path-completions' for details."
(interactive "P")
(unless org-roam-mode (org-roam-mode))
;; Deactivate the mark on quit since `atomic-change-group' prevents it
;; Group functions together to avoid inconsistent state on quit
(let* (region-text
beg end
(_ (when (region-active-p)
(setq beg (set-marker (make-marker) (region-beginning)))
(setq end (set-marker (make-marker) (region-end)))
(setq region-text (buffer-substring-no-properties beg end))))
(completions (--> (or completions
(if filter-fn
(funcall filter-fn it)
(title-with-tags (org-roam-completion--completing-read "File: " completions
:initial-input region-text))
(res (cdr (assoc title-with-tags completions)))
(title (or (plist-get res :title)
(target-file-path (plist-get res :path))
(description (or description region-text title))
(description (if lowercase
(downcase description)
(cond ((and target-file-path
(file-exists-p target-file-path))
(when region-text
(delete-region beg end)
(set-marker beg nil)
(set-marker end nil))
(find-file target-file-path)
(setq target-vector-id
(car (org-roam--extract-ids target-file-path)))
(setq target-id-footnote (aref target-vector-id 0))
(insert "[fn:" target-id-footnote "]")
(org-footnote-goto-definition target-id-footnote
(org-footnote-create-definition target-id-footnote))
(insert " " (org-roam-format-link target-file-path description link-type))))
(let ((org-roam-capture--info `((title . ,title-with-tags)
(slug . ,(funcall org-roam-title-to-slug-function title-with-tags))))
(org-roam-capture--context 'title))
(setq org-roam-capture-additional-template-props (list :region (org-roam-shield-region beg end)
:insert-at (point-marker)
:link-type link-type
:link-description description
:finalize 'insert-link))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment