Categories: embark

RSS - Atom - Subscribe via email

Insert a link to an Org Mode heading from an org-refile prompt

| emacs, embark, org

I often want to link to an Org heading from somewhere in my org-refile-targets, which includes my agenda files and other things. I don't want to think about where the heading is, I just want to link to it. I could use C-u C-c C-w (org-refile) to go to the heading, use C-c l (my shortcut for org-store-link), head back with org-mark-ring-goto, and then insert it with C-c C-l (org-insert-link).

Or I can use this code to make an Embark command that hooks into minibuffer prompts that include "goto" or "refile", so I can link to something with C-. i right from a refile or goto query.

(defun my-embark-org-insert-link-from-path (path)
  (interactive (list (car (org-refile-get-location))))
  (let* ((extra (if org-refile-use-outline-path "/" ""))
         (tbl (mapcar
               (lambda (x)
                 (if (and (not (member org-refile-use-outline-path
                                       '(file full-file-path title)))
                          (not (equal filename (file-truename (nth 1 x)))))
                     (cons (concat (car x) extra " ("
                                   (file-name-nondirectory (nth 1 x)) ")")
                           (cdr x))
                   (cons (concat (car x) extra) (cdr x))))
               org-refile-target-table))
         link)
    (insert (save-window-excursion
              (save-excursion
                (org-goto-marker-or-bmk
                 (elt
                  (org-refile--get-location path tbl)
                  3))
                (org-store-link nil))))))
(defvar-keymap my-org-path-map
  :doc "Shortcuts for working with Org paths from `org-refile'."
  "i" #'my-embark-org-insert-link-from-path)
(with-eval-after-load 'marginalia
  (add-to-list 'marginalia-prompt-categories '("Goto\\|Refile" . my-org-path)))
(with-eval-after-load 'embark
  (add-to-list 'embark-keymap-alist '(my-org-path . my-org-path-map)))
2024-10-24_10-34-21.png
Figure 1: Screenshot of Embark menu invoked with "C-.", showing the new "i" shortcut for inserting a link

There are more Embark shortcuts in my Embark configuration.

This is part of my Emacs configuration.
View org source for this post