9

I have the following:

#+BEGIN_SRC lisp :results value 
  (dolist (x '(1 2 3))
    (print x))

#+END_SRC

#+RESULTS:
: NIL

I want my results block to contain both the output and the value for my source. How do I do that?

1 Answer 1

10

:results value and :results output are collection options. From the org manual:

Collection options specify the results. Choose one of the options; they are mutually exclusive.

So they are mutually exclusive.

If the evaluation takes only little time you can call the source block twice with different collection options:

#+NAME: F
#+BEGIN_SRC emacs-lisp :results output
(dolist (x '(1 2 3))
  (print x))
"Hello World"
#+END_SRC

#+RESULTS: F
: 
: 1
: 
: 2
: 
: 3

#+CALL: F[:results value]()

#+RESULTS:
: Hello World

If the evaluation of the source block is costly you can redirect the output to the value of the block. I've written a macro with-cons-value.stdout for that purpose. If you encapsulate your lisp forms by that macro you get a cons with the last value of the lisp forms as car and the stdout string as cdr. If you need the macro multiple times you can move it from the source block to your init file.

#+BEGIN_SRC emacs-lisp :results value
(defmacro with-cons-value.stdout (&rest body)
  "Evaluate BODY like `progn'.
Return `cons' with value of BODY as `car' and
the standard output string as `cdr'."
  (declare (debug body))
  `(let ((old-stdout standard-output)
         stdout)
     (unwind-protect
         (progn
           (setq stdout (generate-new-buffer "stdout")
                 standard-output stdout)
           (cons
            (progn ,@body)
            (with-current-buffer stdout (buffer-string)))
           )
       (setq standard-output old-stdout)
       (kill-buffer stdout))))

(with-cons-value.stdout
 (dolist (x '(1 2 3))
   (print x))
 "Hello World")
#+END_SRC

#+RESULTS:
: (Hello World . 
: 1
: 
: 2
: 
: 3
: )
3
  • The specified link does not work anymore. The current one (at the time of writing this comment, of course) is this one.
    – applesoup
    Jul 25, 2021 at 16:13
  • 1
    @applesoup Thanks for the hint. Answers here are collaborative work. If you detect a simple error like that one you can correct it yourself if you want.
    – Tobias
    Jul 26, 2021 at 3:41
  • and thanks for that hint as well. I'll simply change things like that next time.
    – applesoup
    Jul 26, 2021 at 13:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.