added "existing similar tools" section to publish task
[org-mode.git] / org-babel-worg.org
blob12c3ea71f3b68b9f9ce1cc1c8127a878fd2f09c8
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) 
5 #+TITLE:      Org-babel
6 #+AUTHOR:     Dan Davison, Eric Schulte
7 #+EMAIL:      davison at stats dot ox dot ac dot uk
8 #+LANGUAGE:   en
9 #+CATEGORY:   worg
11 #+begin_html 
12   <div id="subtitle">
13     <p>executable source code blocks in org-mode</p>
14   </div>
15   <div id="logo">
16     <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"/>
19       <div id="attr">
20         from
21         <a href="http://www.flickr.com/photos/23379658@N05/" title=""><b>Martijn Streefkerk</b></a>
22       </div>
23     </p>
24   </div>
25 #+end_html
27 * Introduction
28   :PROPERTIES:
29   :CUSTOM_ID: introduction
30   :END:
31   Org-babel provides the following modifications to [[http://orgmode.org/manual/Literal-examples.html][the existing
32   support]] for blocks of source code examples in the org-mode core.
33   1. source code execution
34   2. arguments to source code blocks
35   3. exportation of source code blocks to files (literate programming)
37 * Getting started
38   :PROPERTIES:
39   :CUSTOM_ID: getting-started
40   :END:
42   1) Grab the latest code from the git repo at [[http://github.com/eschulte/org-babel/tree/master][github/org-babel]]
43      #+begin_src sh
44      git clone git://github.com/eschulte/org-babel.git
45      #+end_src
47   2) Add the following lines to your .emacs, replacing the path as
48      appropriate. A good place to check that things are up and running
49      would the examples in [[* Basic org-babel functionality][Basic org-babel functionality]].
50      #+begin_src emacs-lisp
51        (add-to-list 'load-path "/path/to/org-babel/lisp")
52        (require 'org-babel-init)
53      #+end_src
55   3) Then activate the subset of supported Org-babel languages which
56      you will want to be able to execute on your system.  The
57      following can be added to your .emacs and used to activate
58      languages.  It includes a brief list of the requirements for each
59      language.
60      #+begin_src emacs-lisp 
61        ;; Uncomment each of the following require lines if you want org-babel
62        ;; to support that language.  Each language has a comment explaining
63        ;; it's dependencies.  See the related files in lisp/langs for more
64        ;; detailed explanations of requirements.
65        ;; (require 'org-babel-R)         ;; R and ess-mode
66        ;; (require 'org-babel-asymptote) ;; asymptote
67        ;; (require 'org-babel-css)       ;; none
68        ;; (require 'org-babel-ditaa)     ;; ditaa
69        ;; (require 'org-babel-dot)       ;; dot
70        ;; (require 'org-babel-gnuplot)   ;; gnuplot, and gnuplot-mode
71        ;; (require 'org-babel-ocaml)     ;; ocaml, and tuareg-mode
72        ;; (require 'org-babel-python)    ;; python, and python-mode
73        ;; (require 'org-babel-ruby)      ;; ruby, irb, ruby-mode, and inf-ruby mode
74        ;; (require 'org-babel-sql)       ;; none
75        ;; 
76        ;; Once you've activated languages, load the library of babel for
77        ;; pre-built helpers in the languages you will be using.
78        (org-babel-load-library-of-babel)
79      #+end_src
80   
81 * Basic org-babel functionality
82   :PROPERTIES:
83   :CUSTOM_ID: basic-functionality
84   :END:
85 *** Source code execution
86     :PROPERTIES:
87     :CUSTOM_ID: source-code-execution
88     :END:
89     For interpreted languages such as shell, python, R, etc, org-babel
90     allows source blocks to be executed: the code is passed to the
91     interpreter and you have control over what is done with the
92     results of excecution. E.g. place point anywhere in the following
93     block and use C-c C-c to run the code:
95 [[http://www.ruby-lang.org/][Ruby]] source code
96 #+begin_src ruby
97 "This file was last evaluated on #{Date.today}"
98 #+end_src
100 Results of Ruby evaluation
101 #+resname:
102 : This file was last evaluated on 2009-08-09
104 [[http://www.r-project.org/][R]] source code
105 #+begin_src R :results value
106 x = 4
107 date()
108 c(5, 10)
109 #+end_src
111 Results of R evaluation
112 #+resname:
113 |  5 |
114 | 10 |
116 *** What happens to the results?
117     :PROPERTIES:
118     :CUSTOM_ID: results
119     :END:
120     Org-babel provides two fundamentally different modes for capturing
121     the results of code evaluation, specified by the :results header
122     argument:
123 **** :results value
124      This means that the 'result' of code evaluation is defined to be
125      the *value* of the last statement in the block. Thus with this
126      setting, one can view the code block as a function with a return
127      value. And not only can one view it that way, but you can
128      actually use the return value of one source block as input for
129      another (see later). This setting is the default.
130 **** :results output
131      With this setting, org-babel captures all the text output of the
132      code block and places it in the org buffer. One can think of this
133      as a 'scripting' mode: the code block contains a series of
134      commands, and you get the output of all the commands. Unlike in
135      the 'functional' mode specified by =:results value=, the code
136      block has no return value. (This mode will be familiar to Sweave
137      users).
138 **** Additional :results settings
139      
140 *** Arguments to source code blocks
141     :PROPERTIES:
142     :CUSTOM_ID: arguments-to-source-code-blocks
143     :END:
144     In addition to evaluation of code blocks, org-babel allows them to
145     be parameterised (i.e. have arguments). Thus source code blocks
146     now have the status of *functions*.
148 Inputs for fibonacci-seq
150 #+tblname: fibonacci-inputs
151 | 1 | 2 | 3 | 4 |  5 |  6 |  7 |  8 |  9 | 10 |
152 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
154 in the Org-mode buffer this looks like
155 : #+tblname: fibonacci-inputs
156 : | 1 | 2 | 3 | 4 |  5 |  6 |  7 |  8 |  9 | 10 |
157 : | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
159 [[http://www.gnu.org/software/emacs/manual/elisp.html][Emacs Lisp]] source code
160 #+srcname: fibonacci-seq
161 #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
162   (defun fibonacci (n)
163     (if (or (= n 0) (= n 1))
164         n
165       (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
166   
167   (mapcar (lambda (row)
168             (mapcar #'fibonacci row)) fib-inputs)
169 #+end_src
171 in the Org-mode buffer this looks like
172 : #+srcname: fibonacci-seq
173 : #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
174 :   (defun fibonacci (n)
175 :     (if (or (= n 0) (= n 1))
176 :         n
177 :       (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
178 :   
179 :   (mapcar (lambda (row)
180 :             (mapcar #'fibonacci row)) fib-inputs)
181 : #+end_src
183 Results of Emacs Lisp code evaluation
184 #+resname:
185 | 1 | 1 | 2 |  3 |  5 |   8 |  13 |  21 |   34 |   55 |
186 | 1 | 3 | 8 | 21 | 55 | 144 | 377 | 987 | 2584 | 6765 |
188 * A meta-programming language for org-mode
189   :PROPERTIES:
190   :CUSTOM_ID: meta-programming-language
191   :END:
193 Since information can pass freely between source-code blocks and
194 org-mode tables you can mix and match languages using each language
195 for those tasks to which it is suited.  This makes Org-mode files with
196 Org-babel into a kind of meta-functional programming language in which
197 functions from many languages can work together.
199 As an example, lets take some system diagnostics in the shell, and
200 then graph them with R.
202 1. Shell source code
203 #+srcname: directories
204    #+begin_src bash :results replace
205    cd ~ && du -sc * |grep -v total
206    #+end_src
207 2. Results of the shell source code (on my system, grab this org-mode
208    files and try running it on your own)
209 #+resname: directories
210 |       72 | "Desktop"   |
211 | 12156104 | "Documents" |
212 |  3482440 | "Downloads" |
213 |  2901720 | "Library"   |
214 |    57344 | "Movies"    |
215 | 16548024 | "Music"     |
216 |      120 | "News"      |
217 |  7649472 | "Pictures"  |
218 |        0 | "Public"    |
219 |   152224 | "Sites"     |
220 |        8 | "System"    |
221 |       56 | "bin"       |
222 |  3821872 | "mail"      |
223 | 10605392 | "src"       |
224 |     1264 | "tools"     |
225 3. R source code (which calls the previous shell source code)
226 #+srcname: directory-pie
227    #+begin_src R :var dirs = directories :session R-pie-example
228    pie(dirs[,1], labels = dirs[,2])
229    #+end_src
230 4. Results of R code [[file:images/dirs.png]]
232 * Spreadsheet plugins for org-mode in any language
233   :PROPERTIES:
234   :CUSTOM_ID: spreadsheet
235   :END:
237 *NOTE*: Maybe in-addition-to/in-stead-of this example we should do a
238 more traditional "spreadsheet" example with R [Eric]
240 Not only can Org-babel pass entire tables of data to source code
241 blocks (see [[arguments-to-source-code-blocks]]), Org-babel can also be
242 used to call source code blocks from *within* tables using the
243 Org-mode's [[http://orgmode.org/manual/The-spreadsheet.html#The-spreadsheet][existing spreadsheet functionality]].
245 In fact the functional test suite for Org-babel is implemented as a
246 large Org-mode table.  To run the entire test suite you simple
247 evaluate the table =C-u C-c C-c=, and all of the tests are run
248 updating the table with pass/fail statistics.
250 Here's a sample of our test suite.
252 #+TBLNAME: org-babel-tests
253 | functionality    | block        | arg |    expected |     results | pass |
254 |------------------+--------------+-----+-------------+-------------+------|
255 | basic evaluation |              |     |             |             | pass |
256 |------------------+--------------+-----+-------------+-------------+------|
257 | emacs lisp       | basic-elisp  |   2 |           4 |           4 | pass |
258 | shell            | basic-shell  |     |           6 |           6 | pass |
259 | ruby             | basic-ruby   |     |   org-babel |   org-babel | pass |
260 | python           | basic-python |     | hello world | hello world | pass |
261 | R                | basic-R      |     |          13 |          13 | pass |
262 #+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))
263 #+TBLFM: $5=""::$6=""
265 *** code blocks for tests
267 #+srcname: basic-elisp
268 #+begin_src emacs-lisp :var n=7
269 (* 2 n)
270 #+end_src
272 #+srcname: basic-shell
273 #+begin_src sh :results silent
274 expr 1 + 5
275 #+end_src
277 #+srcname: date-simple
278 #+begin_src sh :results silent
279 date
280 #+end_src
282 #+srcname: basic-ruby
283 #+begin_src ruby :results silent
284 "org-babel"
285 #+end_src
287 #+srcname: basic-python
288 #+begin_src python :results silent
289 'hello world'
290 #+end_src
292 #+srcname: basic-R
293 #+begin_src R :results silent
294 b <- 9
295 b + 4
296 #+end_src
298 * Library of Babel
299   :PROPERTIES:
300   :CUSTOM_ID: library-of-babel
301   :END:
302   What about those source code blocks which are so useful you want to
303   have them available in every org-mode buffer?
305   The [[file:library-of-babel.org][Library of Babel]] is an extensible collection of ready-made and
306   easily-shortcut-callable source-code blocks for handling common
307   tasks.  Org-babel comes pre-populated with the source-code blocks
308   located in the [[file:library-of-babel.org][library-of-babel.org]] file. It is possible to add
309   source-code blocks from any org-mode file to the library by calling
311 #+srcname: add-file-to-lob
312 #+begin_src emacs-lisp 
313 (org-babel-lob-ingest "path/to/file.org")
314 #+end_src
316 * Reproducible Research
317   :PROPERTIES:
318   :CUSTOM_ID: reproducable-research
319   :END:
320 #+begin_quote 
321 An article about computational science in a scientific publication is
322 not the scholarship itself, it is merely advertising of the
323 scholarship. The actual scholarship is the complete software
324 development environment and the complete set of instructions which
325 generated the figures.
327 -- D. Donoho
328 #+end_quote
330 [[http://reproducibleresearch.net/index.php/Main_Page][Reproducible Research]] (RR) is the practice of distributing along with
331 an article of research all data, code, and tools required to reproduce
332 the results discussed in the paper.  As such the paper becomes not
333 only a document describing the research but a complete laboratory
334 reproducing the research.
336 Org-mode already has exceptional support for [[http://orgmode.org/manual/Exporting.html#Exporting][exporting to html and
337 LaTeX]].  Org-babel makes Org-mode a tool for RR by *activating* the
338 data and source code embedded into Org-mode documents making the
339 entire document executable.  This makes it not only possible, but
340 natural to distribute research in a format that encourages readers to
341 recreate your results, and perform their own analysis.
343 Existing RR tools like [[http://en.wikipedia.org/wiki/Sweave][Sweave]] provide for the embedding of [[http://www.r-project.org/][R]] code into
344 LaTeX documents.  While this is very useful, such documents often
345 still require a large degree of "glue code" in the form of external
346 shell scripts, python scripts, and Makefiles.  To my knowledge
347 Org-babl is the only RR tool which allows multiple languages and data
348 to coexist and cooperate inside of a single document.
350 * Literate programming
351   :PROPERTIES:
352   :CUSTOM_ID: literate-programming
353   :END:
355 #+begin_quote 
356 Let us change our traditional attitude to the con- struction of
357 programs: Instead of imagining that our main task is to instruct a
358 /computer/ what to do, let us concentrate rather on explaining to
359 /human beings/ what we want a computer to do.
361 The practitioner of literate programming can be regarded as an
362 essayist, whose main concern is with exposition and excellence of
363 style. Such an author, with thesaurus in hand, chooses the names of
364 variables carefully and explains what each variable means. He or she
365 strives for a program that is comprehensible because its concepts have
366 been introduced in an order that is best for human understanding,
367 using a mixture of formal and informal methods that reinforce each
368 other.
370  -- Donald Knuth
371 #+end_quote
373 Org-babel supports [[http://en.wikipedia.org/wiki/Literate_programming][Literate Programming]] (LP) by allowing the act of
374 programming to take place inside of Org-mode documents.  The Org-mode
375 file can then be exported (*woven* in LP speak) to html or LaTeX for
376 consumption by a human, and the embedded source code can be extracted
377 (*tangled* in LP speak) into structured source code files for
378 consumption by a computer.
380 To support these operations Org-babel relies on Org-mode's [[http://orgmode.org/manual/Exporting.html#Exporting][existing
381 exporting functionality]] for *weaving* of documentation, and on the
382 =org-babel-tangle= function which makes use of [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] [[reference-expansion][reference syntax]]
383 for *tangling* of code files.
385 The [[literate-programming-example][following example]] demonstrates the process of *tangling* in
386 Org-babel.
388 *** Literate Programming Example
389     :PROPERTIES:
390     :CUSTOM_ID: literate-programming-example
391     :END:
393 Tangling functionality is controlled by the =tangle= family of
394 [[header-arguments]].  These arguments can be used to turn tangling on or
395 off (the default) on the source code block, or the outline heading
396 level.
398 The following demonstrates the combination of three source code blocks
399 into a single source code file using =org-babel-tangle=.
401 The following two blocks will not be tangled by default since they
402 have no =tangle= header arguments.
404 #+srcname: hello-world-prefix
405 #+begin_src sh :exports none
406   echo "/-----------------------------------------------------------\\"
407 #+end_src
409 : #+srcname: hello-world-prefix
410 : #+begin_src sh :exports none
411 :   echo "/-----------------------------------------------------------\\"
412 : #+end_src
414 #+srcname: hello-world-postfix
415 #+begin_src sh :exports none
416   echo "\-----------------------------------------------------------/"
417 #+end_src
419 : #+srcname: hello-world-postfix
420 : #+begin_src sh :exports none
421 :   echo "\-----------------------------------------------------------/"
422 : #+end_src
425 The third block does have a =tangle= header argument indicating the
426 name of the file to which it should be written.  It also has [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]]
427 style references to the two previous source code blocks which will be
428 expanded during tangling to include them in the output file as well.
430 #+srcname: hello-world
431 #+begin_src sh :tangle hello :exports none
432   # <<hello-world-prefix>>
433   echo "|                       hello world                         |"
434   # <<hello-world-postfix>>
435 #+end_src
437 : #+srcname: hello-world
438 : #+begin_src sh :tangle hello :exports none
439 :   # <<hello-world-prefix>>
440 :   echo "|                       hello world                         |"
441 :   # <<hello-world-postfix>>
442 : #+end_src
444 Calling =org-babel-tangle= will result in the following being written
445 to the =hello.sh= file.
447 #+srcname: hello-world-output
448 #+begin_src sh 
449   #!/usr/bin/env sh
450   # generated by org-babel-tangle
451   
452   # [[file:~/src/org-babel/org-babel-worg.org::#literate-programming-example][block-16]]
453   # <<hello-world-prefix>>
454   echo "/-----------------------------------------------------------\\"
455   
456   echo "|                       hello world                         |"
457   # <<hello-world-postfix>>
458   echo "\-----------------------------------------------------------/"
459   # block-16 ends here
460 #+end_src
462 * Reference / Documentation
463   :PROPERTIES:
464   :CUSTOM_ID: reference-and-documentation
465   :END:
467 *** Source Code block syntax
469 The basic syntax of source-code blocks is as follows:
471 : #+srcname: name
472 : #+begin_src language header-arguments
473 : body
474 : #+end_src
476 - name :: This name is associated with the source-code block.  This is
477      similar to the =#+TBLNAME= lines which can be used to name tables
478      in org-mode files.  By referencing the srcname of a source-code
479      block it is possible to evaluate the block for other places,
480      files, or from inside tables.
481 - language :: The language of the code in the source-code block, valid
482      values must be members of `org-babel-interpreters'.
483 - header-arguments :: Header arguments control many facets of the
484      input to, evaluation of, and output of source-code blocks.  See
485      the [[* Header Arguments][Header Arguments]] section for a complete review of available
486      header arguments.
487 - body :: The actual source code which will be evaluated.  This can be
488           edited with `org-edit-special'.
490 *** Header Arguments
491      :PROPERTIES:
492      :CUSTOM_ID: header-arguments
493      :END:
495 - results :: results arguments specify what should be done with the
496              output of source-code blocks
497   - The following options are mutually exclusive, and specify how the
498     results should be collected from the source-code block
499     - value ::
500     - output :: 
501   - The following options are mutually exclusive and specify what type
502     of results the code block will return
503     - vector :: specifies that the results should be interpreted as a
504                 multidimensional vector (even if the vector is
505                 trivial), and will be inserted into the org-mode file
506                 as a table
507     - scalar :: specifies that the results should be interpreted as a
508                 scalar value, and will be inserted into the org-mode
509                 file as quoted text
510     - file :: specifies that the results should be interpreted as the
511               path to a file, and will be inserted into the org-mode
512               file as a link
513   - The following options specify how the results should be inserted
514     into the org-mode file
515     - replace :: the current results replace any previously inserted
516                  results from the code block
517     - silent :: rather than being inserted into the org-mode file the
518                 results are echoed into the message bar
519 - exports :: exports arguments specify what should be included in html
520              or latex exports of the org-mode file
521   - code :: the body of code is included into the exported file
522   - results :: the results of evaluating the code is included in the
523                exported file
524   - both :: both the code and results are included in the exported
525             file
526   - none :: nothing is included in the exported file
527 - tangle :: tangle arguments specify whether or not the source-code
528             block should be included in tangled extraction of
529             source-code files
530   - yes :: the source-code block is exported to a source-code file
531            named after the basename (name w/o extension) of the
532            org-mode file
533   - no :: (default) the source-code block is not exported to a
534           source-code file
535   - other :: any other string passed to the =tangle= header argument
536              is interpreted as a file basename to which the block will
537              be exported
539 *** Noweb reference syntax
540 The [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] Literate Programming system allows named blocks of code to
541 be referenced by using a =<<code-block-name>>= syntax.  When a
542 document is tangled these references are replaced with the named code.
543 An example is provided in the [[literate-programming-example]] in this
544 document.