In the equations rendering challenge described in LaTeX With Emacs, org-fragtog came to the rescue, finally providing something to toggle between mathematical symbols and LaTeX code. But a computational notebook needs more than just mathematical equations rendered properly. It needs to be able to display and run code. Specifically, in my case, it needs to be able to run Python, R, and Julia.

Code Blocks

In Org Mode, #begin_src language ..... #end_src allows for code to be written and displayed correctly. For example:

#begin_src python
2+3
#end_src

These code blocks can be run with C-c C-. (They won’t necessaily work unless the setup steps below are completed.)

Org Babel Setup

Org Babel needs to be set up. Ensure that the Emacs config contains this. Note: The first part of the snippet below is deprecated. Julia-Vterm was necessary as the Babel backend for Julia did not work as desired. See SDS Project Configuration 2 for the update.

(with-eval-after-load 'org
  (org-babel-do-load-languages
   'org-babel-load-languages
   '((python . t)
     (julia  . t)
     (R      . t))))

(setq org-confirm-babel-evaluate nil)

The first part contains instructions for loading Babel language backends. The second part disables confirmation prompts for every instance of running code blocks. Understand the consequences of this line.

Warning

Do not run arbitrary code, especially from untrusted sources. We know the kind of havoc rm -rf... can cause. In the setup above, the shell language has not been included, so this particular command will not run. However, there are malicious workarounds like the one shown below in Python.

import subprocess
subprocess.run(["rm", "...", ...])

Language-Specific Configurations

By default, the codes did not generate results for me. I had to modify the snippets with :resutls output in this way to produce outputs.

#begin_src python :results output
2+3
#end_src

With :results value, the different languages responded differently. The table below summarizes my experience.

Language :results value :results output
Python works with return works with print()
R works works
Julia works after installing CSV + DataFrames works

Once all the language specific requirements were met, the notebook started working as desired, without the :results ... suffix. By default, we get the behavior of :results value when nothing is specified.

Example of a Working Notebook

This is an Org file, say, ComputationalTest.org.

#+title: Computational Test

* Python

#+begin_src python
import numpy as np
x = np.random.normal(size=1000)
return x.mean()
#+end_src

#+RESULTS:
: 0.021707804514847905

* R

#+begin_src R
x <- rnorm(1000)
mean(x)
#+end_src

#+RESULTS:
: 0.0409229767413901

* Julia

#+begin_src julia
using Statistics
x = randn(1000)
mean(x)
#+end_src

#+RESULTS:
: 0.01174148144640376

See also, SDS Project Configuration.