Evaluating a code block containing (switch-to-buffer "test-buffer") does not display test-buffer. It creates the buffer, but it does not switch to it.

#+BEGIN_SRC emacs-lisp
  (switch-to-buffer "test-buffer")

: #<buffer test-buffer>

Evaluating the the function within the code block, running eval-last-sexp, does display the buffer.

I cannot find any switches or header arguments controlling this behaviour, which might well be intended.

From what I can gather this is a more more specific instance of the same issue.

How can I obtain the desired behaviour?

  • 1
    What you want is answered here: Running elisp within an orgmode code block. I keep those function definitions in my Emacs startup files. Then just use :keep-windows t in your Emacs Lisp code block. In addition, you can use :session my-sh and have your my-sh shell window shown so you can display the evaluations you do from your source blocks with C-c Very nice for interactive presentations.
    – gregoryg
    Jul 4, 2020 at 14:43
  • emacs.stackexchange.com/tags/elisp/info
    – Drew
    Jul 4, 2020 at 18:06

1 Answer 1


Lisp code is evaluated by Org babel inside a save-window-excursion, so when you do switch-to-buffer in your code, you do switch to the buffer momentarily, but as soon as the evaluation is over, you are back in the Org mode buffer in order to format and print the result of the evaluation.

The doc string of save-window-excursion says:

Execute BODY, then restore previous window configuration. This macro saves the window configuration on the selected frame, executes BODY, then calls ‘set-window-configuration’ to restore the saved window configuration. The return value is the last form in BODY. The window configuration is also restored if BODY exits nonlocally.

In short, there is no (easy) way to do what you want with Org babel: it's not designed to work as an interactive evaluator - it's more of a batch processor. But you do have an interactive evaluator: emacs itself. What stops you from asking it to do a switch-buffer? In fact, if you just place the cursor after the closing paren of the form and do C-x C-e, you have switched to that buffer.

EDIT: although I think my answer stands, I wanted to preserve the link in @gregoryg's comment as part of the answer: it points to a tour-de-force answer by @Tobias that reimplements save-window-excursion so that it can be controlled by header-line arguments and that will allow window/buffer changes in source code blocks to be preserved. The hair-raising aspect of it is the surgery he does to the babel evaluator in order to use the reimplemented macro: this is code-modifying code and not for the faint-hearted.

Your Answer

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

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