Updating Multiple RESULTS blocks in org-mode

| categories: orgmode | tags:

There was a recent question on the org-mode mailing list about getting multiple named block results to update when a named code block is run. I suppose you might want to do this if you need to see the results in more than one place. org-mode (at the moment) only updates the first named block that it finds from the beginning of the buffer. Challenge accepted ;)

Here is a function that will update all the named RESULTS blocks. The idea is to make a hook function that runs after you run a block. The hook function will get the block name, and if there is one, find all the named results in the buffer and update them.

(defun update-results ()
  ;; get name of src block
  (let ((name (org-element-property :name (org-element-at-point)))
        (results)
        (begin))
    (when name
      (setq results
            (save-excursion
              (goto-char (org-babel-find-named-result name))
              (forward-line)
              (buffer-substring
               (point) (org-element-property :end (org-element-at-point)))))
      (save-excursion
        (goto-char (point-min))
        (while (setq begin (org-babel-find-named-result name (point)))
          (goto-char begin)
          (forward-line)
          (setf (buffer-substring
                 (point)
                 (org-element-property :end (org-element-at-point)))
                results))))))

(add-hook 'org-babel-after-execute-hook 'update-results)
update-results (lambda nil (org-refresh-images))

Now let us test it out. Here is an unnamed block that should be ignored.

print 4
4

Here we have a named results block from a code block we will see later.

[0.0825119635983067, 0.12793443834890417, 0.5235765147357154]

Here is our named code block that just prints three random numbers.

import random

print [random.random() for i in range(3)]
[0.0825119635983067, 0.12793443834890417, 0.5235765147357154]

Swell, everytime I run the block, the named results get updated everywhere! It isn't tested more than this post, so I would spend some time trying out your use cases before doing anything mission critical. Your mileage might vary. For example, if you have a named block outside a narrowed region it is not clear to me it would update. In other words, there might be other corners where this doesn't update like you thing.

Copyright (C) 2015 by John Kitchin. See the License for information about copying.

org-mode source

Org-mode version = 8.2.10

Discuss on Twitter