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.
:keep-windows t
in your Emacs Lisp code block. In addition, you can use:session my-sh
and have yourmy-sh
shell window shown so you can display the evaluations you do from your source blocks withC-c
Very nice for interactive presentations. – gregoryg Jul 4 '20 at 14:43