Search code examples
emacselisporg-mode

Org-mode & Elisp: How does one switch the buffer when using an ID to visit an entry?


I'm trying to write an Elisp function that opens an Org-mode entry given its ID and operates on that entry. When using org-open-link-from-string from org.el and the value of the entry's ID property, however, Emacs appears to jump to the entry (i.e., the entry's buffer appears, and the cursor moves to the correct entry), but any code that follows the call to org-open-link-from-string seems to operate on the original buffer.

For example, suppose you evaluate the following code in *scratch*, where XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX is a legit Org-mode ID in a file called Test.org. Again,

  • *scratch* is the buffer in which you evaluate the code below
  • Test.org is the buffer that contains the Org-mode entry with ID XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX

Here's the code to evaluate while in *scratch*:

(defun testfn-visit-org-entry (id)
  (org-open-link-from-string (concat "id:" id))
  (message "%s" (current-buffer))
  )
(testfn-visit-org-entry "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")

The Emacs cursor jumps to the correct entry in Test.org, but message prints *scratch*, the buffer we started in. Moreover, additional code that might follow the call to org-open-link-from-string operates in *scratch*, not Task.org.

Is there a way to fully jump to the entry corresponding to ID and actually switch to the appropriate buffer within the context of the Elisp function?


Solution

  • Try:

    (defun open-id (id)
     (org-id-goto id)
     (message "%s" (current-buffer)))
    

    That seems to do what you want.