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.
472 In the Org-mode file, the function looks like this:
479 Now we use the source block:
481 : #+call: square(x=6)
482 (/for information on the/ =call= /syntax see/ [[library-of-babel]])
486 #+results: square(x=6)
489 *** A more complex example using an Org-mode table as input
491 In this example we define a function called =fibonacci-seq=, using
492 Emacs Lisp. The function =fibonacci-seq= computes a Fibonacci
493 sequence. The function takes a single argument, in this case, a
494 reference to an Org-mode table.
496 Here is the Org-mode table that is passed to =fibonacci-seq=:
498 #+tblname: fibonacci-inputs
499 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
500 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
502 The table looks like this in the Org-mode buffer:
503 : #+tblname: fibonacci-inputs
504 : | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
505 : | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
507 The [[http://www.gnu.org/software/emacs/manual/elisp.html][Emacs Lisp]] source code:
508 #+name: fibonacci-seq(fib-inputs=fibonacci-inputs)
509 #+begin_src emacs-lisp
511 (if (or (= n 0) (= n 1))
513 (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
515 (mapcar (lambda (row)
516 (mapcar #'fibonacci row)) fib-inputs)
519 In the Org-mode buffer the function looks like this:
520 : #+name: fibonacci-seq(fib-inputs=fibonacci-inputs)
521 : #+begin_src emacs-lisp
522 : (defun fibonacci (n)
523 : (if (or (= n 0) (= n 1))
525 : (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
527 : (mapcar (lambda (row)
528 : (mapcar #'fibonacci row)) fib-inputs)
531 The return value of =fibonacci-seq= is a table:
533 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
534 | 1 | 3 | 8 | 21 | 55 | 144 | 377 | 987 | 2584 | 6765 |
536 ** In-line Code Blocks
537 Code can be evaluated in-line using the following syntax:
539 : Without header args: src_lang{code} or with header args: src_lang[args]{code},
540 : for example src_python[:session]{10*x}, where x is a variable existing in the
543 ** Code Block Body Expansion
544 Babel "expands" code blocks prior to evaluation, i.e., the
545 evaluated code comprises the code block contents augmented with
546 code that assigns referenced data to variables. It is possible to
547 preview expanded contents, and also to expand code during
548 tangling. Expansion takes into account header arguments and
551 - preview :: =C-c M-b p= is bound to =org-babel-expand-src-block=. It
552 can be used inside a code block to preview the expanded
553 contents. This facility is useful for debugging.
555 - tangling :: The expanded body can be tangled. Tangling this way includes
556 variable values that may be
557 - the results of other code blocks,
558 - variables stored in headline properties, or
561 One possible use for tangling expanded code block is for emacs
562 initialization. Values such as user names and passwords can be
563 stored in headline properties or in tables. The =:no-expand=
564 header argument can be used to inhibit expansion of a code block
567 Here is an example of a code block and its resulting expanded body.
569 The data are kept in a table:
571 | username | john-doe |
572 | password | abc123 |
574 The code block refers to the data table:
575 #+name: setup-my-account
576 #+begin_src emacs-lisp :rownames yes :var data=user-data
577 (setq my-special-username (first (first data)))
578 (setq my-special-password (first (second data)))
581 With point inside the code block, =C-c M-b p= expands the contents:
582 #+begin_src emacs-lisp
583 (let ((data (quote (("john-doe") ("abc123")))))
584 (setq my-special-username (first (first data)))
585 (setq my-special-password (first (second data)))
590 ** A Meta-programming Language for Org-mode
592 :CUSTOM_ID: meta-programming-language
595 Because the return value of a function written in one language can be
596 passed to a function written in another language, or to an Org-mode
597 table, which is itself programmable, Babel can be used as a
598 meta-functional programming language. With Babel, functions from
599 many languages can work together. You can mix and match languages,
600 using each language for the tasks to which it is best suited.
602 For example, let's take some system diagnostics in the shell and graph them with R.
604 1. Create a code block, using shell code, to list
605 directories in our home directory, together with their
606 sizes. Babel automatically converts the output into an Org-mode
609 : #+name: directories
610 : #+begin_src sh :results replace
611 : cd ~ && du -sc * |grep -v total
614 #+resname: directories
616 | 12156104 | "Documents" |
617 | 3482440 | "Downloads" |
618 | 2901720 | "Library" |
620 | 16548024 | "Music" |
622 | 7649472 | "Pictures" |
631 2. A function, written with a single line of R code, plots the data
632 in the Org-mode table as a
633 pie-chart. Note how this code block uses the =srcname=
634 of the previous code block to obtain the data.
636 In the Org-mode file:
637 : #+name: directory-pie-chart(dirs = directories)
638 : #+begin_src R :session R-pie-example :file ../../images/babel/dirs.png
639 : pie(dirs[,1], labels = dirs[,2])
643 #+name: directory-pie-chart(dirs=directories)
644 #+begin_src R :session R-pie-example :file ../../images/babel/dirs.png
645 pie(dirs[,1], labels = dirs[,2])
647 [[file:../../images/babel/dirs.png]]
649 * Using Code Blocks in Org Tables
651 :CUSTOM_ID: spreadsheet
654 In addition to passing data from tables as [[arguments-to-source-code-blocks][arguments]] to code
655 blocks, and [[#results-value][storing]] results as tables, Babel can be used in a
656 third way with Org-mode tables. First note that Org-mode's [[http://orgmode.org/manual/The-spreadsheet.html#The-spreadsheet][existing
657 spreadsheet functionality]] allows values in cells to be computed
658 automatically from the values of other cells, using a =#+TBLFM=
659 formula line. In this way, table computations can be carried out using
660 [[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]].
662 What Babel adds is the ability to use code blocks (in whatever
663 language) in the =#+TBLFM= line to perform the necessary computation.
665 *** Example 1: Data Summaries Using R
666 As a simple example, we'll fill in a cell in an Org-mode table with the
667 average value of a few numbers. First, let's make some data. The
668 following source block creates an Org-mode table filled with five random
669 numbers between 0 and 1.
671 : #+name: tbl-example-data()
673 : runif(n=5, min=0, max=1)
676 #+resname: tbl-example-data
677 | 0.836685163900256 |
678 | 0.696652316721156 |
679 | 0.382423302158713 |
680 | 0.987541858805344 |
681 | 0.994794291909784 |
683 Now we define a source block to calculate the mean.
685 In the Org-mode file:
697 Finally, we create the table which is going to make use of the R
698 code. This is done using the =sbe= ('source block evaluate') macro in
699 the table formula line.
701 In the Org-mode file:
702 : #+tblname: summaries
704 : |-------------------|
705 : | 0.779619386699051 |
706 : #+TBLFM: @2$1='(sbe "R-mean" (x "tbl-example-data()"))
713 #+TBLFM: @2$1='(sbe R-mean (x tbl-example-data));%.2f
715 To recalculate the table formula, use C-u C-c C-c in the
716 table. Notice that as things stand the calculated value doesn't
717 change, because the data (held in the table above named
718 =tbl-example-data=) are static. However, if you delete that data table,
719 then the reference will be interpreted as a reference to the source
720 block responsible for generating the data; each time the table formula
721 is recalculated the source block will be evaluated again, and
722 therefore the calculated average value will change.
724 *** Example 2: Babel Test Suite
725 While developing Babel, we used a suite of tests implemented
726 as a large Org-mode table. To run the entire test suite we simply
727 evaluate the table with C-u C-c C-c: all of the tests are run,
728 the results are compared with expectations, and the table is updated
729 with results and pass/fail statistics.
731 Here's a sample of our test suite.
733 In the Org-mode file:
735 : #+TBLNAME: org-babel-tests
736 : | functionality | block | arg | expected | results | pass |
737 : |------------------+--------------+-----+-------------+-------------+------|
738 : | basic evaluation | | | | | pass |
739 : |------------------+--------------+-----+-------------+-------------+------|
740 : | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
741 : | shell | basic-shell | | 6 | 6 | pass |
742 : | ruby | basic-ruby | | org-babel | org-babel | pass |
743 : | python | basic-python | | hello world | hello world | pass |
744 : | R | basic-R | | 13 | 13 | pass |
745 : #+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))
749 #+TBLNAME: org-babel-tests
750 | functionality | block | arg | expected | results | pass |
751 |------------------+--------------+-----+-------------+-------------+------|
752 | basic evaluation | | | | | pass |
753 |------------------+--------------+-----+-------------+-------------+------|
754 | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
755 | shell | basic-shell | | 6 | 6 | pass |
756 | ruby | basic-ruby | | org-babel | org-babel | pass |
757 | python | basic-python | | hello world | hello world | pass |
758 | R | basic-R | | 13 | 13 | pass |
759 #+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))
761 **** code blocks for tests
763 In the Org-mode file:
765 : #+name: basic-elisp(n)
766 : #+begin_src emacs-lisp
772 #+name: basic-elisp(n=0)
773 #+begin_src emacs-lisp
777 In the Org-mode file:
778 : #+name: basic-shell
779 : #+begin_src sh :results silent
785 #+begin_src sh :results silent
789 In the Org-mode file:
790 : #+name: date-simple
791 : #+begin_src sh :results silent
797 #+begin_src sh :results silent
801 In the Org-mode file:
803 : #+begin_src ruby :results silent
809 #+begin_src ruby :results silent
814 : #+name: basic-python
815 : #+begin_src python :results silent
821 #+begin_src python :results silent
825 In the Org-mode file:
827 : #+begin_src R :results silent
834 #+begin_src R :results silent
839 * The Library of Babel
841 :CUSTOM_ID: library-of-babel
844 (see also [[http://orgmode.org/manual/Library-of-Babel.html#Library-of-Babel][Org manual:Library-of-Babel]])
846 As we saw above with the [[*Simple%20example%20of%20using%20a%20source%20block%20as%20a%20function][=square=]] example, once a source block
847 function has been defined it can be called using the =lob= notation:
851 But what about code blocks that you want to make available to
852 every Org-mode buffer?
854 In addition to the current buffer, Babel searches for
855 pre-defined code block functions in the Library of
856 Babel. This is a user-extensible collection of ready-made source
857 code blocks for handling common tasks. One use for the Library of
858 Babel (not yet done!) will be to provide a choice of data graphing
859 procedures for data held in Org-mode tables, using languages such as
860 R, gnuplot, asymptote, etc. If you implement something that might be
861 of use to other Org-mode users, please consider adding it to the
862 Library of Babel; similarly, feel free to request help solving a
863 problem using external code via Babel -- there's always a chance
864 that other Babel users will be able to contribute some helpful
867 Babel comes pre-populated with the code blocks located in
868 the [[file:library-of-babel.org][Library of Babel]] file -- raw file at
869 #+html: <a href="http://orgmode.org/w/org-mode.git/blob/HEAD:/contrib/babel/library-of-babel.org">library-of-babel.org</a>
870 --. It is possible to add code blocks to the library from any
871 Org-mode file using the =org-babel-lob-ingest= (bound to =C-c C-v
874 #+name: add-file-to-lob
875 #+begin_src emacs-lisp
876 (org-babel-lob-ingest "path/to/file.org")
879 Note that it is possible to pass table values or the output of a
880 source-code block to Library of Babel functions. It is also possible
881 to reference Library of Babel functions in arguments to code blocks.
883 * Literate Programming
885 :CUSTOM_ID: literate-programming
889 Let us change our traditional attitude to the construction of
890 programs: Instead of imagining that our main task is to instruct a
891 /computer/ what to do, let us concentrate rather on explaining to
892 /human beings/ what we want a computer to do.
894 The practitioner of literate programming can be regarded as an
895 essayist, whose main concern is with exposition and excellence of
896 style. Such an author, with thesaurus in hand, chooses the names of
897 variables carefully and explains what each variable means. He or she
898 strives for a program that is comprehensible because its concepts have
899 been introduced in an order that is best for human understanding,
900 using a mixture of formal and informal methods that reinforce each
906 Babel supports [[http://en.wikipedia.org/wiki/Literate_programming][Literate Programming]] (LP) by allowing the act of
907 programming to take place inside of Org-mode documents. The Org-mode
908 file can then be exported (*woven* in LP speak) to HTML or LaTeX for
909 consumption by a human, and the embedded source code can be extracted
910 (*tangled* in LP speak) into structured source code files for
911 consumption by a computer.
913 To support these operations Babel relies on Org-mode's [[http://orgmode.org/manual/Exporting.html#Exporting][existing
914 exporting functionality]] for *weaving* of documentation, and on the
915 =org-babel-tangle= function which makes use of [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] [[noweb-reference-syntax][reference syntax]]
916 for *tangling* of code files.
918 The [[literate-programming-example][following example]] demonstrates the process of *tangling* in
921 *** Simple Literate Programming Example (Noweb syntax)
923 :CUSTOM_ID: literate-programming-example
926 Tangling functionality is controlled by the =tangle= family of [[tangle-header-arguments][Tangle
927 header arguments]]. These arguments can be used to turn tangling on or
928 off (the default), either for the code block or the Org-mode
931 The following code blocks demonstrate how to tangle them into a
932 single source code file using =org-babel-tangle=.
934 The following two code blocks have no =tangle= header arguments
935 and so will not, by themselves, create source code files. They are
936 included in the source code file by the third code block, which
937 does have a =tangle= header argument.
939 In the Org-mode file:
940 : #+name: hello-world-prefix
941 : #+begin_src sh :exports none
942 : echo "/-----------------------------------------------------------\\"
946 #+name: hello-world-prefix
947 #+begin_src sh :exports none
948 echo "/-----------------------------------------------------------\\"
952 : #+name: hello-world-postfix
953 : #+begin_src sh :exports none
954 : echo "\-----------------------------------------------------------/"
958 #+name: hello-world-postfix
959 #+begin_src sh :exports none
960 echo "\-----------------------------------------------------------/"
964 The third code block does have a =tangle= header argument
965 indicating the name of the file to which the tangled source code will
966 be written. It also has [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] style references to the two previous
967 code blocks. These references will be expanded during tangling
968 to include them in the output file as well.
970 In the Org-mode file:
971 : #+name: hello-world
972 : #+begin_src sh :tangle hello :exports none :noweb yes
973 : <<hello-world-prefix>>
974 : echo "| hello world |"
975 : <<hello-world-postfix>>
980 #+begin_src sh :tangle hello.sh :exports none :noweb yes
981 <<hello-world-prefix>>
982 echo "| hello world |"
983 <<hello-world-postfix>>
987 Calling =org-babel-tangle= will result in the following shell source
988 code being written to the =hello.sh= file:
990 #+name: hello-world-output
994 # [[file:~/org/temp/index.org::*Noweb%20test][hello-world]]
996 echo "/-----------------------------------------------------------\\"
997 echo "| hello world |"
998 echo "\-----------------------------------------------------------/"
999 # hello-world ends here
1002 In addition, the following syntax can be used to insert the *results*
1003 of evaluating a code block, in this case one named =example-block=.
1005 : # <<example-block()>>
1007 Any optional arguments can be passed to =example-block()= by placing the
1008 arguments inside the parentheses following the convention defined when
1009 calling source block functions (see the [[library-of-babel][Library of babel]]). For example,
1011 : # <<example-block(a=9)>>
1013 sets the value of argument \"a\" equal to \"9\". Note that
1014 these arguments are not evaluated in the current source-code
1015 block but are passed literally to =example-block()=.
1017 *** Emacs Initialization with Babel
1019 :CUSTOM_ID: emacs-initialization
1022 #+attr_html: style="float:left;"
1023 [[file:../../images/babel/dot-emacs.png]]
1025 Babel has special support for embedding your Emacs initialization
1026 into Org-mode files. The =org-babel-load-file= function can be used
1027 to load the Emacs Lisp code blocks embedded in a literate
1028 Org-mode file in the same way that you might load a regular Emacs Lisp
1029 file, such as .emacs.
1031 This allows you to make use of the nice features of Org-mode, such as folding, tags,
1032 notes, HTML export, etc., to organize and maintain your Emacs initialization.
1034 To try this out, either see the simple [[literate-emacs-init][Literate Emacs Initialization]]
1035 example, or check out the Babel Literate Programming version of
1036 Phil Hagelberg's excellent [[http://github.com/technomancy/emacs-starter-kit/tree/master][emacs-starter-kit]] available at
1037 [[http://github.com/eschulte/emacs-starter-kit/tree/master][Org-babel-emacs-starter-kit]].
1039 ***** Literate Emacs Initialization
1041 :CUSTOM_ID: literate-emacs-init
1044 For a simple example of usage, follow these 5 steps:
1046 1) create a directory named =.emacs.d= in the base of your home
1051 2) checkout the latest version of Org-mode into the src subdirectory
1052 of this new directory;
1057 git clone git://orgmode.org/org-mode.git
1059 3) place the following code block in a file called =init.el= in your Emacs
1060 initialization directory (=~/.emacs.d=).
1062 #+begin_src emacs-lisp
1063 ;;; init.el --- Where all the magic begins
1065 ;; This file loads Org-mode and then loads the rest of our Emacs initialization from Emacs lisp
1066 ;; embedded in literate Org-mode files.
1068 ;; Load up Org Mode and (now included) Org Babel for elisp embedded in Org Mode files
1069 (setq dotfiles-dir (file-name-directory (or (buffer-file-name) load-file-name)))
1071 (let* ((org-dir (expand-file-name
1072 "lisp" (expand-file-name
1073 "org" (expand-file-name
1074 "src" dotfiles-dir))))
1075 (org-contrib-dir (expand-file-name
1076 "lisp" (expand-file-name
1077 "contrib" (expand-file-name
1079 (load-path (append (list org-dir org-contrib-dir)
1080 (or load-path nil))))
1081 ;; load up Org-mode and Org-babel
1082 (require 'org-install)
1083 (require 'ob-tangle))
1085 ;; load up all literate org-mode files in this directory
1086 (mapc #'org-babel-load-file (directory-files dotfiles-dir t "\\.org$"))
1088 ;;; init.el ends here
1090 4) implement all of your Emacs customizations inside of Emacs Lisp
1091 code blocks embedded in Org-mode files in this directory;
1093 5) re-start Emacs to load the customizations.
1095 * Reproducible Research
1097 :CUSTOM_ID: reproducable-research
1100 An article about computational science in a scientific publication is
1101 not the scholarship itself, it is merely advertising of the
1102 scholarship. The actual scholarship is the complete software
1103 development environment and the complete set of instructions which
1104 generated the figures.
1109 [[http://reproducibleresearch.net/index.php/Main_Page][Reproducible Research]] (RR) is the practice of distributing, along with
1110 a research publication, all data, software source code, and tools
1111 required to reproduce the results discussed in the publication. As
1112 such the RR package not only describes the research and its results,
1113 but becomes a complete laboratory in which the research can be
1114 reproduced and extended.
1116 Org-mode already has exceptional support for [[http://orgmode.org/manual/Exporting.html#Exporting][exporting to HTML and
1117 LaTeX]]. Babel makes Org-mode a tool for RR by *activating* the
1118 data and code blocks embedded in Org-mode documents; the
1119 entire document becomes executable. This makes it possible, and natural, to
1120 distribute research in a format that encourages readers to recreate
1121 results and perform their own analyses.
1123 One notable existing RR tool is [[http://en.wikipedia.org/wiki/Sweave][Sweave]], which provides a mechanism for
1124 embedding [[http://www.r-project.org/][R]] code into LaTeX documents. Sweave is a mature
1125 and very useful tool, but we believe that Babel has several
1127 - it supports multiple languages (we're not aware of other RR tools that do this);
1128 - the [[http://orgmode.org/manual/Exporting.html#Exporting][export process]] is flexible and powerful, including HTML as a
1129 target in addition to LaTeX; and
1130 - the document can make use of Org-mode features that support [[http://orgmode.org/manual/Agenda-Views.html#Agenda-Views][project
1131 planning]] and [[http://orgmode.org/manual/TODO-Items.html#TODO-Items][task management]].
1134 [fn:1] Calling =C-c C-o= on a code block will open the
1135 block's results in a separate buffer.
1137 [fn:2] This mode will be familiar to Sweave users.