1 #+TITLE: Babel: Introduction
2 #+AUTHOR: Eric Schulte, Dan Davison, Tom Dye
3 #+EMAIL: schulte.eric at gmail dot com, davison at stats dot ox dot ac dot uk, tsd at tsdye dot com
4 #+OPTIONS: H:3 num:nil toc:2 \n:nil ::t |:t ^:{} -:t f:t *:t tex:t d:(HIDE) tags:not-in-toc
5 #+STARTUP: align fold nodlcheck hidestars oddeven lognotestate hideblocks
6 #+SEQ_TODO: TODO(t) INPROGRESS(i) WAITING(w@) | DONE(d) CANCELED(c@)
7 #+TAGS: Write(w) Update(u) Fix(f) Check(c) noexport(n)
9 #+HTML_LINK_UP: index.php
10 #+HTML_LINK_HOME: https://orgmode.org/worg
12 # This file is released by its authors and contributors under the GNU
13 # Free Documentation license v1.3 or later, code examples are released
14 # under the GNU General Public License v3 or later.
16 * Improving this document :noexport:
17 ** DONE Document slice indexing of tables
18 ** DONE Document synonymous alternatives
19 {call,lob}, {source, function, srcname}, {results, resname}
20 ** DONE Describe useful functions
21 - `org-babel-execute-buffer'
22 - `org-babel-execute-subtree'
24 ** DONE Language support
25 Hopefully we will be breaking out a separate section for
26 each language, and expanding the portion which documents the actual
27 usage of header-arguments and noweb references as those sections are
29 ** DONE Document noweb references
30 *** DONE Why is :noweb needed for execution but not for tangling?
32 - org-babel can now cache the results of source block execution to avoid
33 rerunning the same calculation. The cache uses a sha1 hash key of the
34 source code body and the header arguments to determine if
35 recalculation is required. These hash keys are kept mostly hidden in
36 the #+resname line of the results of the block. This behavior is
37 turned off by default. It is controlled through the :cache
38 and :nocache header arguments. To enable caching on a single block
39 add the :cache header argument, to enable global caching change the
40 value of your `org-babel-default-header-args' variable as follows
42 (setq org-babel-default-header-args
44 (assq-delete-all :nocache org-babel-default-header-args)))
46 - It is now possible to fold results by tabbing on the beginning of the
47 #+resname line. This can be done automatically to all results on
48 opening of a file by adding the following to your org-mode hook
50 (add-hook 'org-mode-hook 'org-babel-result-hide-all)
52 - allow header argument values to be lisp forms, for example the
53 following is now valid
55 :file (format "%s/images/pca-scatter.png" dir)
57 ** DONE Useful variables
58 - # -*- org-src-preserve-indentation: t -*-
59 ** TODO Language specific header arguments
60 - org-babel: capture graphical output from R
62 If a [:file filename.ext] header arg is provided, then all graphical
63 output from the source block is captured on disk, and output of the
64 source block is a link to the resulting file, as with the
65 graphics-only languages such as gnuplot, ditaa, dot, asymptote. An
66 attempt is made to find a graphics device corresponding to the file
67 extension (currently .png, .jpg, .jpeg, .tiff, .bmp, .pdf, .ps,
68 .postscript are recognised); if that fails, png format output is
71 Additionally, values for several arguments to the R graphics
72 device can be passed using header args:
74 :width :height :bg :units :pointsize
75 :antialias :quality :compression :res :type
76 :family :title :fonts :version :paper :encoding
77 :pagecentre :colormodel :useDingbats :horizontal
79 Arguments to the R graphics device that are not supported as header
80 args can be passed as a string in R argument syntax, using the header
83 An example block is (although both bg and fg can be passed directly as
86 \#+begin_src R :file z.pdf :width 8 :height 8 :R-dev-args bg="olivedrab", fg="hotpink"
87 plot(matrix(rnorm(100), ncol=2), type="l")
90 - Yes, I think we do want a version of this for python and ruby et al. In
91 your example, the filename is created in python. I suggest doing it
92 slightly differently, something like this.
95 #+begin_src python :file outfile.txt
96 def savetofile(result, filename):
97 with open(filename, 'w') as f:
99 savetofile(78, 'outfile.txt')
103 #+resname: fileoutput
106 This functionality is now available for ruby & python in branch
107 ded-babel of git://orgmode.org/org-mode/babel.git.
109 So here, if you specify :file <filepath> ruby/python blindly outputs a
110 link to <filepath>, regardless of the contents of the
111 code. Responsibility for creating useful contents of <filepath> lies
112 with the code. Notice that with this you have to specify the output file
113 twice: once as an org-babel directive, and once in the python code. This
114 is in contrast to the graphics languages (dot, ditaa, asymptote), where
115 the results *automatically* get sent to the file specified by :file. The
116 same is also true now for graphical output from R.
118 The difference with python, ruby et al is that they might create file
119 output in a variety of ways which we can't anticipate, so we can't
120 automatically send output to the file. In contrast, the graphics
121 language *always* create file output and always do it in the same
122 way. [And in R it is possible to divert all graphical output to file] A
123 possible extension of the above might be to use a "magic variable" so
124 that a python variable is created e.g. __org_babel_output_file__ that
125 always holds a string corresponding to the file specified by :file. Eric
126 may have further ideas / views here.
129 ** DONE What function is bound to C-c '?
130 - this document notes two different functions
133 :CUSTOM_ID: introduction
136 Babel is about letting [[file:languages/index.org][many different languages]] work together.
137 Programming languages live in blocks inside natural language
138 [[https://orgmode.org/][Org-mode]] documents. A piece of data may pass from a table to a
139 Python code block, then maybe move on to an =R= code block, and
140 finally end up embedded as a value in the middle of a paragraph or
141 possibly pass through a =gnuplot= code block and end up as a plot
142 embedded in the document.
144 Through extending [[https://orgmode.org/][Org-mode]] with several features for editing
145 exporting and executing source code Babel turns Org-mode into a tool
146 for both /Literate Programming/ and /Reproducible Research/.
148 Babel augments [[https://orgmode.org/manual/Literal-examples.html][Org-mode support for code blocks]] by providing:
150 - interactive and on-export execution of code blocks;
151 - code blocks as functions that can be parameterised, refer to
152 other code blocks, and be called remotely; and
153 - export to files for literate programming.
156 Babel provides new features on a few different fronts, and
157 different people may want to start in different places.
159 - Using 'src' blocks in Org mode ::
160 If you are not familiar with creating 'src' blocks in an Org-mode
161 buffer, and moving between that buffer and the language major-mode
162 edit buffer, then you should have a look at the relevant section
163 in the [[https://orgmode.org/manual/Literal-examples.html][Org manual]] and [[#source-code-blocks][below]], try it out, and come back.
165 The core of Babel is its ability to execute code in Org-mode
166 'src' blocks, taking input from other blocks and tables, with
167 output to further blocks and tables. This is described starting
168 [[#source-code-execution][here]].
169 - Literate Programming ::
170 If you are a programmer writing code that you would normally
171 execute in some other way (e.g. from the command line, or sourcing
172 it into an interactive session), then a simple introduction to
173 Babel is to place your code in blocks in an Org-mode file, and to
174 use Babel's [[#literate-programming][Literate Programming]] support to extract pure code
177 All of these use cases, as well as exhaustive documentation of the
178 features of Babel are covered in the [[https://orgmode.org/manual/Working-with-source-code.html#Working-with-source-code][Working with Source Code]]
179 section of the Org manual.
181 * Initial Configuration
183 :CUSTOM_ID: getting-started
187 If you have a working Emacs installation, then getting started with
188 Babel is a simple process.
190 1) If you are running Emacs24 a current version of Org-mode with
191 Babel is already available by default. Otherwise, it is strongly
192 recommended that you update to the latest version of Org-mode by
193 [[https://orgmode.org/worg/org-faq.html#keeping-current-with-Org-mode-development][keeping current with Org-mode development]]. As of Org-mode 7.0,
194 Babel is included as part of Org-mode.
196 2) Optionally activate the subset of languages that you will want
197 to execute with Babel. See [[file:languages/index.org::#configure][Configure active languages]]
198 instructions. Emacs Lisp is activated by default so this step
199 can be skipped for now and all =emacs-lisp= examples will still
202 3) If you have made any changes don't forget to evaluate your
207 :CUSTOM_ID: source-code-blocks
210 ** Code Blocks in Org
212 :CUSTOM_ID: source-code-blocks-org
215 Babel is all about [[https://orgmode.org/manual/Literal-examples.html][code blocks]] in Org-mode. If you are
216 unfamiliar with the notion of a code block in Org-mode, where they
217 are called 'src' blocks, please have a look at the [[https://orgmode.org/manual/Literal-examples.html][Org-mode manual]]
220 Code blocks in supported languages can occur anywhere in an
221 Org-mode file. Code blocks can be entered directly into the
222 Org-mode file, but it is often easier to enter code with the
223 function =org-edit-src-code=, which is called with the keyboard
224 shortcut, C-c '. This places the code block in a new buffer with
225 the appropriate mode activated.
228 ,#+begin_src language org-switches
233 For example, a code block of [[http://www.ruby-lang.org/][ruby]] code looks like this in
239 ,"This file was last evaluated on #{Date.today}"
243 ** Code Blocks in Babel
245 :CUSTOM_ID: source-code-blocks-babel
248 Babel adds some new elements to code blocks. The basic
252 ,#+begin_src language org-switches header-arguments
258 - language :: The language of the code in the source-code block. Valid
259 values must be members of =org-babel-interpreters=.
260 - header-arguments :: Header arguments control many facets of the
261 evaluation and output of source-code blocks. See the
262 [[https://orgmode.org/manual/Header-arguments.html#Header-arguments][Header
263 Arguments]] section for a complete review of available header
265 - body :: The source code to be evaluated. An important key-binding
266 is =​C-c '​=. This calls =org-edit-src-code=, a function that brings
267 up an edit buffer containing the code using the Emacs major mode
268 appropriate to the language. You can edit your code block
269 as you regularly would in Emacs.
271 * Source Code Execution
273 :CUSTOM_ID: source-code-execution
276 Babel executes code blocks for *interpreted* languages such
277 as shell, python, R, etc. by passing code to the interpreter, which
278 must be installed on your system. You control what is done with the
279 results of execution.
281 Here are examples of code blocks in three different languages,
282 followed by their output. If you are viewing the Org-mode version of
283 this document in Emacs, place point anywhere inside a block and press
284 C-c C-c to run the code[fn:1] (and feel free to alter it!).
286 In the Org-mode file:
288 : "This file was last evaluated on #{Date.today}"
293 "This file was last evaluated on #{Date.today}"
296 HTML export of the resulting string:
298 : This file was last evaluated on 2009-08-09
301 In the Org-mode file:
303 : echo "This file takes up `du -h org-babel.org |sed 's/\([0-9k]*\)[ ]*org-babel.org/\1/'`"
308 echo "This file takes up `du -h org-babel.org |sed 's/\([0-9k]*\)[ ]*org-babel.org/\1/'`"
311 HTML export of the resulting string:
313 : This file takes up 36K
315 *** [[http://www.r-project.org/][R]]
316 What are the most common words in this file?
317 In the Org-mode file:
318 : #+begin_src R :colnames yes
319 : words <- tolower(scan("intro.org", what="", na.strings=c("|",":")))
320 : t(sort(table(words[nchar(words) > 3]), decreasing=TRUE)[1:10])
325 #+begin_src R :colnames yes
326 words <- tolower(scan("intro.org", what="", na.strings=c("|",":")))
327 t(sort(table(words[nchar(words) > 3]), decreasing=TRUE)[1:10])
331 | code | org-mode | #+end_src | #+begin_src | block | with | babel | that | #+name: | this |
332 |------+----------+-----------+-------------+-------+------+-------+------+---------+------|
333 | 85 | 60 | 47 | 44 | 40 | 38 | 35 | 34 | 33 | 33 |
335 *** [[http://ditaa.sourceforge.net/][ditaa]]
337 In the Org-mode file:
338 : #+begin_src ditaa :file blue.png :cmdline -r
349 #+begin_src ditaa :file blue.png :cmdline -r
359 HTML export of the resulting image:
361 [[file:../../images/babel/blue.png]]
363 ** Capturing the Results of Code Evaluation
367 Babel provides two fundamentally different modes for capturing
368 the results of code evaluation: functional mode and scripting
369 mode. The choice of mode is specified by the =:results= header
371 *** =:results value= (functional mode)
373 :CUSTOM_ID: results-value
375 The 'result' of code evaluation is the *value* of the last
376 statement in the code block. In functional mode, the
377 code block is a function with a return value. The return
378 value of one code block can be used as input for another
379 code block, even one in a different language. In this
380 way, Babel becomes a [[#meta-programming-language][meta-programming language]]. If the block
381 returns tabular data (a vector, array or table of some sort) then
382 this will be held as an Org-mode table in the buffer. This
383 setting is the default.
385 For example, consider the following block of python code and its
388 #+begin_src python :results value
390 print("Hello, today's date is %s" % time.ctime())
391 print('Two plus two is')
398 Notice that, in functional mode, the output consists of the value of
399 the last statement and nothing else.
401 *** =:results output= (scripting mode)
403 :CUSTOM_ID: results-output
406 In scripting mode, Babel captures the text output of the
407 code block and places it in the Org-mode buffer. It is
408 called scripting mode because the code block contains a series of
409 commands, and the output of each command is returned. Unlike
410 functional mode, the code block itself has no return value
411 apart from the output of the commands it contains.[fn:2]
413 Consider the result of evaluating this code block with
417 #+begin_src python :results output
419 print("Hello, today's date is %s" % time.ctime())
420 print('Two plus two is')
425 : Hello, today's date is Wed Nov 11 18:50:36 2009
428 Here, scripting mode returned the text that python sent to =stdout=. Because
429 the code block doesn't include a =print()= statement for the last
430 value, =(2 + 2)=, 4 does not appear in the results.
432 ** Session-based Evaluation
433 For some languages, such as python, R, ruby and shell, it is
434 possible to run an interactive session as an "inferior process"
435 within Emacs. This means that an environment is created containing
436 data objects that persist between different source code
437 blocks. Babel supports evaluation of code within such sessions
438 with the =:session= header argument. If the header argument is
439 given a value then that will be used as the name of the session.
440 Thus, it is possible to run separate simultaneous sessions in the
443 Session-based evaluation is particularly useful for prototyping and
444 debugging. The function =org-babel-pop-to-session= can be used to
445 switch to the session buffer.
447 Once a code block is finished, it is often best to execute it
448 outside of a session, so the state of the environment in which it
449 executes will be certain.
451 With R, the session will be under the control of [[http://ess.r-project.org/][Emacs Speaks
452 Statistics]] as usual, and the full power of ESS is thus still
453 available, both in the R session, and when switching to the R code
454 edit buffer with =​C-c '​=.
456 ** Arguments to Code Blocks
458 :CUSTOM_ID: arguments-to-source-code-blocks
460 Babel supports parameterisation of code blocks, i.e.,
461 arguments can be passed to code blocks, which gives them
462 the status of *functions*. Arguments can be passed to code blocks in
463 both functional and scripting modes.
465 *** Simple example of using a code block as a function
467 First let's look at a very simple example. The following source
468 code block defines a function, using python, that squares its argument.
476 In the Org-mode file, the function looks like this:
484 Now we use the source block:
486 : #+call: square(x=6)
488 (/for information on the/ =call= /syntax see/ [[#library-of-babel][Library of Babel]])
492 #+results: square(x=6)
495 *** A more complex example using an Org-mode table as input
497 In this example we define a function called =fibonacci-seq=, using
498 Emacs Lisp. The function =fibonacci-seq= computes a Fibonacci
499 sequence. The function takes a single argument, in this case, a
500 reference to an Org-mode table.
502 Here is the Org-mode table that is passed to =fibonacci-seq=:
504 #+name: fibonacci-inputs
505 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
506 | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
508 The table looks like this in the Org-mode buffer:
509 : #+tblname: fibonacci-inputs
510 : | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 |
511 : | 2 | 4 | 6 | 8 | 10 | 12 | 14 | 16 | 18 | 20 |
513 The [[http://www.gnu.org/software/emacs/manual/elisp.html][Emacs Lisp]] source code:
514 #+name: fibonacci-seq
515 #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
517 (if (or (= n 0) (= n 1))
519 (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
521 (mapcar (lambda (row)
522 (mapcar #'fibonacci row)) fib-inputs)
525 In the Org-mode buffer the function looks like this:
526 : #+name: fibonacci-seq
527 : #+begin_src emacs-lisp :var fib-inputs=fibonacci-inputs
528 : (defun fibonacci (n)
529 : (if (or (= n 0) (= n 1))
531 : (+ (fibonacci (- n 1)) (fibonacci (- n 2)))))
533 : (mapcar (lambda (row)
534 : (mapcar #'fibonacci row)) fib-inputs)
537 The return value of =fibonacci-seq= is a table:
539 | 1 | 1 | 2 | 3 | 5 | 8 | 13 | 21 | 34 | 55 |
540 | 1 | 3 | 8 | 21 | 55 | 144 | 377 | 987 | 2584 | 6765 |
542 ** In-line Code Blocks
543 Code can be evaluated in-line using the following syntax:
545 : Without header args: src_lang{code} or with header args: src_lang[args]{code},
546 : for example src_python[:session]{10*x}, where x is a variable existing in the
549 ** Code Block Body Expansion
550 Babel "expands" code blocks prior to evaluation, i.e., the
551 evaluated code comprises the code block contents augmented with
552 code that assigns referenced data to variables. It is possible to
553 preview expanded contents, and also to expand code during
554 tangling. Expansion takes into account header arguments and
557 - preview :: =C-c M-b p= is bound to =org-babel-expand-src-block=. It
558 can be used inside a code block to preview the expanded
559 contents. This facility is useful for debugging.
561 - tangling :: The expanded body can be tangled. Tangling this way includes
562 variable values that may be
563 - the results of other code blocks,
564 - variables stored in headline properties, or
567 One possible use for tangling expanded code block is for emacs
568 initialization. Values such as user names and passwords can be
569 stored in headline properties or in tables. The =:no-expand=
570 header argument can be used to inhibit expansion of a code block
573 Here is an example of a code block and its resulting expanded body.
575 The data are kept in a table:
577 | username | john-doe |
578 | password | abc123 |
580 The code block refers to the data table:
581 #+name: setup-my-account
582 #+begin_src emacs-lisp :rownames yes :var data=user-data
583 (setq my-special-username (first (first data)))
584 (setq my-special-password (first (second data)))
587 With point inside the code block, =C-c M-b p= expands the contents:
588 #+begin_src emacs-lisp
589 (let ((data (quote (("john-doe") ("abc123")))))
590 (setq my-special-username (first (first data)))
591 (setq my-special-password (first (second data)))
596 ** A Meta-programming Language for Org-mode
598 :CUSTOM_ID: meta-programming-language
601 Because the return value of a function written in one language can be
602 passed to a function written in another language, or to an Org-mode
603 table, which is itself programmable, Babel can be used as a
604 meta-functional programming language. With Babel, functions from
605 many languages can work together. You can mix and match languages,
606 using each language for the tasks to which it is best suited.
608 For example, let's take some system diagnostics in the shell and graph them with R.
610 1. Create a code block, using shell code, to list
611 directories in our home directory, together with their
612 sizes. Babel automatically converts the output into an Org-mode
615 : #+name: directories
616 : #+begin_src sh :results replace
617 : cd ~ && du -sc * |grep -v total
620 #+resname: directories
622 | 12156104 | "Documents" |
623 | 3482440 | "Downloads" |
624 | 2901720 | "Library" |
626 | 16548024 | "Music" |
628 | 7649472 | "Pictures" |
637 2. A function, written with a single line of R code, plots the data
638 in the Org-mode table as a
639 pie-chart. Note how this code block uses the =srcname=
640 of the previous code block to obtain the data.
642 In the Org-mode file:
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])
649 #+name: directory-pie-chart(dirs=directories)
650 #+begin_src R :session R-pie-example :file ../../images/babel/dirs.png
651 pie(dirs[,1], labels = dirs[,2])
653 [[file:../../images/babel/dirs.png]]
655 * Using Code Blocks in Org Tables
657 :CUSTOM_ID: spreadsheet
660 In addition to passing data from tables as [[#arguments-to-source-code-blocks][arguments]] to code
661 blocks, and [[#results-value][storing]] results as tables, Babel can be used in a
662 third way with Org-mode tables. First note that Org-mode's [[https://orgmode.org/manual/The-spreadsheet.html#The-spreadsheet][existing
663 spreadsheet functionality]] allows values in cells to be computed
664 automatically from the values of other cells, using a =#+TBLFM=
665 formula line. In this way, table computations can be carried out using
666 [[https://orgmode.org/manual/Formula-syntax-for-Calc.html#Formula-syntax-for-Calc][calc]] and [[https://orgmode.org/manual/Formula-syntax-for-Lisp.html#Formula-syntax-for-Lisp][emacs lisp]].
668 What Babel adds is the ability to use code blocks (in whatever
669 language) in the =#+TBLFM= line to perform the necessary computation.
671 *** Example 1: Data Summaries Using R
672 As a simple example, we'll fill in a cell in an Org-mode table with the
673 average value of a few numbers. First, let's make some data. The
674 following source block creates an Org-mode table filled with five random
675 numbers between 0 and 1.
677 : #+name: tbl-example-data
679 : runif(n=5, min=0, max=1)
682 #+name: tbl-example-data
683 | 0.836685163900256 |
684 | 0.696652316721156 |
685 | 0.382423302158713 |
686 | 0.987541858805344 |
687 | 0.994794291909784 |
689 Now we define a source block to calculate the mean of a table column.
691 In the Org-mode file:
693 : #+begin_src R :var x=""
699 #+begin_src R :var x=""
703 Finally, we create the table which is going to make use of the R
704 code. This is done using the =org-sbe= ('source block evaluate') macro in
705 the table formula line.
707 In the Org-mode file:
708 : #+tblname: summaries
710 : |-------------------|
711 : | 0.779619386699051 |
712 : #+TBLFM: @2$1='(org-sbe "R-mean" (x "tbl-example-data()"))
719 #+TBLFM: @2$1='(org-sbe "R-mean" (x "tbl-example-data()"));%.2f
721 To recalculate the table formula, use C-u C-c C-c in the
722 table. Notice that as things stand the calculated value doesn't
723 change, because the data (held in the table above named
724 =tbl-example-data=) are static. However, if you delete that data table,
725 then the reference will be interpreted as a reference to the source
726 block responsible for generating the data; each time the table formula
727 is recalculated the source block will be evaluated again, and
728 therefore the calculated average value will change.
730 *** Example 2: Babel Test Suite
731 While developing Babel, we used a suite of tests implemented
732 as a large Org-mode table. To run the entire test suite we simply
733 evaluate the table with C-u C-c C-c: all of the tests are run,
734 the results are compared with expectations, and the table is updated
735 with results and pass/fail statistics.
737 Here's a sample of our test suite.
739 In the Org-mode file:
741 : #+TBLNAME: org-babel-tests
742 : | functionality | block | arg | expected | results | pass |
743 : |------------------+--------------+-----+-------------+-------------+------|
744 : | basic evaluation | | | | | pass |
745 : |------------------+--------------+-----+-------------+-------------+------|
746 : | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
747 : | shell | basic-shell | | 6 | 6 | pass |
748 : | ruby | basic-ruby | | org-babel | org-babel | pass |
749 : | python | basic-python | | hello world | hello world | pass |
750 : | R | basic-R | | 13 | 13 | pass |
751 : #+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))
755 #+TBLNAME: org-babel-tests
756 | functionality | block | arg | expected | results | pass |
757 |------------------+--------------+-----+-------------+-------------+------|
758 | basic evaluation | | | | | pass |
759 |------------------+--------------+-----+-------------+-------------+------|
760 | emacs lisp | basic-elisp | 2 | 4 | 4 | pass |
761 | shell | basic-shell | | 6 | 6 | pass |
762 | ruby | basic-ruby | | org-babel | org-babel | pass |
763 | python | basic-python | | hello world | hello world | pass |
764 | R | basic-R | | 13 | 13 | pass |
765 #+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))
767 **** code blocks for tests
769 In the Org-mode file:
771 : #+name: basic-elisp(n)
772 : #+begin_src emacs-lisp
778 #+name: basic-elisp(n=0)
779 #+begin_src emacs-lisp
783 In the Org-mode file:
784 : #+name: basic-shell
785 : #+begin_src sh :results silent
791 #+begin_src sh :results silent
795 In the Org-mode file:
796 : #+name: date-simple
797 : #+begin_src sh :results silent
803 #+begin_src sh :results silent
807 In the Org-mode file:
809 : #+begin_src ruby :results silent
815 #+begin_src ruby :results silent
820 : #+name: basic-python
821 : #+begin_src python :results silent
827 #+begin_src python :results silent
831 In the Org-mode file:
833 : #+begin_src R :results silent
840 #+begin_src R :results silent
845 * The Library of Babel
847 :CUSTOM_ID: library-of-babel
850 (see also [[https://orgmode.org/manual/Library-of-Babel.html#Library-of-Babel][Org manual:Library-of-Babel]])
852 As we saw above with the [[*Simple example of using a code block as a function][square]] example, once a source block
853 function has been defined it can be called using the =lob= notation:
857 But what about code blocks that you want to make available to
858 every Org-mode buffer?
860 In addition to the current buffer, Babel searches for
861 pre-defined code block functions in the Library of
862 Babel. This is a user-extensible collection of ready-made source
863 code blocks for handling common tasks. One use for the Library of
864 Babel (not yet done!) will be to provide a choice of data graphing
865 procedures for data held in Org-mode tables, using languages such as
866 R, gnuplot, asymptote, etc. If you implement something that might be
867 of use to other Org-mode users, please consider adding it to the
868 Library of Babel; similarly, feel free to request help solving a
869 problem using external code via Babel -- there's always a chance
870 that other Babel users will be able to contribute some helpful
873 Babel comes pre-populated with the code blocks located in
874 the [[file:library-of-babel.org][Library of Babel]] file -- raw file at
875 @@html: <a href="https://code.orgmode.org/bzg/worg/raw/master/library-of-babel.org">library-of-babel.org</a>@@
876 --. It is possible to add code blocks to the library from any
877 Org-mode file using the =org-babel-lob-ingest= (bound to =C-c C-v
880 #+name: add-file-to-lob
881 #+begin_src emacs-lisp
882 (org-babel-lob-ingest "path/to/file.org")
885 Note that it is possible to pass table values or the output of a
886 source-code block to Library of Babel functions. It is also possible
887 to reference Library of Babel functions in arguments to code blocks.
889 * Literate Programming
891 :CUSTOM_ID: literate-programming
895 Let us change our traditional attitude to the construction of
896 programs: Instead of imagining that our main task is to instruct a
897 /computer/ what to do, let us concentrate rather on explaining to
898 /human beings/ what we want a computer to do.
900 The practitioner of literate programming can be regarded as an
901 essayist, whose main concern is with exposition and excellence of
902 style. Such an author, with thesaurus in hand, chooses the names of
903 variables carefully and explains what each variable means. He or she
904 strives for a program that is comprehensible because its concepts have
905 been introduced in an order that is best for human understanding,
906 using a mixture of formal and informal methods that reinforce each
912 Babel supports [[https://en.wikipedia.org/wiki/Literate_programming][Literate Programming]] (LP) by allowing the act of
913 programming to take place inside of Org-mode documents. The Org-mode
914 file can then be exported (*woven* in LP speak) to HTML or LaTeX for
915 consumption by a human, and the embedded source code can be extracted
916 (*tangled* in LP speak) into structured source code files for
917 consumption by a computer.
919 To support these operations Babel relies on Org-mode's [[https://orgmode.org/manual/Exporting.html#Exporting][existing
920 exporting functionality]] for *weaving* of documentation, and on the
921 =org-babel-tangle= function which makes use of [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] [[#literate-programming-example][reference syntax]]
922 for *tangling* of code files.
924 The [[#literate-programming-example][following example]] demonstrates the process of *tangling* in
927 *** Simple Literate Programming Example (Noweb syntax)
929 :CUSTOM_ID: literate-programming-example
932 Tangling functionality is controlled by the =tangle= family of tangle
933 header arguments. These arguments can be used to turn tangling on or
934 off (the default), either for the code block or the Org-mode
937 The following code blocks demonstrate how to tangle them into a
938 single source code file using =org-babel-tangle=.
940 The following two code blocks have no =tangle= header arguments
941 and so will not, by themselves, create source code files. They are
942 included in the source code file by the third code block, which
943 does have a =tangle= header argument.
945 In the Org-mode file:
946 : #+name: hello-world-prefix
947 : #+begin_src sh :exports none
948 : echo "/-----------------------------------------------------------\\"
952 #+name: hello-world-prefix
953 #+begin_src sh :exports none
954 echo "/-----------------------------------------------------------\\"
958 : #+name: hello-world-postfix
959 : #+begin_src sh :exports none
960 : echo "\-----------------------------------------------------------/"
964 #+name: hello-world-postfix
965 #+begin_src sh :exports none
966 echo "\-----------------------------------------------------------/"
970 The third code block does have a =tangle= header argument
971 indicating the name of the file to which the tangled source code will
972 be written. It also has [[http://www.cs.tufts.edu/~nr/noweb/][Noweb]] style references to the two previous
973 code blocks. These references will be expanded during tangling
974 to include them in the output file as well.
976 In the Org-mode file:
977 : #+name: hello-world
978 : #+begin_src sh :tangle hello :exports none :noweb yes
979 : <<hello-world-prefix>>
980 : echo "| hello world |"
981 : <<hello-world-postfix>>
986 #+begin_src sh :tangle hello.sh :exports none :noweb yes
987 <<hello-world-prefix>>
988 echo "| hello world |"
989 <<hello-world-postfix>>
993 Calling =org-babel-tangle= will result in the following shell source
994 code being written to the =hello.sh= file:
996 #+name: hello-world-output
1000 # [[file:~/org/temp/index.org::*Noweb%20test][hello-world]]
1002 echo "/-----------------------------------------------------------\\"
1003 echo "| hello world |"
1004 echo "\-----------------------------------------------------------/"
1005 # hello-world ends here
1008 In addition, the following syntax can be used to insert the *results*
1009 of evaluating a code block, in this case one named =example-block=.
1011 : # <<example-block()>>
1013 Any optional arguments can be passed to =example-block()= by placing the
1014 arguments inside the parentheses following the convention defined when
1015 calling source block functions (see the [[#library-of-babel][Library of babel]]). For example,
1017 : # <<example-block(a=9)>>
1019 sets the value of argument \"a\" equal to \"9\". Note that
1020 these arguments are not evaluated in the current source-code
1021 block but are passed literally to =example-block()=.
1023 *** Emacs Initialization with Babel
1025 :CUSTOM_ID: emacs-initialization
1028 #+attr_html: style="float:left;"
1029 [[file:../../images/babel/dot-emacs.png]]
1031 Babel has special support for embedding your Emacs initialization
1032 into Org-mode files. The =org-babel-load-file= function can be used
1033 to load the Emacs Lisp code blocks embedded in a literate
1034 Org-mode file in the same way that you might load a regular Emacs Lisp
1035 file, such as .emacs.
1037 This allows you to make use of the nice features of Org-mode, such as folding, tags,
1038 notes, HTML export, etc., to organize and maintain your Emacs initialization.
1040 To try this out, either see the simple [[#literate-emacs-init][Literate Emacs Initialization]]
1041 example, or check out the Babel Literate Programming version of
1042 Phil Hagelberg's excellent [[http://github.com/technomancy/emacs-starter-kit/tree/master][emacs-starter-kit]] available at
1043 [[http://github.com/eschulte/emacs-starter-kit/tree/master][Org-babel-emacs-starter-kit]].
1045 ***** Literate Emacs Initialization
1047 :CUSTOM_ID: literate-emacs-init
1050 For a simple example of usage, follow these 5 steps:
1052 1) create a directory named =.emacs.d= in the base of your home
1057 2) checkout the latest version of Org-mode into the src subdirectory
1058 of this new directory;
1063 git clone https://code.orgmode.org/bzg/org-mode.git
1065 3) place the following code block in a file called =init.el= in your Emacs
1066 initialization directory (=~/.emacs.d=).
1068 #+begin_src emacs-lisp
1069 ;;; init.el --- Where all the magic begins
1071 ;; This file loads Org-mode and then loads the rest of our Emacs initialization from Emacs lisp
1072 ;; embedded in literate Org-mode files.
1074 ;; Load up Org Mode and (now included) Org Babel for elisp embedded in Org Mode files
1075 (setq dotfiles-dir (file-name-directory (or (buffer-file-name) load-file-name)))
1077 (let* ((org-dir (expand-file-name
1078 "lisp" (expand-file-name
1079 "org" (expand-file-name
1080 "src" dotfiles-dir))))
1081 (org-contrib-dir (expand-file-name
1082 "lisp" (expand-file-name
1083 "contrib" (expand-file-name
1085 (load-path (append (list org-dir org-contrib-dir)
1086 (or load-path nil))))
1087 ;; load up Org-mode and Org-babel
1089 (require 'ob-tangle))
1091 ;; load up all literate org-mode files in this directory
1092 (mapc #'org-babel-load-file (directory-files dotfiles-dir t "\\.org$"))
1094 ;;; init.el ends here
1096 4) implement all of your Emacs customizations inside of Emacs Lisp
1097 code blocks embedded in Org-mode files in this directory;
1099 5) re-start Emacs to load the customizations.
1101 * Reproducible Research
1103 :CUSTOM_ID: reproducible-research
1106 An article about computational science in a scientific publication is
1107 not the scholarship itself, it is merely advertising of the
1108 scholarship. The actual scholarship is the complete software
1109 development environment and the complete set of instructions which
1110 generated the figures.
1115 [[http://reproducibleresearch.net/index.php/Main_Page][Reproducible Research]] (RR) is the practice of distributing, along with
1116 a research publication, all data, software source code, and tools
1117 required to reproduce the results discussed in the publication. As
1118 such the RR package not only describes the research and its results,
1119 but becomes a complete laboratory in which the research can be
1120 reproduced and extended.
1122 Org-mode already has exceptional support for [[https://orgmode.org/manual/Exporting.html#Exporting][exporting to HTML and
1123 LaTeX]]. Babel makes Org-mode a tool for RR by *activating* the
1124 data and code blocks embedded in Org-mode documents; the
1125 entire document becomes executable. This makes it possible, and natural, to
1126 distribute research in a format that encourages readers to recreate
1127 results and perform their own analyses.
1129 One notable existing RR tool is [[https://en.wikipedia.org/wiki/Sweave][Sweave]], which provides a mechanism for
1130 embedding [[http://www.r-project.org/][R]] code into LaTeX documents. Sweave is a mature
1131 and very useful tool, but we believe that Babel has several
1133 - it supports multiple languages (we're not aware of other RR tools that do this);
1134 - the [[https://orgmode.org/manual/Exporting.html#Exporting][export process]] is flexible and powerful, including HTML as a
1135 target in addition to LaTeX; and
1136 - the document can make use of Org-mode features that support [[https://orgmode.org/manual/Agenda-views.html#Agenda-views][project
1137 planning]] and [[https://orgmode.org/manual/TODO-items.html#TODO-items][task management]].
1140 [fn:1] Calling =C-c C-o= on a code block will open the
1141 block's results in a separate buffer.
1143 [fn:2] This mode will be familiar to Sweave users.