Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Insert org-roam link using a footnote style
;; First implementation by lejon
;; https://discord.com/channels/406534637242810369/695219268358504458/781858450069782538
(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
`org-roam--get-title-path-completions`.
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
(unwind-protect
;; Group functions together to avoid inconsistent state on quit
(atomic-change-group
(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
(org-roam--get-title-path-completions))
(if filter-fn
(funcall filter-fn it)
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)
title-with-tags))
(target-file-path (plist-get res :path))
(description (or description region-text title))
(description (if lowercase
(downcase description)
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)))
(kill-current-buffer)
(setq target-id-footnote (aref target-vector-id 0))
(insert "[fn:" target-id-footnote "]")
(save-excursion
(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))))
(t
(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))
(org-roam-capture--capture))))
res))
(deactivate-mark)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment