Emacs org-mode lets you manage blocks of source code inside a text file. You can execute these blocks and have the output display in your text file. Or you could export the file, say to HTML or PDF, and show the code and/or the results of executing the code.
Here I’ll show some of the most basic possibilities. For much more information, see orgmode.org. And for the use of org-mode in research, see A Multi-Language Computing Environment for Literate Programming and Reproducible Research.
Source code blocks go between lines of the form
#+begin_src line, specify the programming language. Here I’ll demonstrate Python and R, but org-mode currently supports C++, Java, Perl, etc. for a total of 35 languages.
Suppose we want to compute √42 using R.
If we put the cursor somewhere in the code block and type C-c C-c, org-mode will add these lines:
Now suppose we do the same with Python:
from math import sqrt
This time we get disappointing results:
What happened? The org-mode manual explains:
… code should be written as if it were the body of such a function. In particular, note that Python does not automatically return a value from a function unless a
return statement is present, and so a ‘
return’ statement will usually be required in Python.
If we change
return sqrt(42) then we get the same result that we got when using R.
By default, evaluating a block of code returns a single result. If you want to see the output as if you were interactively using Python from the REPL, you can add
:results output :session following the language name.
#+begin_src python :results output :session
print "There are %d hours in a week." % (7*24)
This produces the lines
: There are 168 hours in a week.
:session tag, the second line would not appear because there was no
I had to do a couple things before I could get the examples above to work. First, I had to upgrade org-mode. The version of org-mode that shipped with Emacs 23.3 was quite out of date. Second, the only language you can run by default is Emacs Lisp. You have to turn on support for other languages in your
.emacs file. Here’s the code to turn on support for Python and R.
'org-babel-load-languages '((python . t) (R . t)))
Update: My next post shows how to call code in written in one language from code written in another language.