Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to auto-suppress `#+RESULTS` for empty output?

In the following org-mode source snippet, no result is generated:

#+BEGIN_SRC ipython :session
  import numpy as np
#+END_SRC

However, upon execution #+RESULTS: is added to the document. How can I configure org-mode / babel to only insert results when there is something to display?

I know I can disable output using :results silent, but I'd prefer not to have to specify a different flag depending on whether a result is generated or not.

like image 272
Stefan van der Walt Avatar asked Oct 27 '25 09:10

Stefan van der Walt


2 Answers

Using ob-ipython with Org 9, I got this to work with the following hack, provided that source blocks are configured to return values (i.e., the default header specifies :results value):

; don't label empty outputs, exclude empty result blocks
(advice-add 'ob-ipython--process-response :filter-return
            (λ (contents)
               (if (string-match-p "\\`# Out\[[0-9]+\]:\n\\'" contents)
                   "" contents)))
(advice-add 'org-babel-insert-result :filter-args
            (λ (args)
               (let ((result (car args))
                     (result-params (cadr args))
                     (others (cddr args)))
                 (apply 'list
                        result
                        (if (string-empty-p result) '("silent") result-params)
                        others))))

The first advice strips the output tag inserted by ob-ipython when there is nothing further in the output (making the result empty), while the second advice effectively applies :results silent when the result is empty. These pieces could be arranged differently depending on your use case.

like image 125
thcoffee-msft Avatar answered Oct 29 '25 07:10

thcoffee-msft


I've added a check for a nil result to thcoffee-msft's answer to be compatible with emacs-jupyter. It also deletes any previous result if the current one is empty:

(advice-add 'org-babel-insert-result :filter-args
        (lambda (args)
          (let ((result (car args))
            (result-params (cadr args))
            (others (cddr args)))
        (apply 'list
               result
               (if (or
                (string-empty-p result) (not result))
               (progn (org-babel-remove-result) '("silent"))
                result-params)
               others))))
like image 20
sents Avatar answered Oct 29 '25 09:10

sents



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!