1 #+OPTIONS: H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:t -:t f:t *:t TeX:t LaTeX:t skip:nil d:(HIDE) tags:not-in-toc
2 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate hideblocks
3 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
4 #+TAGS: Write(w) Update(u) Fix(f) Check(c)
6 #+AUTHOR: Dan Davison, Eric Schulte
7 #+EMAIL: davison at stats dot ox dot ac dot uk
13 <p>executable source code blocks in org-mode</p>
17 <img src="images/tower-of-babel.png" alt="images/tower-of-babel.png"
18 title="And the Lord said, Behold, the people is one, and they have all one language; and this they begin to do; and now nothing will be restrained from them, which they have imagined to do. Genesis 11:1-9"/>
21 <a href="http://www.flickr.com/photos/23379658@N05/" title=""><b>Martijn Streefkerk</b></a>
34 :CUSTOM_ID: introduction
36 Org-babel is an extension to the very excellent [[http://orgmode.org/][Org-mode]]; an [[http://www.gnu.org/software/emacs/][Emacs]]
37 major mode for doing almost anything with plain text. If you are
38 not familiar with Org-mode please take a moment to read [[http://orgmode.org/][the Org-mode
39 homepage]] before continuing.
41 Org-babel provides the following modifications to [[http://orgmode.org/manual/Literal-examples.html][the existing
42 support]] for blocks of source code examples in the org-mode core.
43 1. interactive source code execution
44 2. arguments to source code blocks
45 3. exportation of source code blocks to files (literate programming)
47 Much of this document includes interactive examples. The reader is
48 encouraged to grab either the plain text version of this file
49 #+HTML: <a href="org-babel-worg.org">org-babel-worg.org</a>
50 which can be read and run in Emacs or the htmlized version of the
51 plain text of this file
52 #+HTML: <a href="org-babel-worg.org.html">org-babel-worg.html</a>
53 which is viewable through the web browser.
57 :CUSTOM_ID: getting-started
60 1) Grab the latest code from the git repo at [[http://github.com/eschulte/org-babel/tree/master][github/org-babel]]
62 git clone git://github.com/eschulte/org-babel.git
65 2) Add the following lines to your .emacs, replacing the path as
66 appropriate. A good place to check that things are up and running
67 would the examples in [[* Basic org-babel functionality][Basic org-babel functionality]].
68 #+begin_src emacs-lisp
69 (add-to-list 'load-path "/path/to/org-babel/lisp")
70 (require 'org-babel-init)
73 3) Then activate the subset of supported Org-babel languages which
74 you will want to be able to execute on your system. The
75 following can be added to your .emacs and used to activate
76 languages. It includes a brief list of the requirements for each
77 language. *Note*: this also serves as the list of languages
78 currently supported by Org-babel.
79 #+begin_src emacs-lisp
80 ;; Uncomment each of the following require lines if you want org-babel
81 ;; to support that language. Each language has a comment explaining
82 ;; it's dependencies. See the related files in lisp/langs for more
83 ;; detailed explanations of requirements.
84 ;; (require 'org-babel-R) ;; R and ess-mode
85 ;; (require 'org-babel-asymptote) ;; asymptote
86 ;; (require 'org-babel-css) ;; none
87 ;; (require 'org-babel-ditaa) ;; ditaa
88 ;; (require 'org-babel-dot) ;; dot
89 ;; (require 'org-babel-gnuplot) ;; gnuplot, and gnuplot-mode
90 ;; (require 'org-babel-haskell) ;; haskell, haskell-mode, inf-haskell
91 ;; (require 'org-babel-ocaml) ;; ocaml, and tuareg-mode
92 ;; (require 'org-babel-python) ;; python, and python-mode
93 ;; (require 'org-babel-ruby) ;; ruby, irb, ruby-mode, and inf-ruby
94 ;; (require 'org-babel-sass) ;; sass, sass-mode
95 ;; (require 'org-babel-sql) ;; none
97 ;; Once you've activated languages, load the library of babel for
98 ;; pre-built helpers in the languages you will be using.
99 (org-babel-load-library-of-babel)
102 * Basic org-babel functionality
104 :CUSTOM_ID: basic-functionality
106 *** Source code execution
108 :CUSTOM_ID: source-code-execution
110 For interpreted languages such as shell, python, R, etc, org-babel
111 allows source blocks to be executed: the code is passed to the
112 interpreter and you have control over what is done with the
113 results of excecution. E.g. place point anywhere in the following
114 block and use =C-c C-c= to run the code:
116 *Note:* calling =C-c C-o= on a source-code block will open the
119 [[http://www.ruby-lang.org/][Ruby]] source code
121 "This file was last evaluated on #{Date.today}"
124 Results of Ruby evaluation
126 : This file was last evaluated on 2009-08-09
128 [[http://www.r-project.org/][R]] source code
129 #+begin_src R :results value
135 Results of R evaluation
140 [[http://ditaa.sourceforge.net/][ditaa]] source code
141 #+begin_src ditaa :file images/blue.png :cmdline -r
152 [[file:images/blue.png]]
154 *** What happens to the results?
158 Org-babel provides two fundamentally different modes for capturing
159 the results of code evaluation, specified by the :results header
162 This means that the 'result' of code evaluation is defined to be
163 the *value* of the last statement in the block. Thus with this
164 setting, one can view the code block as a function with a return
165 value. And not only can one view it that way, but you can
166 actually use the return value of one source block as input for
167 another (see later). This setting is the default.
169 With this setting, org-babel captures all the text output of the
170 code block and places it in the org buffer. One can think of this
171 as a 'scripting' mode: the code block contains a series of
172 commands, and you get the output of all the commands. Unlike in
173 the 'functional' mode specified by =:results value=, the code
174 block has no return value. (This mode will be familiar to Sweave
176 **** Additional :results settings
178 *** Arguments to source code blocks
180 :CUSTOM_ID: arguments-to-source-code-blocks
182 In addition to evaluation of code blocks, org-babel allows them to
183 be parameterised (i.e. have arguments). Thus source code blocks
184 now have the status of *functions*.
186 Inputs for fibonacci-seq
188 #+tblname: fibonacci-inputs
189 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
190 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
192 in the Org-mode buffer this looks like
193 : #+tblname: fibonacci-inputs
194 : | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
195 : | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
197 [[http://www.gnu.org/software/emacs/manual/elisp.html][Emacs Lisp]] source code
198 #+srcname: fibonacci-seq
199 #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
201 (if (or (= n 0) (= n 1))
203 (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
205 (mapcar (lambda (row)
206 (mapcar #'fibonacci row)) fib-inputs)
209 in the Org-mode buffer this looks like
210 : #+srcname: fibonacci-seq
211 : #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
212 : (defun fibonacci (n)
213 : (if (or (= n 0) (= n 1))
215 : (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
217 : (mapcar (lambda (row)
218 : (mapcar #'fibonacci row)) fib-inputs)
221 Results of Emacs Lisp code evaluation
223 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
224 | 1 | 3 | 8 | 21 | 55 | 144 | 377 | 987 | 2584 | 6765 |
226 * A meta-programming language for org-mode
228 :CUSTOM_ID: meta-programming-language
231 Since information can pass freely between source-code blocks and
232 org-mode tables you can mix and match languages using each language
233 for those tasks to which it is suited. This makes Org-mode files with
234 Org-babel into a kind of meta-functional programming language in which
235 functions from many languages can work together.
237 As an example, lets take some system diagnostics in the shell, and
238 then graph them with R.
241 #+srcname: directories
242 #+begin_src bash :results replace
243 cd ~ && du -sc * |grep -v total
245 2. Results of the shell source code (on my system, grab this org-mode
246 files and try running it on your own)
247 #+resname: directories
249 | 12156104 | "Documents" |
250 | 3482440 | "Downloads" |
251 | 2901720 | "Library" |
253 | 16548024 | "Music" |
255 | 7649472 | "Pictures" |
263 3. R source code (which calls the previous shell source code)
264 #+srcname: directory-pie
265 #+begin_src R :var dirs = directories :session R-pie-example
266 pie(dirs[,1], labels = dirs[,2])
268 4. Results of R code [[file:images/dirs.png]]
270 * Spreadsheet plugins for org-mode in any language
272 :CUSTOM_ID: spreadsheet
275 *NOTE*: Maybe in-addition-to/in-stead-of this example we should do a
276 more traditional "spreadsheet" example with R [Eric]
278 Not only can Org-babel pass entire tables of data to source code
279 blocks (see [[arguments-to-source-code-blocks]]), Org-babel can also be
280 used to call source code blocks from *within* tables using the
281 Org-mode's [[http://orgmode.org/manual/The-spreadsheet.html#The-spreadsheet][existing spreadsheet functionality]].
283 In fact the functional test suite for Org-babel is implemented as a
284 large Org-mode table. To run the entire test suite you simple
285 evaluate the table =C-u C-c C-c=, and all of the tests are run
286 updating the table with pass/fail statistics.
288 Here's a sample of our test suite.
290 #+TBLNAME: org-babel-tests
291 | functionality | block | arg | expected | results | pass |
292 |------------------+--------------+-----+-------------+-------------+------|
293 | basic evaluation | | | | | pass |
294 |------------------+--------------+-----+-------------+-------------+------|
295 | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
296 | shell | basic-shell | | 6 | 6 | pass |
297 | ruby | basic-ruby | | org-babel | org-babel | pass |
298 | python | basic-python | | hello world | hello world | pass |
299 | R | basic-R | | 13 | 13 | pass |
300 #+TBLFM: $5='(if (= (length $3) 1) (progn (message (format "running %S" '(sbe $2 (n $3)))) (sbe $2 (n $3))) (sbe $2))::$6='(if (string= $4 $5) "pass" (format "expected %S but was %S" $4 $5))
301 #+TBLFM: $5=""::$6=""
303 *** code blocks for tests
305 #+srcname: basic-elisp
306 #+begin_src emacs-lisp :var n=7
310 #+srcname: basic-shell
311 #+begin_src sh :results silent
315 #+srcname: date-simple
316 #+begin_src sh :results silent
320 #+srcname: basic-ruby
321 #+begin_src ruby :results silent
325 #+srcname: basic-python
326 #+begin_src python :results silent
331 #+begin_src R :results silent
338 :CUSTOM_ID: library-of-babel
340 What about those source code blocks which are so useful you want to
341 have them available in every org-mode buffer?
343 The [[file:library-of-babel.org][Library of Babel]] is an extensible collection of ready-made and
344 easily-shortcut-callable source-code blocks for handling common
345 tasks. Org-babel comes pre-populated with the source-code blocks
346 located in the [[file:library-of-babel.org][library-of-babel.org]] file. It is possible to add
347 source-code blocks from any org-mode file to the library by calling
349 #+srcname: add-file-to-lob
350 #+begin_src emacs-lisp
351 (org-babel-lob-ingest "path/to/file.org")
354 * Reproducible Research
356 :CUSTOM_ID: reproducable-research
359 An article about computational science in a scientific publication is
360 not the scholarship itself, it is merely advertising of the
361 scholarship. The actual scholarship is the complete software
362 development environment and the complete set of instructions which
363 generated the figures.
368 [[http://reproducibleresearch.net/index.php/Main_Page][Reproducible Research]] (RR) is the practice of distributing along with
369 an article of research all data, code, and tools required to reproduce
370 the results discussed in the paper. As such the paper becomes not
371 only a document describing the research but a complete laboratory
372 reproducing the research.
374 Org-mode already has exceptional support for [[http://orgmode.org/manual/Exporting.html#Exporting][exporting to html and
375 LaTeX]]. Org-babel makes Org-mode a tool for RR by *activating* the
376 data and source code embedded into Org-mode documents making the
377 entire document executable. This makes it not only possible, but
378 natural to distribute research in a format that encourages readers to
379 recreate your results, and perform their own analysis.
381 Existing RR tools like [[http://en.wikipedia.org/wiki/Sweave][Sweave]] provide for the embedding of [[http://www.r-project.org/][R]] code into
382 LaTeX documents. While this is very useful, such documents often
383 still require a large degree of "glue code" in the form of external
384 shell scripts, python scripts, and Makefiles. To our knowledge
385 Org-babel is the only RR tool which allows multiple languages and data
386 to coexist and cooperate inside of a single document.
388 * Literate programming
390 :CUSTOM_ID: literate-programming
394 Let us change our traditional attitude to the construction of
395 programs: Instead of imagining that our main task is to instruct a
396 /computer/ what to do, let us concentrate rather on explaining to
397 /human beings/ what we want a computer to do.
399 The practitioner of literate programming can be regarded as an
400 essayist, whose main concern is with exposition and excellence of
401 style. Such an author, with thesaurus in hand, chooses the names of
402 variables carefully and explains what each variable means. He or she
403 strives for a program that is comprehensible because its concepts have
404 been introduced in an order that is best for human understanding,
405 using a mixture of formal and informal methods that reinforce each
411 Org-babel supports [[http://en.wikipedia.org/wiki/Literate_programming][Literate Programming]] (LP) by allowing the act of
412 programming to take place inside of Org-mode documents. The Org-mode
413 file can then be exported (*woven* in LP speak) to html or LaTeX for
414 consumption by a human, and the embedded source code can be extracted
415 (*tangled* in LP speak) into structured source code files for
416 consumption by a computer.
418 To support these operations Org-babel relies on Org-mode's [[http://orgmode.org/manual/Exporting.html#Exporting][existing
419 exporting functionality]] for *weaving* of documentation, and on the
420 =org-babel-tangle= function which makes use of [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] [[reference-expansion][reference syntax]]
421 for *tangling* of code files.
423 The [[literate-programming-example][following example]] demonstrates the process of *tangling* in
426 *** Simple Literate Programming Example (Noweb syntax)
428 :CUSTOM_ID: literate-programming-example
431 Tangling functionality is controlled by the =tangle= family of
432 [[header-arguments]]. These arguments can be used to turn tangling on or
433 off (the default) on the source code block, or the outline heading
436 The following demonstrates the combination of three source code blocks
437 into a single source code file using =org-babel-tangle=.
439 The following two blocks will not be tangled by default since they
440 have no =tangle= header arguments.
442 #+srcname: hello-world-prefix
443 #+begin_src sh :exports none
444 echo "/-----------------------------------------------------------\\"
447 : #+srcname: hello-world-prefix
448 : #+begin_src sh :exports none
449 : echo "/-----------------------------------------------------------\\"
452 #+srcname: hello-world-postfix
453 #+begin_src sh :exports none
454 echo "\-----------------------------------------------------------/"
457 : #+srcname: hello-world-postfix
458 : #+begin_src sh :exports none
459 : echo "\-----------------------------------------------------------/"
463 The third block does have a =tangle= header argument indicating the
464 name of the file to which it should be written. It also has [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]]
465 style references to the two previous source code blocks which will be
466 expanded during tangling to include them in the output file as well.
468 #+srcname: hello-world
469 #+begin_src sh :tangle hello :exports none
470 # <<hello-world-prefix>>
471 echo "| hello world |"
472 # <<hello-world-postfix>>
475 : #+srcname: hello-world
476 : #+begin_src sh :tangle hello :exports none
477 : # <<hello-world-prefix>>
478 : echo "| hello world |"
479 : # <<hello-world-postfix>>
482 Calling =org-babel-tangle= will result in the following being written
483 to the =hello.sh= file.
485 #+srcname: hello-world-output
488 # generated by org-babel-tangle
490 # [[file:~/src/org-babel/org-babel-worg.org::#literate-programming-example][block-16]]
491 # <<hello-world-prefix>>
492 echo "/-----------------------------------------------------------\\"
494 echo "| hello world |"
495 # <<hello-world-postfix>>
496 echo "\-----------------------------------------------------------/"
500 *** Emacs Initialization with Org-babel
501 Org-babel has special support for embedding your emacs initialization
502 into Org-mode files. The =org-babel-load-file= function can be used
503 to load the emacs lisp embedded in a literate Org-mode file in the
504 same way that you might load a regular elisp file.
506 This allows you to have all the niceness of Org-mode (folding, tags,
507 notes, html export, etc...) available in your emacs initialization.
509 To try this out either see the simple [[literate-emacs-init][Literate Emacs Initialization]]
510 example directly below, or check out the Org-babel Literate
511 Programming version of Phil Hagelberg's excellent [[http://github.com/technomancy/emacs-starter-kit/tree/master][emacs-starter-kit]]
512 available at [[http://github.com/eschulte/emacs-starter-kit/tree/master][Org-babel-emacs-starter-kit]].
514 ***** Literate Emacs Initialization
516 :CUSTOM_ID: literate-emacs-init
519 For a simple example of usage follow these 4 steps.
521 1) create a directory named =.emacs.d= in the base of your home
526 2) checkout the latest versions of Org-mode and Org-babel into the src
527 subdirectory of this new directory
532 git clone git://repo.or.cz/org-mode.git
533 git clone git://github.com/eschulte/org-babel.git
535 3) place the following in a file called =init.el= in your emacs
536 initialization directory (=~/.emacs.d=).
537 #+srcname: emacs-init
538 #+begin_src emacs-lisp
539 ;;; init.el --- Where all the magic begins
541 ;; This file loads both
542 ;; - Org-mode : http://orgmode.org/ and
543 ;; - Org-babel: http://eschulte.github.com/org-babel/
545 ;; It then loads the rest of our Emacs initialization from Emacs lisp
546 ;; embedded in literate Org-mode files.
548 ;; Load up Org Mode and Org Babel for elisp embedded in Org Mode files
549 (setq dotfiles-dir (file-name-directory (or (buffer-file-name) load-file-name)))
550 (add-to-list 'load-path (expand-file-name
551 "lisp" (expand-file-name
552 "org" (expand-file-name
553 "src" dotfiles-dir))))
554 (add-to-list 'load-path (expand-file-name
555 "lisp" (expand-file-name
556 "org-babel" (expand-file-name
557 "src" dotfiles-dir))))
558 (require 'org-babel-init)
560 ;; load up all literate org-mode files in this directory
561 (mapc #'org-babel-load-file (directory-files dotfiles-dir t "\\.org$"))
563 ;;; init.el ends here
565 4) Implement all of your emacs customizations inside of elisp
566 source-code blocks located in Org-mode files in this directory.
567 They will be loaded by emacs on startup.
569 * Reference / Documentation
571 :CUSTOM_ID: reference-and-documentation
574 *** Source Code block syntax
576 The basic syntax of source-code blocks is as follows:
579 : #+begin_src language header-arguments
583 - name :: This name is associated with the source-code block. This is
584 similar to the =#+TBLNAME= lines which can be used to name tables
585 in org-mode files. By referencing the srcname of a source-code
586 block it is possible to evaluate the block for other places,
587 files, or from inside tables.
588 - language :: The language of the code in the source-code block, valid
589 values must be members of `org-babel-interpreters'.
590 - header-arguments :: Header arguments control many facets of the
591 input to, evaluation of, and output of source-code blocks. See
592 the [[* Header Arguments][Header Arguments]] section for a complete review of available
594 - body :: The actual source code which will be evaluated. This can be
595 edited with `org-edit-special'.
599 :CUSTOM_ID: header-arguments
602 - results :: results arguments specify what should be done with the
603 output of source-code blocks
604 - The following options are mutually exclusive, and specify how the
605 results should be collected from the source-code block
608 - The following options are mutually exclusive and specify what type
609 of results the code block will return
610 - vector :: specifies that the results should be interpreted as a
611 multidimensional vector (even if the vector is
612 trivial), and will be inserted into the org-mode file
614 - scalar :: specifies that the results should be interpreted as a
615 scalar value, and will be inserted into the org-mode
617 - file :: specifies that the results should be interpreted as the
618 path to a file, and will be inserted into the org-mode
620 - The following options specify how the results should be inserted
621 into the org-mode file
622 - replace :: the current results replace any previously inserted
623 results from the code block
624 - silent :: rather than being inserted into the org-mode file the
625 results are echoed into the message bar
626 - exports :: exports arguments specify what should be included in html
627 or latex exports of the org-mode file
628 - code :: the body of code is included into the exported file
629 - results :: the results of evaluating the code is included in the
631 - both :: both the code and results are included in the exported
633 - none :: nothing is included in the exported file
634 - tangle :: tangle arguments specify whether or not the source-code
635 block should be included in tangled extraction of
637 - yes :: the source-code block is exported to a source-code file
638 named after the basename (name w/o extension) of the
640 - no :: (default) the source-code block is not exported to a
642 - other :: any other string passed to the =tangle= header argument
643 is interpreted as a file basename to which the block will
646 *** Noweb reference syntax
647 The [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] Literate Programming system allows named blocks of code to
648 be referenced by using a =<<code-block-name>>= syntax. When a
649 document is tangled these references are replaced with the named code.
650 An example is provided in the [[literate-programming-example]] in this