1 #+OPTIONS: H:3 num:nil toc:2 \n:nil @:t ::t |:t ^:{} -:t f:t *:t TeX:t LaTeX:nil 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) noexport(n)
5 #+TITLE: Babel: Introduction
6 #+AUTHOR: Eric Schulte, Dan Davison, Tom Dye
7 #+EMAIL: schulte.eric at gmail dot com, davison at stats dot ox dot ac dot uk, tsd at tsdye dot com
9 #+STYLE: <style type="text/css">#outline-container-introduction{ clear:both; }</style>
10 #+STYLE: <style type="text/css">#table-of-contents{ max-width:100%; }</style>
12 #+LINK_HOME: http://orgmode.org/worg
14 * Improving this document :noexport:
15 ** DONE Document slice indexing of tables
16 ** DONE Document synonymous alternatives
17 {call,lob}, {source, function, srcname}, {results, resname}
18 ** DONE Describe useful functions
19 - `org-babel-execute-buffer'
20 - `org-babel-execute-subtree'
22 ** DONE Language support
23 Hopefully we will be breaking out a separate section for
24 each language, and expanding the portion which documents the actual
25 usage of header-arguments and noweb references as those sections are
27 ** DONE Document noweb references
28 *** DONE Why is :noweb needed for execution but not for tangling?
30 - org-babel can now cache the results of source block execution to avoid
31 rerunning the same calculation. The cache uses a sha1 hash key of the
32 source code body and the header arguments to determine if
33 recalculation is required. These hash keys are kept mostly hidden in
34 the #+resname line of the results of the block. This behavior is
35 turned off by default. It is controlled through the :cache
36 and :nocache header arguments. To enable caching on a single block
37 add the :cache header argument, to enable global caching change the
38 value of your `org-babel-default-header-args' variable as follows
40 (setq org-babel-default-header-args
42 (assq-delete-all :nocache org-babel-default-header-args)))
44 - It is now possible to fold results by tabbing on the beginning of the
45 #+resname line. This can be done automatically to all results on
46 opening of a file by adding the following to your org-mode hook
48 (add-hook 'org-mode-hook 'org-babel-result-hide-all)
50 - allow header argument values to be lisp forms, for example the
51 following is now valid
53 :file (format "%s/images/pca-scatter.png" dir)
55 ** DONE Useful variables
56 - # -*- org-src-preserve-indentation: t -*-
57 ** TODO Language specific header arguments
58 - org-babel: capture graphical output from R
60 If a [:file filename.ext] header arg is provided, then all graphical
61 output from the source block is captured on disk, and output of the
62 source block is a link to the resulting file, as with the
63 graphics-only languages such as gnuplot, ditaa, dot, asymptote. An
64 attempt is made to find a graphics device corresponding to the file
65 extension (currently .png, .jpg, .jpeg, .tiff, .bmp, .pdf, .ps,
66 .postscript are recognised); if that fails, png format output is
69 Additionally, values for several arguments to the R graphics
70 device can be passed using header args:
72 :width :height :bg :units :pointsize
73 :antialias :quality :compression :res :type
74 :family :title :fonts :version :paper :encoding
75 :pagecentre :colormodel :useDingbats :horizontal
77 Arguments to the R graphics device that are not supported as header
78 args can be passed as a string in R argument syntax, using the header
81 An example block is (although both bg and fg can be passed directly as
84 \#+begin_src R :file z.pdf :width 8 :height 8 :R-dev-args bg="olivedrab", fg="hotpink"
85 plot(matrix(rnorm(100), ncol=2), type="l")
88 - Yes, I think we do want a version of this for python and ruby et al. In
89 your example, the filename is created in python. I suggest doing it
90 slightly differently, something like this.
93 #+begin_src python :file outfile.txt
94 def savetofile(result, filename):
95 with open(filename, 'w') as f:
97 savetofile(78, 'outfile.txt')
101 #+resname: fileoutput
104 This functionality is now available for ruby & python in branch
105 ded-babel of git://orgmode.org/org-mode/babel.git.
107 So here, if you specify :file <filepath> ruby/python blindly outputs a
108 link to <filepath>, regardless of the contents of the
109 code. Responsibility for creating useful contents of <filepath> lies
110 with the code. Notice that with this you have to specify the output file
111 twice: once as an org-babel directive, and once in the python code. This
112 is in contrast to the graphics languages (dot, ditaa, asymptote), where
113 the results *automatically* get sent to the file specified by :file. The
114 same is also true now for graphical output from R.
116 The difference with python, ruby et al is that they might create file
117 output in a variety of ways which we can't anticipate, so we can't
118 automatically send output to the file. In contrast, the graphics
119 language *always* create file output and always do it in the same
120 way. [And in R it is possible to divert all graphical output to file] A
121 possible extension of the above might be to use a "magic variable" so
122 that a python variable is created e.g. __org_babel_output_file__ that
123 always holds a string corresponding to the file specified by :file. Eric
124 may have further ideas / views here.
127 ** DONE What function is bound to C-c '?
128 - this document notes two different functions
131 :CUSTOM_ID: introduction
134 Babel is about letting [[file:languages.org][many different languages]] work together.
135 Programming languages live in blocks inside natural language
136 [[http://orgmode.org/][Org-mode]] documents. A piece of data may pass from a table to a
137 Python code block, then maybe move on to an =R= code block, and
138 finally end up embedded as a value in the middle of a paragraph or
139 possibly pass through a =gnuplot= code block and end up as a plot
140 embedded in the document.
142 Through extending [[http://orgmode.org/][Org-mode]] with several features for editing
143 exporting and executing source code Babel turns Org-mode into a tool
144 for both /Literate Programming/ and /Reproducible Research/.
146 Babel augments [[http://orgmode.org/manual/Literal-examples.html][Org-mode support for code blocks]] by providing:
148 - interactive and on-export execution of code blocks;
149 - code blocks as functions that can be parameterised, refer to
150 other code blocks, and be called remotely; and
151 - export to files for literate programming.
154 Babel provides new features on a few different fronts, and
155 different people may want to start in different places.
157 - Using 'src' blocks in Org mode ::
158 If you are not familiar with creating 'src' blocks in an Org-mode
159 buffer, and moving between that buffer and the language major-mode
160 edit buffer, then you should have a look at the relevant section
161 in the [[http://orgmode.org/manual/Literal-examples.html][Org manual]] and [[#source-code-blocks][below]], try it out, and come back.
163 The core of Babel is its ability to execute code in Org-mode
164 'src' blocks, taking input from other blocks and tables, with
165 output to further blocks and tables. This is described starting
166 [[#source-code-execution][here]].
167 - Literate Programming ::
168 If you are a programmer writing code that you would normally
169 execute in some other way (e.g. from the command line, or sourcing
170 it into an interactive session), then a simple introduction to
171 Babel is to place your code in blocks in an Org-mode file, and to
172 use Babel's [[#literate-programming][Literate Programming]] support to extract pure code
175 All of these use cases, as well as exhaustive documentation of the
176 features of Babel are covered in the [[http://orgmode.org/manual/Working-With-Source-Code.html#Working-With-Source-Code][Working with Source Code]]
177 section of the Org manual.
179 * Initial Configuration
181 :CUSTOM_ID: getting-started
185 If you have a working Emacs installation, then getting started with
186 Babel is a simple process.
188 1) If you are running Emacs24 a current version of Org-mode with
189 Babel is already available by default. Otherwise, it is strongly
190 recommended that you update to the latest version of Org-mode by
191 [[file:../../org-faq.org::keeping-current-with-Org-mode-development][keeping current with Org-mode development]]. As of Org-mode 7.0,
192 Babel is included as part of Org-mode.
194 2) Optionally activate the subset of languages that you will want
195 to execute with Babel. See [[file:languages.org::#configure][Configure active languages]]
196 instructions. Emacs Lisp is activated by default so this step
197 can be skipped for now and all =emacs-lisp= examples will still
200 3) If you have made any changes don't forget to evaluate your
205 :CUSTOM_ID: source-code-blocks
208 ** Code Blocks in Org
210 :CUSTOM_ID: source-code-blocks-org
213 Babel is all about [[http://orgmode.org/manual/Literal-examples.html][code blocks]] in Org-mode. If you are
214 unfamiliar with the notion of a code block in Org-mode, where they
215 are called 'src' blocks, please have a look at the [[http://orgmode.org/manual/Literal-examples.html][Org-mode manual]]
218 Code blocks in [[#reference-and-documentation][supported languages]] can occur anywhere in an
219 Org-mode file. Code blocks can be entered directly into
220 the Org-mode file, but it is often easier to enter code with the
221 function =org-edit-src-code=, which is called with the keyboard
222 shortcut, C-c '. This places the code block in a new
223 buffer with the appropriate mode activated.
226 ,#+begin_src language org-switches
231 For example, a code block of [[http://www.ruby-lang.org/][ruby]] code looks like this in
237 ,"This file was last evaluated on #{Date.today}"
241 ** Code Blocks in Babel
243 :CUSTOM_ID: source-code-blocks-babel
246 Babel adds some new elements to code blocks. The basic
250 ,#+begin_src language org-switches header-arguments
256 - language :: The language of the code in the source-code block. Valid
257 values must be members of =org-babel-interpreters=.
258 - header-arguments :: Header arguments control many facets of the
259 evaluation and output of source-code blocks. See the [[file:reference.org::#header-arguments][Header
260 Arguments]] section for a complete review of available header
262 - body :: The source code to be evaluated. An important key-binding
263 is =
\200bC-c '
\200b=. This calls =org-edit-src-code=, a function that brings
264 up an edit buffer containing the code using the Emacs major mode
265 appropriate to the language. You can edit your code block
266 as you regularly would in Emacs.
268 * Source Code Execution
270 :CUSTOM_ID: source-code-execution
273 Babel executes code blocks for *interpreted* languages such
274 as shell, python, R, etc. by passing code to the interpreter, which
275 must be installed on your system. You control what is done with the
276 results of execution.
278 Here are examples of code blocks in three different languages,
279 followed by their output. If you are viewing the Org-mode version of
280 this document in Emacs, place point anywhere inside a block and press
281 C-c C-c to run the code[fn:1] (and feel free to alter it!).
283 In the Org-mode file:
285 : "This file was last evaluated on #{Date.today}"
290 "This file was last evaluated on #{Date.today}"
293 HTML export of the resulting string:
295 : This file was last evaluated on 2009-08-09
298 In the Org-mode file:
300 : echo "This file takes up `du -h org-babel.org |sed 's/\([0-9k]*\)[ ]*org-babel.org/\1/'`"
305 echo "This file takes up `du -h org-babel.org |sed 's/\([0-9k]*\)[ ]*org-babel.org/\1/'`"
308 HTML export of the resulting string:
310 : This file takes up 36K
312 *** [[http://www.r-project.org/][R]]
313 What are the most common words in this file?
314 In the Org-mode file:
315 : #+begin_src R :colnames yes
316 : words <- tolower(scan("intro.org", what="", na.strings=c("|",":")))
317 : t(sort(table(words[nchar(words) > 3]), decreasing=TRUE)[1:10])
322 #+begin_src R :colnames yes
323 words <- tolower(scan("intro.org", what="", na.strings=c("|",":")))
324 t(sort(table(words[nchar(words) > 3]), decreasing=TRUE)[1:10])
328 | code | org-mode | #+end_src | #+begin_src | block | with | babel | that | #+name: | this |
329 |------+----------+-----------+-------------+-------+------+-------+------+---------+------|
330 | 85 | 60 | 47 | 44 | 40 | 38 | 35 | 34 | 33 | 33 |
332 *** [[http://ditaa.sourceforge.net/][ditaa]]
334 In the Org-mode file:
335 : #+begin_src ditaa :file blue.png :cmdline -r
346 #+begin_src ditaa :file blue.png :cmdline -r
356 HTML export of the resulting image:
358 [[file:../../images/babel/blue.png]]
360 ** Capturing the Results of Code Evaluation
364 Babel provides two fundamentally different modes for capturing
365 the results of code evaluation: functional mode and scripting
366 mode. The choice of mode is specified by the =:results= header
368 *** =:results value= (functional mode)
370 :CUSTOM_ID: results-value
372 The 'result' of code evaluation is the *value* of the last
373 statement in the code block. In functional mode, the
374 code block is a function with a return value. The return
375 value of one code block can be used as input for another
376 code block, even one in a different language. In this
377 way, Babel becomes a [[meta-programming-language]]. If the block
378 returns tabular data (a vector, array or table of some sort) then
379 this will be held as an Org-mode table in the buffer. This
380 setting is the default.
382 For example, consider the following block of python code and its
385 #+begin_src python :results value
387 print("Hello, today's date is %s" % time.ctime())
388 print('Two plus two is')
395 Notice that, in functional mode, the output consists of the value of
396 the last statement and nothing else.
398 *** =:results output= (scripting mode)
400 :CUSTOM_ID: results-output
403 In scripting mode, Babel captures the text output of the
404 code block and places it in the Org-mode buffer. It is
405 called scripting mode because the code block contains a series of
406 commands, and the output of each command is returned. Unlike
407 functional mode, the code block itself has no return value
408 apart from the output of the commands it contains.[fn:2]
410 Consider the result of evaluating this code block with
414 #+begin_src python :results output
416 print("Hello, today's date is %s" % time.ctime())
417 print('Two plus two is')
422 : Hello, today's date is Wed Nov 11 18:50:36 2009
425 Here, scripting mode returned the text that python sent to =stdout=. Because
426 the code block doesn't include a =print()= statement for the last
427 value, =(2 + 2)=, 4 does not appear in the results.
429 ** Session-based Evaluation
430 For some languages, such as python, R, ruby and shell, it is
431 possible to run an interactive session as an "inferior process"
432 within Emacs. This means that an environment is created containing
433 data objects that persist between different source code
434 blocks. Babel supports evaluation of code within such sessions
435 with the =:session= header argument. If the header argument is
436 given a value then that will be used as the name of the session.
437 Thus, it is possible to run separate simultaneous sessions in the
440 Session-based evaluation is particularly useful for prototyping and
441 debugging. The function =org-babel-pop-to-session= can be used to
442 switch to the session buffer.
444 Once a code block is finished, it is often best to execute it
445 outside of a session, so the state of the environment in which it
446 executes will be certain.
448 With R, the session will be under the control of [[http://ess.r-project.org/][Emacs Speaks
449 Statistics]] as usual, and the full power of ESS is thus still
450 available, both in the R session, and when switching to the R code
451 edit buffer with =
\200bC-c '
\200b=.
453 ** Arguments to Code Blocks
455 :CUSTOM_ID: arguments-to-source-code-blocks
457 Babel supports parameterisation of code blocks, i.e.,
458 arguments can be passed to code blocks, which gives them
459 the status of *functions*. Arguments can be passed to code blocks in
460 both functional and scripting modes.
462 *** Simple example of using a code block as a function
464 First let's look at a very simple example. The following source
465 code block defines a function, using python, that squares its argument.
473 In the Org-mode file, the function looks like this:
481 Now we use the source block:
483 : #+call: square(x=6)
484 (/for information on the/ =call= /syntax see/ [[library-of-babel]])
488 #+results: square(x=6)
492 *** A more complex example using an Org-mode table as input
494 In this example we define a function called =fibonacci-seq=, using
495 Emacs Lisp. The function =fibonacci-seq= computes a Fibonacci
496 sequence. The function takes a single argument, in this case, a
497 reference to an Org-mode table.
499 Here is the Org-mode table that is passed to =fibonacci-seq=:
501 #+tblname: fibonacci-inputs
502 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
503 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
505 The table looks like this in the Org-mode buffer:
506 : #+tblname: fibonacci-inputs
507 : | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
508 : | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
510 The [[http://www.gnu.org/software/emacs/manual/elisp.html][Emacs Lisp]] source code:
511 #+name: fibonacci-seq(fib-inputs=fibonacci-inputs)
512 #+begin_src emacs-lisp
514 (if (or (= n 0) (= n 1))
516 (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
518 (mapcar (lambda (row)
519 (mapcar #'fibonacci row)) fib-inputs)
522 In the Org-mode buffer the function looks like this:
523 : #+name: fibonacci-seq(fib-inputs=fibonacci-inputs)
524 : #+begin_src emacs-lisp
525 : (defun fibonacci (n)
526 : (if (or (= n 0) (= n 1))
528 : (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
530 : (mapcar (lambda (row)
531 : (mapcar #'fibonacci row)) fib-inputs)
534 The return value of =fibonacci-seq= is a table:
536 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
537 | 1 | 3 | 8 | 21 | 55 | 144 | 377 | 987 | 2584 | 6765 |
539 ** In-line Code Blocks
540 Code can be evaluated in-line using the following syntax:
542 : Without header args: src_lang{code} or with header args: src_lang[args]{code},
543 : for example src_python[:session]{10*x}, where x is a variable existing in the
546 ** Code Block Body Expansion
547 Babel "expands" code blocks prior to evaluation, i.e., the
548 evaluated code comprises the code block contents augmented with
549 code that assigns referenced data to variables. It is possible to
550 preview expanded contents, and also to expand code during
551 tangling. Expansion takes into account header arguments and
554 - preview :: =C-c M-b p= is bound to =org-babel-expand-src-block=. It
555 can be used inside a code block to preview the expanded
556 contents. This facility is useful for debugging.
558 - tangling :: The expanded body can be tangled. Tangling this way includes
559 variable values that may be
560 - the results of other code blocks,
561 - variables stored in headline properties, or
564 One possible use for tangling expanded code block is for emacs
565 initialization. Values such as user names and passwords can be
566 stored in headline properties or in tables. The =:no-expand=
567 header argument can be used to inhibit expansion of a code block
570 Here is an example of a code block and its resulting expanded body.
572 The data are kept in a table:
574 | username | john-doe |
575 | password | abc123 |
577 The code block refers to the data table:
578 #+name: setup-my-account
579 #+begin_src emacs-lisp :rownames yes :var data=user-data
580 (setq my-special-username (first (first data)))
581 (setq my-special-password (first (second data)))
584 With point inside the code block, =C-c M-b p= expands the contents:
585 #+begin_src emacs-lisp
586 (let ((data (quote (("john-doe") ("abc123")))))
587 (setq my-special-username (first (first data)))
588 (setq my-special-password (first (second data)))
593 ** A Meta-programming Language for Org-mode
595 :CUSTOM_ID: meta-programming-language
598 Because the return value of a function written in one language can be
599 passed to a function written in another language, or to an Org-mode
600 table, which is itself programmable, Babel can be used as a
601 meta-functional programming language. With Babel, functions from
602 many languages can work together. You can mix and match languages,
603 using each language for the tasks to which it is best suited.
605 For example, let's take some system diagnostics in the shell and graph them with R.
607 1. Create a code block, using shell code, to list
608 directories in our home directory, together with their
609 sizes. Babel automatically converts the output into an Org-mode
612 : #+name: directories
613 : #+begin_src sh :results replace
614 : cd ~ && du -sc * |grep -v total
617 #+resname: directories
619 | 12156104 | "Documents" |
620 | 3482440 | "Downloads" |
621 | 2901720 | "Library" |
623 | 16548024 | "Music" |
625 | 7649472 | "Pictures" |
634 2. A function, written with a single line of R code, plots the data
635 in the Org-mode table as a
636 pie-chart. Note how this code block uses the =srcname=
637 of the previous code block to obtain the data.
639 In the Org-mode file:
640 : #+name: directory-pie-chart(dirs = directories)
641 : #+begin_src R :session R-pie-example :file ../../images/babel/dirs.png
642 : pie(dirs[,1], labels = dirs[,2])
646 #+name: directory-pie-chart(dirs=directories)
647 #+begin_src R :session R-pie-example :file ../../images/babel/dirs.png
648 pie(dirs[,1], labels = dirs[,2])
650 [[file:../../images/babel/dirs.png]]
652 * Using Code Blocks in Org Tables
654 :CUSTOM_ID: spreadsheet
657 In addition to passing data from tables as [[arguments-to-source-code-blocks][arguments]] to code
658 blocks, and [[#results-value][storing]] results as tables, Babel can be used in a
659 third way with Org-mode tables. First note that Org-mode's [[http://orgmode.org/manual/The-spreadsheet.html#The-spreadsheet][existing
660 spreadsheet functionality]] allows values in cells to be computed
661 automatically from the values of other cells, using a =#+TBLFM=
662 formula line. In this way, table computations can be carried out using
663 [[http://orgmode.org/manual/Formula-syntax-for-Calc.html#Formula-syntax-for-Calc][calc]] and [[http://orgmode.org/manual/Formula-syntax-for-Lisp.html#Formula-syntax-for-Lisp][emacs lisp]].
665 What Babel adds is the ability to use code blocks (in whatever
666 language) in the =#+TBLFM= line to perform the necessary computation.
668 *** Example 1: Data Summaries Using R
669 As a simple example, we'll fill in a cell in an Org-mode table with the
670 average value of a few numbers. First, let's make some data. The
671 following source block creates an Org-mode table filled with five random
672 numbers between 0 and 1.
674 : #+name: tbl-example-data()
676 : runif(n=5, min=0, max=1)
679 #+resname: tbl-example-data
680 | 0.836685163900256 |
681 | 0.696652316721156 |
682 | 0.382423302158713 |
683 | 0.987541858805344 |
684 | 0.994794291909784 |
686 Now we define a source block to calculate the mean.
688 In the Org-mode file:
700 Finally, we create the table which is going to make use of the R
701 code. This is done using the =sbe= ('source block evaluate') macro in
702 the table formula line.
704 In the Org-mode file:
705 : #+tblname: summaries
707 : |-------------------|
708 : | 0.779619386699051 |
709 : #+TBLFM: @2$1='(sbe "R-mean" (x "tbl-example-data()"))
716 #+TBLFM: @2$1='(sbe R-mean (x tbl-example-data));%.2f
718 To recalculate the table formula, use C-u C-c C-c in the
719 table. Notice that as things stand the calculated value doesn't
720 change, because the data (held in the table above named
721 =tbl-example-data=) are static. However, if you delete that data table,
722 then the reference will be interpreted as a reference to the source
723 block responsible for generating the data; each time the table formula
724 is recalculated the source block will be evaluated again, and
725 therefore the calculated average value will change.
727 *** Example 2: Babel Test Suite
728 While developing Babel, we used a suite of tests implemented
729 as a large Org-mode table. To run the entire test suite we simply
730 evaluate the table with C-u C-c C-c: all of the tests are run,
731 the results are compared with expectations, and the table is updated
732 with results and pass/fail statistics.
734 Here's a sample of our test suite.
736 In the Org-mode file:
738 : #+TBLNAME: org-babel-tests
739 : | functionality | block | arg | expected | results | pass |
740 : |------------------+--------------+-----+-------------+-------------+------|
741 : | basic evaluation | | | | | pass |
742 : |------------------+--------------+-----+-------------+-------------+------|
743 : | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
744 : | shell | basic-shell | | 6 | 6 | pass |
745 : | ruby | basic-ruby | | org-babel | org-babel | pass |
746 : | python | basic-python | | hello world | hello world | pass |
747 : | R | basic-R | | 13 | 13 | pass |
748 : #+TBLFM: $5='(if (= (length $3) 1) (sbe $2 (n $3)) (sbe $2)) :: $6='(if (string= $4 $5) "pass" (format "expected %S but was %S" $4 $5))
752 #+TBLNAME: org-babel-tests
753 | functionality | block | arg | expected | results | pass |
754 |------------------+--------------+-----+-------------+-------------+------|
755 | basic evaluation | | | | | pass |
756 |------------------+--------------+-----+-------------+-------------+------|
757 | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
758 | shell | basic-shell | | 6 | 6 | pass |
759 | ruby | basic-ruby | | org-babel | org-babel | pass |
760 | python | basic-python | | hello world | hello world | pass |
761 | R | basic-R | | 13 | 13 | pass |
762 #+TBLFM: $5='(if (= (length $3) 1) (sbe $2 (n $3)) (sbe $2)) :: $6='(if (string= $4 $5) "pass" (format "expected %S but was %S" $4 $5))
764 **** code blocks for tests
766 In the Org-mode file:
768 : #+name: basic-elisp(n)
769 : #+begin_src emacs-lisp
775 #+name: basic-elisp(n=0)
776 #+begin_src emacs-lisp
780 In the Org-mode file:
781 : #+name: basic-shell
782 : #+begin_src sh :results silent
788 #+begin_src sh :results silent
792 In the Org-mode file:
793 : #+name: date-simple
794 : #+begin_src sh :results silent
800 #+begin_src sh :results silent
804 In the Org-mode file:
806 : #+begin_src ruby :results silent
812 #+begin_src ruby :results silent
817 : #+name: basic-python
818 : #+begin_src python :results silent
824 #+begin_src python :results silent
828 In the Org-mode file:
830 : #+begin_src R :results silent
837 #+begin_src R :results silent
842 * The Library of Babel
844 :CUSTOM_ID: library-of-babel
847 (see also [[http://orgmode.org/manual/Library-of-Babel.html#Library-of-Babel][Org manual:Library-of-Babel]])
849 As we saw above with the [[*Simple%20example%20of%20using%20a%20source%20block%20as%20a%20function][=square=]] example, once a source block
850 function has been defined it can be called using the =lob= notation:
854 But what about code blocks that you want to make available to
855 every Org-mode buffer?
857 In addition to the current buffer, Babel searches for
858 pre-defined code block functions in the Library of
859 Babel. This is a user-extensible collection of ready-made source
860 code blocks for handling common tasks. One use for the Library of
861 Babel (not yet done!) will be to provide a choice of data graphing
862 procedures for data held in Org-mode tables, using languages such as
863 R, gnuplot, asymptote, etc. If you implement something that might be
864 of use to other Org-mode users, please consider adding it to the
865 Library of Babel; similarly, feel free to request help solving a
866 problem using external code via Babel -- there's always a chance
867 that other Babel users will be able to contribute some helpful
870 Babel comes pre-populated with the code blocks located in
871 the [[file:library-of-babel.org][Library of Babel]] file -- raw file at
872 #+html: <a href="http://orgmode.org/w/org-mode.git/blob/HEAD:/contrib/babel/library-of-babel.org">library-of-babel.org</a>
873 --. It is possible to add code blocks to the library from any
874 Org-mode file using the =org-babel-lob-ingest= (bound to =C-c C-v
877 #+name: add-file-to-lob
878 #+begin_src emacs-lisp
879 (org-babel-lob-ingest "path/to/file.org")
882 Note that it is possible to pass table values or the output of a
883 source-code block to Library of Babel functions. It is also possible
884 to reference Library of Babel functions in arguments to code blocks.
886 * Literate Programming
888 :CUSTOM_ID: literate-programming
892 Let us change our traditional attitude to the construction of
893 programs: Instead of imagining that our main task is to instruct a
894 /computer/ what to do, let us concentrate rather on explaining to
895 /human beings/ what we want a computer to do.
897 The practitioner of literate programming can be regarded as an
898 essayist, whose main concern is with exposition and excellence of
899 style. Such an author, with thesaurus in hand, chooses the names of
900 variables carefully and explains what each variable means. He or she
901 strives for a program that is comprehensible because its concepts have
902 been introduced in an order that is best for human understanding,
903 using a mixture of formal and informal methods that reinforce each
909 Babel supports [[http://en.wikipedia.org/wiki/Literate_programming][Literate Programming]] (LP) by allowing the act of
910 programming to take place inside of Org-mode documents. The Org-mode
911 file can then be exported (*woven* in LP speak) to HTML or LaTeX for
912 consumption by a human, and the embedded source code can be extracted
913 (*tangled* in LP speak) into structured source code files for
914 consumption by a computer.
916 To support these operations Babel relies on Org-mode's [[http://orgmode.org/manual/Exporting.html#Exporting][existing
917 exporting functionality]] for *weaving* of documentation, and on the
918 =org-babel-tangle= function which makes use of [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] [[noweb-reference-syntax][reference syntax]]
919 for *tangling* of code files.
921 The [[literate-programming-example][following example]] demonstrates the process of *tangling* in
924 *** Simple Literate Programming Example (Noweb syntax)
926 :CUSTOM_ID: literate-programming-example
929 Tangling functionality is controlled by the =tangle= family of [[tangle-header-arguments][Tangle
930 header arguments]]. These arguments can be used to turn tangling on or
931 off (the default), either for the code block or the Org-mode
934 The following code blocks demonstrate how to tangle them into a
935 single source code file using =org-babel-tangle=.
937 The following two code blocks have no =tangle= header arguments
938 and so will not, by themselves, create source code files. They are
939 included in the source code file by the third code block, which
940 does have a =tangle= header argument.
942 In the Org-mode file:
943 : #+name: hello-world-prefix
944 : #+begin_src sh :exports none
945 : echo "/-----------------------------------------------------------\\"
949 #+name: hello-world-prefix
950 #+begin_src sh :exports none
951 echo "/-----------------------------------------------------------\\"
955 : #+name: hello-world-postfix
956 : #+begin_src sh :exports none
957 : echo "\-----------------------------------------------------------/"
961 #+name: hello-world-postfix
962 #+begin_src sh :exports none
963 echo "\-----------------------------------------------------------/"
967 The third code block does have a =tangle= header argument
968 indicating the name of the file to which the tangled source code will
969 be written. It also has [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] style references to the two previous
970 code blocks. These references will be expanded during tangling
971 to include them in the output file as well.
973 In the Org-mode file:
974 : #+name: hello-world
975 : #+begin_src sh :tangle hello :exports none :noweb yes
976 : <<hello-world-prefix>>
977 : echo "| hello world |"
978 : <<hello-world-postfix>>
983 #+begin_src sh :tangle hello.sh :exports none :noweb yes
984 <<hello-world-prefix>>
985 echo "| hello world |"
986 <<hello-world-postfix>>
990 Calling =org-babel-tangle= will result in the following shell source
991 code being written to the =hello.sh= file:
993 #+name: hello-world-output
997 # [[file:~/org/temp/index.org::*Noweb%20test][hello-world]]
999 echo "/-----------------------------------------------------------\\"
1000 echo "| hello world |"
1001 echo "\-----------------------------------------------------------/"
1002 # hello-world ends here
1005 In addition, the following syntax can be used to insert the *results*
1006 of evaluating a code block, in this case one named =example-block=.
1008 : # <<example-block()>>
1010 Any optional arguments can be passed to =example-block()= by placing the
1011 arguments inside the parentheses following the convention defined when
1012 calling source block functions (see the [[library-of-babel][Library of babel]]). For example,
1014 : # <<example-block(a=9)>>
1016 sets the value of argument \"a\" equal to \"9\". Note that
1017 these arguments are not evaluated in the current source-code
1018 block but are passed literally to =example-block()=.
1020 *** Emacs Initialization with Babel
1022 :CUSTOM_ID: emacs-initialization
1025 #+attr_html: style="float:left;"
1026 [[file:../../images/babel/dot-emacs.png]]
1028 Babel has special support for embedding your Emacs initialization
1029 into Org-mode files. The =org-babel-load-file= function can be used
1030 to load the Emacs Lisp code blocks embedded in a literate
1031 Org-mode file in the same way that you might load a regular Emacs Lisp
1032 file, such as .emacs.
1034 This allows you to make use of the nice features of Org-mode, such as folding, tags,
1035 notes, HTML export, etc., to organize and maintain your Emacs initialization.
1037 To try this out, either see the simple [[literate-emacs-init][Literate Emacs Initialization]]
1038 example, or check out the Babel Literate Programming version of
1039 Phil Hagelberg's excellent [[http://github.com/technomancy/emacs-starter-kit/tree/master][emacs-starter-kit]] available at
1040 [[http://github.com/eschulte/emacs-starter-kit/tree/master][Org-babel-emacs-starter-kit]].
1042 ***** Literate Emacs Initialization
1044 :CUSTOM_ID: literate-emacs-init
1047 For a simple example of usage, follow these 5 steps:
1049 1) create a directory named =.emacs.d= in the base of your home
1054 2) checkout the latest version of Org-mode into the src subdirectory
1055 of this new directory;
1060 git clone git://orgmode.org/org-mode.git
1062 3) place the following code block in a file called =init.el= in your Emacs
1063 initialization directory (=~/.emacs.d=).
1065 #+begin_src emacs-lisp
1066 ;;; init.el --- Where all the magic begins
1068 ;; This file loads Org-mode and then loads the rest of our Emacs initialization from Emacs lisp
1069 ;; embedded in literate Org-mode files.
1071 ;; Load up Org Mode and (now included) Org Babel for elisp embedded in Org Mode files
1072 (setq dotfiles-dir (file-name-directory (or (buffer-file-name) load-file-name)))
1074 (let* ((org-dir (expand-file-name
1075 "lisp" (expand-file-name
1076 "org" (expand-file-name
1077 "src" dotfiles-dir))))
1078 (org-contrib-dir (expand-file-name
1079 "lisp" (expand-file-name
1080 "contrib" (expand-file-name
1082 (load-path (append (list org-dir org-contrib-dir)
1083 (or load-path nil))))
1084 ;; load up Org-mode and Org-babel
1085 (require 'org-install)
1086 (require 'ob-tangle))
1088 ;; load up all literate org-mode files in this directory
1089 (mapc #'org-babel-load-file (directory-files dotfiles-dir t "\\.org$"))
1091 ;;; init.el ends here
1093 4) implement all of your Emacs customizations inside of Emacs Lisp
1094 code blocks embedded in Org-mode files in this directory;
1096 5) re-start Emacs to load the customizations.
1098 * Reproducible Research
1100 :CUSTOM_ID: reproducable-research
1103 An article about computational science in a scientific publication is
1104 not the scholarship itself, it is merely advertising of the
1105 scholarship. The actual scholarship is the complete software
1106 development environment and the complete set of instructions which
1107 generated the figures.
1112 [[http://reproducibleresearch.net/index.php/Main_Page][Reproducible Research]] (RR) is the practice of distributing, along with
1113 a research publication, all data, software source code, and tools
1114 required to reproduce the results discussed in the publication. As
1115 such the RR package not only describes the research and its results,
1116 but becomes a complete laboratory in which the research can be
1117 reproduced and extended.
1119 Org-mode already has exceptional support for [[http://orgmode.org/manual/Exporting.html#Exporting][exporting to HTML and
1120 LaTeX]]. Babel makes Org-mode a tool for RR by *activating* the
1121 data and code blocks embedded in Org-mode documents; the
1122 entire document becomes executable. This makes it possible, and natural, to
1123 distribute research in a format that encourages readers to recreate
1124 results and perform their own analyses.
1126 One notable existing RR tool is [[http://en.wikipedia.org/wiki/Sweave][Sweave]], which provides a mechanism for
1127 embedding [[http://www.r-project.org/][R]] code into LaTeX documents. Sweave is a mature
1128 and very useful tool, but we believe that Babel has several
1130 - it supports multiple languages (we're not aware of other RR tools that do this);
1131 - the [[http://orgmode.org/manual/Exporting.html#Exporting][export process]] is flexible and powerful, including HTML as a
1132 target in addition to LaTeX; and
1133 - the document can make use of Org-mode features that support [[http://orgmode.org/manual/Agenda-Views.html#Agenda-Views][project
1134 planning]] and [[http://orgmode.org/manual/TODO-Items.html#TODO-Items][task management]].
1137 [fn:1] Calling =C-c C-o= on a code block will open the
1138 block's results in a separate buffer.
1140 [fn:2] This mode will be familiar to Sweave users.