2011-02-27

executable source code blocks with org-babel

org-babel is the mechanism that org-mode offers for evaluating (executing) blocks of source code embedded in your org-mode-documents. This is useful for so-called reproducible research, i.e., where you allow your readers to go through the steps that led to your results.

Here, I'm just scratching the surface with some simple examples.

source code blocks

Let's first look at how it all began: source code blocks. I guess most org-mode-users will be familiar with those: the ability to include syntax-highlighted ('font-locked') snippets of source code in org-documents. We discussed source blocks before, they look like this:

#+begin_src perl
sub my_func {
        print "Hello, world!\n";
}
#+end_src

And note that code blocks can be edited in their 'native mode' using C-c'= (or, =org-edit-src-code).

When code block like this are exported to, say, HTML, they'll look like the following fully highlighted snippet (assuming you're reading Emacs-fu in it's full-color version):

sub my_func {
        print "Hello, world!\n";
}

evaluating source code

org-babel takes this a few steps further: instead of just looking at source code, we can actually evaluate (execute) it, using the org-mode-based system called org-babel.

If you have a recent version of org-mode (7.x or later), add the following to your .emacs (or equivalent):

(org-babel-do-load-languages
 'org-babel-load-languages
  '( (perl . t)         
     (ruby . t)
     (sh . t)
     (python . t)
     (emacs-lisp . t)   
   ))

This enables org-babel for the mentioned languages; there are many other languages available as well.

Now, suppose we have a snippet of python in an org-mode-buffer:

#+begin_src python
def hello(str):
        return "Hello, " + str + "!"
return hello ("dude")
#+end_src

You can move the cursor (point) inside the src-block and press C-c C-c (or, org-confirm-babel-evaluate). This causes the block of code to be evaluated (executed), after asking you for confirmation. The result will inserted below the block, like:

#+results:
: Hello, dude!

Note, in the hello example, the result of the block is the value of the evaluation - that is, the value of the last expression evaluated. This is the also the default, so we don't need to (but could) write:

#+begin_src python :results value

The alternative is to use the (standard) output of the function, which is activated with :results output, e.g.:

#+begin_src sh :results output
   echo "Hello $USER! Today is `date`"
#+end_src

Moving to this block and pressing C-c C=c would get you something like the following – probably with a different username and time:

˜#+results:
: Hello djcb! Today is Sun Feb 27 13:51:50 EET 2011

almost like functions

org-babel also allows you to refer to the code blocks from elsewhere in your document, by labeling your code-blocks with srcname. Let's say we have some Ruby code to revert a string:

#+begin_src ruby
def revert(s)
  if s == "" then 
    return ""
  else
    return s[-1].chr + revert(s.slice(0, s.length()-1))
  end
end
revert(str)
#+end_src

We can now 'call' this block; note that we get the result of evaluating the block. So if you want to use the result of a function in the block, you also need to add the call to that function (see the last line).

Now, we can use:

#+call: revert(str="VeryCoolStuff")

And we get:

: ffutSlooCyreV

Note, due to some limitation/bug in my version of org-babel, the strings should not contain spaces or other special characters, so the following will give result in an error note:

˜#+call: revert(str="Very Cool Stuff")

Whenever you try to evaluate a code block, emacs will ask for confirmation -- this is important, because of the obvious security implications of executing unknown code. Anyway, if you do trust the code, you can use the following to skip the confirmation:

(setq org-confirm-babel-evaluate nil)

These simple examples do not really capture the power that org-babel brings, but it's a start. There is quite a bit of documentation for org-babel to help you further. Finally, if you are already using org-babel, feel free to share your experiences in the comments!

6 comments:

Michaƫl Bruneel said...

Hi,

Thanks for your post ! Just to mention that you can insert #BEGIN_SRC and +END_SRC pairs with just a few key strokes : type '<s' followed by TAB and you get the block ;-)

http://orgmode.org/manual/Easy-Templates.html

yandros said...

Setting org-confirm-babel-evaluate to nil all the time is dicey, so you might be better off recommending ``C-u M-x set-variable RET org-confirm-babel-evaluate RET nil RET'', which turns off confirmations only in that buffer and in that session.

Michael King said...

I am running a compiled version of emacs 23.2, but do not seem to have the ability to evaluate source code with babel. The command org-confirm-babel-evaluate is not available at emacs runtime and setting org-babel-do-load-languages gives an emacs initialization error. "Symbol's function definition is void".

Did I not have some library installed at emacs compile time that babel needed? Thanks in advance for any help you can give.

Michael King said...

I quickly figured out that the org-mode version that I was using was the one that shipped with emacs 23.2, which I believe was 6.44 or something. After downloading org-mode 7.4 from the website, all is well.

However, when I add "(C++ . t)" to the org-babel-load-languages variable, I get the error "File error: Cannot open load file, ob-C++". However, this is how the C++ identifier is listed on the org website.

Anyone else run into this issue?

Wu said...

Hi Michael King, please use c++ instead of C++. I had similar problem in org2blog.

pimiento said...

When i say Org Edit Example to python code, then code open in new buffer. But when i try to save edited code, then it ask me name of file where i will be save code. And then doesn't return code to org-mode.