14 Working with Source Code

Intro

Source code here refers to any plain text collection of computer instructions, possibly with comments, written using a human-readable programming language. Org can manage source code in an Org document when the source code is identified with begin and end markers. Working with source code begins with identifying source code blocks. A source code block can be placed almost anywhere in an Org document; it is not restricted to the preamble [pri’æmb(ə)l] or the end of the document. However, Org cannot manage a source code block if it is placed inside an Org comment or within a fixed width section.

Here is an example source code block in the Emacs Lisp language:

1
2
3
4
5
#+BEGIN_SRC emacs-lisp
(defun org-xor (a b)
"Exclusive or."
(if a (not b) b))
#+END_SRC

Org can manage the source code in the block delimited by ‘#+BEGIN_SRC’ … ‘#+END_SRC’ in several ways that can simplify housekeeping tasks essential to modern source code maintenance. Org can edit, format, extract, export, and publish source code blocks. Org can also compile and execute a source code block, then capture the results. The Org mode literature sometimes refers to source code blocks as live code blocks because they can alter the content of the Org document or the material that it exports. Users can control how live they want each source code block by tweaking the header arguments (see [Using Header A for compiling, execution, extraction, and exporting.

Source code blocks are one of many Org block types, which also include “center”, “comment”, “dynamic”, “example”, “export”, “quote”, “special”, and “verse”. This section pertains to blocks between ‘#+BEGIN_SRC’ and ‘#+END_SRC’.

For editing and formatting a source code block, Org uses an appropriate Emacs major mode that includes features specifically designed for source code in that language.

Org can extract one or more source code blocks and write them to one or more source files—a process known as tangling in literate programming terminology.

For exporting and publishing, Org’s back-ends can format a source code block appropriately, often with native syntax highlighting.

For executing and compiling a source code block, the user can configure Org to select the appropriate compiler. Org provides facilities to collect the result of the execution or compiler output, insert it into the Org document, and/or export it. In addition to text results, Org can insert links to other data types, including audio, video, and graphics. Org can also link a compiler error message to the appropriate line in the source code block.

An important feature of Org’s management of source code blocks is the ability to pass variables, functions, and results to one another using a common syntax for source code blocks in any language. Although most literate programming facilities are restricted to one language or another, Org’s language-agnostic approach lets the literate programmer match each programming task with the appropriate computer language and to mix them all together in a single Org document. This interoperability among languages explains why Org’s source code management facility was named Org Babel by its originators, Eric Schulte and Dan Davison.

Org mode fulfills the promise of easy verification and maintenance of publishing reproducible research by keeping text, data, code, configuration settings of the execution environment, the results of the execution, and associated narratives, claims, references, and internal and external links in a single Org document.

Details of Org’s facilities for working with source code are described in the following sections.

Structure of Code Blocks: Code block syntax described.
Using Header Arguments: Different ways to set header arguments.
Environment of a Code Block: Arguments, sessions, working directory…
Evaluating Code Blocks: Place results of evaluation in the Org buffer.
Results of Evaluation: Choosing a results type, post-processing…
Exporting Code Blocks: Export contents and/or results.
Extracting Source Code: Create pure source code files.
Languages: List of supported code block languages.
Editing Source Code: Language major-mode editing.
Noweb Reference Syntax: Literate programming in Org mode.
Library of Babel: Use and contribute to a library of useful code blocks.
Key bindings and Useful Functions: Work quickly with code blocks.

14.1 Structure of Code Blocks

Org offers two ways to structure source code in Org documents: in a source code block, and directly inline. Both specifications are shown below.

A source code block conforms to this structure:

1
2
3
4
#+NAME: <name>
#+BEGIN_SRC <language> <switches> <header arguments>
<body>
#+END_SRC

Do not be put-off by having to remember the source block syntax. Org mode offers a command for wrapping existing text in a block (see Structure Templates). Org also works with other completion systems in Emacs, some of which predate Org and have custom domain-specific languages for defining templates. Regular use of templates reduces errors, increases accuracy, and maintains consistency.

An inline code block conforms to this structure:

1
src_<language>{<body>}

or

1
src_<language>[<header arguments>]{<body>}

1) ‘#+NAME:

Optional. Names the source block so it can be called, like a function, from other source blocks or inline code to evaluate or to capture the results. Code from other blocks, other files, and from table formulas (see The Spreadsheet) can use the name to reference a source block. This naming serves the same purpose as naming Org tables. Org mode requires unique names. For duplicate names, Org mode’s behavior is undefined.

2) ‘#+BEGIN_SRC’ … ‘#+END_SRC’

Mandatory. They mark the start and end of a block that Org requires. The ‘#+BEGIN_SRC’ line takes additional arguments, as described next.

3) ‘

Mandatory. It is the identifier of the source code language in the block. See Languages, for identifiers of supported langua
ges.

4) ‘

Optional. Switches provide finer control of the code execution, export, and format (see the discussion of switches in Literal Examples).

5) ‘

Optional. Heading arguments control many aspects of evaluation, export and tangling of code blocks (see Using Header Arguments). Using Org’s properties feature, header arguments can be selectively applied to the entire buffer or specific sub-trees of the Org document.

6) ‘’
^
Source code in the dialect of the specified language identifier.

14.2 Using Header Arguments

Org comes with many header arguments common to all languages. New header arguments are added for specific languages as they become available for use in source code blocks. A header argument is specified with an initial colon followed by the argument’s name in lowercase.

Since header arguments can be set in several ways, Org prioritizes them in case of overlaps or conflicts by giving local settings a higher priority. Header values in function calls, for example, override header values from global defaults.

1.System-wide header arguments

System-wide values of header arguments can be specified by customizing the org-babel-default-header-args variable, which defaults to the following values:

1
2
3
4
5
:session    => "none"
:results => "replace"
:exports => "code"
:cache => "no"
:noweb => "no"

The example below sets ‘:noweb’ header arguments to ‘yes’, which makes Org expand ‘:noweb’ references by default.

1
2
3
(setq org-babel-default-header-args
(cons '(:noweb . "yes")
(assq-delete-all :noweb org-babel-default-header-args)))

Each language can have separate default header arguments by customizing the variable org-babel-default-header-args:<LANG>, where is the name of the language. For details, see the language-specific online documentation at https://orgmode.org/worg/org-contrib/babel/.

2.Header arguments in Org mode properties

For header arguments applicable to the buffer, use ‘PROPERTY’ keyword anywhere in the Org file (see Property Syntax).

The following example makes all the R code blocks execute in the same session. Setting ‘:results’ to ‘silent’ ignores the results of executions for all blocks, not just R code blocks; no results inserted for any block.

1
2
#+PROPERTY: header-args:R  :session *R*
#+PROPERTY: header-args :results silent

Header arguments set through Org’s property drawers (see Property Syntax) apply at the sub-tree level on down. Since these property drawers can appear anywhere in the file hierarchy, Org uses outermost call or source block to resolve the values. Org ignores org-use-property-inheritance setting.

In this example, ‘:cache’ defaults to ‘yes’ for all code blocks in the sub-tree.

1
2
3
4
 sample header
:PROPERTIES:
:header-args: :cache yes
:END:

Properties defined through org-set-property function, bound to C-c C-x p, apply to all active languages. They override properties set in org-babel-default-header-args.

Language-specific header arguments are also read from properties ‘header-args:’ where is the language identifier. For example,

1
2
3
4
5
6
7
8
9
Heading
:PROPERTIES:
:header-args:clojure: :session *clojure-1*
:header-args:R: :session *R*
:END:
Subheading
:PROPERTIES:
:header-args:clojure: :session *clojure-2*
:END:

would force separate sessions for Clojure blocks in ‘Heading’ and ‘Subheading’, but use the same session for all R blocks. Blocks in ‘Subheading’ inherit settings from ‘Heading’.

3.Code block specific header arguments

Header arguments are most commonly set at the source code block level, on the ‘#+BEGIN_SRC’ line. Arguments set at this level take precedence over those set in the org-babel-default-header-args variable, and also those set as header properties.

In the following example, setting ‘:results’ to ‘silent’ makes it ignore results of the code execution. Setting ‘:exports’ to ‘code’ exports only the body of the code block to HTML or LaTeX.

1
2
3
4
#+NAME: factorial
#+BEGIN_SRC haskell :results silent :exports code :var n=0
fac 0 = 1
#+END_SRC

The same header arguments in an inline code block:

1
src_haskell[:exports both]{fac 5}

Code block header arguments can span multiple lines using ‘#+HEADER:’ on each line. Note that Org currently accepts the plural spelling of ‘#+HEADER:’ only as a convenience for backward-compatibility. It may be removed at some point.

Multi-line header arguments on an unnamed code block:

1
2
3
4
5
6
7
#+HEADER: :var data1=1
#+BEGIN_SRC emacs-lisp :var data2=2
(message "data1:%S, data2:%S" data1 data2)
#+END_SRC

#+RESULTS:
: data1:1, data2:2

Multi-line header arguments on a named code block:

1
2
3
4
5
6
7
8
#+NAME: named-block
#+HEADER: :var data=2
#+BEGIN_SRC emacs-lisp
(message "data:%S" data)
#+END_SRC

#+RESULTS: named-block
: data:2
  • Header arguments in function calls

Header arguments in function calls are the most specific and override all other settings in case of an overlap. They get the highest priority. Two ‘#+CALL:’ examples are shown below. For the complete syntax of ‘CALL’ keyword, see Evaluating Code Blocks.

In this example, ‘:exports results’ header argument is applied to the evaluation of the ‘#+CALL:’ line.

1
#+CALL: factorial(n=5) :exports results

In this example, ‘:session special’ header argument is applied to the evaluation of ‘factorial’ code block.

1
#+CALL: factorial[:session special](n=5)

14.3 Environment of a Code Block

1.Passing arguments

Use ‘var’ for passing arguments to source code blocks. The specifics of variables in code blocks vary by the source language and are covered in the language-specific documentation. The syntax for ‘var’, however, is the same for all languages. This includes declaring a variable, and assigning a default value.

The following syntax is used to pass arguments to code blocks using the ‘var’ header argument.

1
:var NAME=ASSIGN

NAME is the name of the variable bound in the code block body. ASSIGN is a literal value, such as a string, a number, a reference to a table, a list, a literal example, another code block—with or without arguments—or the results of evaluating a code block.

Here are examples of passing values by reference:

  1. table

    A table named with a ‘NAME’ keyword.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    #+NAME: example-table
    | 1 |
    | 2 |
    | 3 |
    | 4 |

    #+NAME: table-length
    #+BEGIN_SRC emacs-lisp :var table=example-table
    (length table)
    #+END_SRC

    #+RESULTS: table-length

    When passing a table, you can treat specially the row, or the column, containing labels for the columns, or the rows, in the table.The ‘colnames’ header argument accepts ‘yes’, ‘no’, or ‘nil’ values. The default value is ‘nil’: if an input table has column names—because the second row is a horizontal rule—then Org removes the column names, processes the table, puts back the column names, and then writes the table to the results block. Using ‘yes’, Org does the same to the first row, even if the initial table does not contain any horizontal rule. When set to ‘no’, Org does not pre-process column names at all.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #+NAME: less-cols
    | a |
    |---|
    | b |
    | c |

    #+BEGIN_SRC python :var tab=less-cols :colnames nil
    return [[val + '*' for val in row] for row in tab]
    #+END_SRC
    #+RESULTS:
    | a |
    |----|
    | b* |
    | c* |

    Similarly, the ‘rownames’ header argument can take two values: ‘yes’ or ‘no’. When set to ‘yes’, Org removes the first column, processes the table, puts back the first column, and then writes the table to the results block. The default is ‘no’, which means Org does not pre-process the first column. Note that Emacs Lisp code blocks ignore ‘rownames’ header argument because of the ease of table-handling in Emacs.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #+NAME: with-rownames
    | one | 1 | 2 | 3 | 4 | 5 |
    | two | 6 | 7 | 8 | 9 | 10 |
    #+BEGIN_SRC python :var tab=with-rownames :rownames yes
    return [[val + 10 for val in row] for row in tab]
    #+END_SRC
    #+RESULTS:
    | one | 11 | 12 | 13 | 14 | 15 |
    | two | 16 | 17 | 18 | 19 | 20 |
  2. list

    A simple named list.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    #+NAME: example-list
    - simple
    - not
    - nested
    - list
    #+BEGIN_SRC emacs-lisp :var x=example-list
    (print x)c
    #+END_SRC
    #+RESULTS:
    | simple | list |

    Note that only the top level list items are passed along. Nested list items are ignored.

  3. code block without arguments

    A code block name, as assigned by ‘NAME’ keyword from the example above, optionally followed by parentheses.

    1
    2
    3
    4
    5
    6
    #+BEGIN_SRC emacs-lisp :var length=table-length()
    (* 2 length)
    #+END_SRC

    #+RESULTS:
    : 8
  4. code block with arguments

    A code block name, as assigned by ‘NAME’ keyword, followed by parentheses and optional arguments passed within the parentheses.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #+NAME: double
    #+BEGIN_SRC emacs-lisp :var input=8
    (* 2 input)
    #+END_SRC

    #+RESULTS: double
    : 16
    #+NAME: squared
    #+BEGIN_SRC emacs-lisp :var input=double(input=1)
    (* input input)
    #+END_SRC
    #+RESULTS: squared
    : 4
  5. literal example

    A literal example block named with a ‘NAME’ keyword.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    #+NAME: literal-example
    #+BEGIN_EXAMPLE
    A literal example
    on two lines
    #+END_EXAMPLE

    #+NAME: read-literal-example
    #+BEGIN_SRC emacs-lisp :var x=literal-example
    (concatenate #'string x " for you.")
    #+END_SRC

    #+RESULTS: read-literal-example
    : A literal example
    : on two lines for you.

Indexing variable values enables referencing portions of a variable. Indexes are 0 based with negative values counting backwards from the end. If an index is separated by commas then each subsequent section indexes as the next dimension. Note that this indexing occurs before other table-related header arguments are applied, such as ‘hlines’, ‘colnames’ and ‘rownames’. The following example assigns the last cell of the first row the table ‘example-table’ to the variable ‘data’:

1
2
3
4
5
6
7
8
9
10
11
12
#+NAME: example-table
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |

#+BEGIN_SRC emacs-lisp :var data=example-table[0,-1]
data
#+END_SRC

#+RESULTS:
: a

Two integers separated by a colon reference a range of variable values. In that case the entire inclusive range is referenced. For example the following assigns the middle three rows of ‘example-table’ to ‘data’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#+NAME: example-table
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |
| 5 | 3 |

#+BEGIN_SRC emacs-lisp :var data=example-table[1:3]
data
#+END_SRC

#+RESULTS:
| 2 | b |
| 3 | c |
| 4 | d |

To pick the entire range, use an empty index, or the single character ‘*’. ‘0:-1’ does the same thing. Example below shows how to reference the first column only.

1
2
3
4
5
6
7
8
9
10
11
12
#+NAME: example-table
| 1 | a |
| 2 | b |
| 3 | c |
| 4 | d |

#+BEGIN_SRC emacs-lisp :var data=example-table[,0]
data
#+END_SRC

#+RESULTS:
| 1 | 2 | 3 | 4 |

Index referencing can be used for tables and code blocks. Index referencing can handle any number of dimensions. Commas delimit multiple dimensions, as shown below.

1
2
3
4
5
6
7
8
9
10
11
12
13
#+NAME: 3D
#+BEGIN_SRC emacs-lisp
'(((1 2 3) (4 5 6) (7 8 9))
((10 11 12) (13 14 15) (16 17 18))
((19 20 21) (22 23 24) (25 26 27)))
#+END_SRC

#+BEGIN_SRC emacs-lisp :var data=3D[1,,1]
data
#+END_SRC

#+RESULTS:
| 11 | 14 | 17 |

Note that row names and column names are not removed prior to variable indexing. You need to take them into account, even when ‘colnames’ or ‘rownames’ header arguments remove them.

Emacs lisp code can also set the values for variables. To differentiate a value from Lisp code, Org interprets any value starting with ‘(’, ‘[’, ‘’’ or ‘`’ as Emacs Lisp code. The result of evaluating that code is then assigned to the value of that variable. The following example shows how to reliably query and pass the file name of the Org mode buffer to a code block using headers. We need reliability here because the file’s name could change once the code in the block starts executing.

1
2
3
#+BEGIN_SRC sh :var filename=(buffer-file-name) :exports both
wc -w $filename
#+END_SRC

Note that values read from tables and lists are not mistakenly evaluated as Emacs Lisp code, as illustrated in the following example.

1
2
3
4
5
6
7
8
9
10
#+NAME: table
| (a b c) |

#+HEADER: :var data=table[0,0]
#+BEGIN_SRC perl
$data
#+END_SRC

#+RESULTS:
: (a b c)

2.Using sessions

Two code blocks can share the same environment. The ‘session’ header argument is for running multiple source code blocks under one session. Org runs code blocks with the same session name in the same interpreter process.

1) ‘none’

Default. Each code block gets a new interpreter process to execute. The process terminates once the block is evaluated.

2) STRING

Any string besides ‘none’ turns that string into the name of that session. For example, ‘:session STRING’ names it ‘STRING’. If ‘session’ has no value, then the session name is derived from the source language identifier. Subsequent blocks with the same source code language use the same session. Depending on the language, state variables, code from other blocks, and the overall interpreted environment may be shared. Some interpreted languages support concurrent sessions when subsequent source code language blocks change session names.

Only languages that provide interactive evaluation can have session support. Not all languages provide this support, such as C and ditaa. Even languages, such as Python and Haskell, that do support interactive evaluation impose limitations on allowable language constructs that can run interactively. Org inherits those limitations for those code blocks running in a session.

3.Choosing a working directory

The ‘dir’ header argument specifies the default directory during code block execution. If it is absent, then the directory associated with the current buffer is used. In other words, supplying ‘:dir PATH’ temporarily has the same effect as changing the current directory with M-x cd PATH, and then not setting ‘dir’. Under the surface, ‘dir’ simply sets the value of the Emacs variable default-directory.

For example, to save the plot file in the ‘Work/’ folder of the home directory—notice tilde is expanded:

1
2
3
#+BEGIN_SRC R :file myplot.png :dir ~/Work
matplot(matrix(rnorm(100), 10), type="l")
#+END_SRC

To evaluate the code block on a remote machine, supply a remote directory name using Tramp syntax. For example:

1
2
3
#+BEGIN_SRC R :file plot.png :dir /scp:dand@yakuba.princeton.edu:
plot(1:10, main=system("hostname", intern=TRUE))
#+END_SRC

Org first captures the text results as usual for insertion in the Org file. Then Org also inserts a link to the remote file, thanks to Emacs Tramp. Org constructs the remote path to the file name from ‘dir’ and default-directory, as illustrated here:

1
[[file:/scp:dand@yakuba.princeton.edu:/home/dand/plot.png][plot.png]]

When ‘dir’ is used with ‘session’, Org sets the starting directory for a new session. But Org does not alter the directory of an already existing session.

Do not use ‘dir’ with ‘:exports results’ or with ‘:exports both’ to avoid Org inserting incorrect links to remote files. That is because Org does not expand default directory to avoid some underlying portability issues.

4.Inserting headers and footers

The ‘prologue’ header argument is for appending to the top of the code block for execution, like a reset instruction. For example, you may use ‘:prologue “reset”’ in a Gnuplot code block or, for every such block:

1
2
(add-to-list 'org-babel-default-header-args:gnuplot
'((:prologue . "reset")))

Likewise, the value of the ‘epilogue’ header argument is for appending to the end of the code block for execution.

14.4 Evaluating Code Blocks

A note about security: With code evaluation comes the risk of harm. Org safeguards by prompting for user’s permission before executing any code in the source block. To customize this safeguard, or disable it, see Code Evaluation Security.

1.How to evaluate source code

Org captures the results of the code block evaluation and inserts them in the Org file, right after the code block. The insertion point is after a newline and the ‘RESULTS’ keyword. Org creates the ‘RESULTS’ keyword if one is not already there.

By default, Org enables only Emacs Lisp code blocks for execution. See Languages to enable other languages.

Org provides many ways to execute code blocks. C-c C-c or C-c C-v e with the point on a code block141 calls the org-babel-execute-src-block function, which executes the code in the block, collects the results, and inserts them in the buffer.

By calling a named code block142 from an Org mode buffer or a table. Org can call the named code blocks from the current Org mode buffer or from the “Library of Babel” (see Library of Babel).

The syntax for ‘CALL’ keyword is:

1
2
#+CALL: <name>(<arguments>)
#+CALL: <name>[<inside header arguments>](<arguments>) <end header arguments>

The syntax for inline named code blocks is:

1
2
... call_<name>(<arguments>) ...
... call_<name>[<inside header arguments>](<arguments>)[<end header arguments>] ...

When inline syntax is used, the result is wrapped based on the variable org-babel-inline-result-wrap, which by default is set to "=%s=" to produce verbatim text suitable for markup.

  1. This is the name of the code block (see Structure of Code Blocks) to be evaluated in the current document. If the block is located in another file, start ‘’ with the file name followed by a colon. For example, in order to execute a block named ‘clear-data’ in ‘file.org’, you can write the following:

    1
    2
    #+CALL: file.org:clear-data()
    #这一点太神奇了.
  2. Org passes arguments to the code block using standard function call syntax. For example, a ‘#+CALL:’ line that passes ‘4’ to a code block named ‘double’, which declares the header argument ‘:var n=2’, would be written as:

    #+CALL: double(n=4)

    Note how this function call syntax is different from the header argument syntax.

  3. Org passes inside header arguments to the named code block using the header argument syntax. Inside header arguments apply to code block evaluation. For example, ‘[:results output]’ collects results printed to stdout during code execution of that block. Note how this header argument syntax is different from the function call syntax.

  4. End header arguments affect the results returned by the code block. For example, ‘:results html’ wraps the results in a ‘#+BEGIN_EXPORT html’ block before inserting the results in the Org buffer.

2.Limit code block evaluation

The ‘eval’ header argument can limit evaluation of specific code blocks and ‘CALL’ keyword. It is useful for protection against evaluating untrusted code blocks by prompting for a confirmation.

  1. ‘never’ or ‘no’

    Org never evaluates the source code.

  2. ‘query’

    Org prompts the user for permission to evaluate the source code.

  3. ‘never-export’ or ‘no-export’

    Org does not evaluate the source code when exporting, yet the user can evaluate it interactively.

  4. ‘query-export’

    Org prompts the user for permission to evaluate the source code during export.

If ‘eval’ header argument is not set, then Org determines whether to evaluate the source code from the org-confirm-babel-evaluate variable (see Code Evaluation Security).

3.Cache results of evaluation

The ‘cache’ header argument is for caching results of evaluating code blocks. Caching results can avoid re-evaluating a code block that have not changed since the previous run. To benefit from the cache and avoid redundant evaluations, the source block must have a result already present in the buffer, and neither the header arguments—including the value of ‘var’ references—nor the text of the block itself has changed since the result was last computed. This feature greatly helps avoid long-running calculations. For some edge cases, however, the cached results may not be reliable.

The caching feature is best for when code blocks are pure functions, that is functions that return the same value for the same input arguments (see Environment of a Code Block), and that do not have side effects, and do not rely on external variables other than the input arguments. Functions that depend on a timer, file system objects, and random number generators are clearly unsuitable for caching.

A note of warning: when ‘cache’ is used in a session, caching may cause unexpected results.

When the caching mechanism tests for any source code changes, it does not expand Noweb style references (see Noweb Reference Syntax). For reasons why, see http://thread.gmane.org/gmane.emacs.orgmode/79046.

The ‘cache’ header argument can have one of two values: ‘yes’ or ‘no’.

1) ‘no’

Default. No caching of results; code block evaluated every time.

2) ‘yes’

Whether to run the code or return the cached results is determined by comparing the SHA1 hash value of the combined code block and arguments passed to it. This hash value is packed on the ‘#+RESULTS:’ line from previous evaluation. When hash values match, Org does not evaluate the code block. When hash values mismatch, Org evaluates the code block, inserts the results, recalculates the hash value, and updates ‘#+RESULTS:’ line.

In this example, both functions are cached. But ‘caller’ runs only if the result from ‘random’ has changed since the last run.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#+NAME: random
#+BEGIN_SRC R :cache yes
runif(1)
#+END_SRC

#+RESULTS[a2a72cd647ad44515fab62e144796432793d68e1]: random
0.4659510825295

#+NAME: caller
#+BEGIN_SRC emacs-lisp :var x=random :cache yes
x
#+END_SRC

#+RESULTS[bec9c8724e397d5df3b696502df3ed7892fc4f5f]: caller
0.254227238707244

4.Footnotes

The option org-babel-no-eval-on-ctrl-c-ctrl-c can be used to remove code evaluation from the C-c C-c key binding.

Actually, the constructs ‘call_()’ and ‘src_{}’ are not evaluated when they appear in a keyword (see In-buffer Settings).

14.5 Results of Evaluation

How Org handles results of a code block execution depends on many header arguments working together. The primary determinant, however, is the ‘results’ header argument. It accepts four classes of options. Each code block can take only one option per class:

1) collection

For how the results should be collected from the code block;

2) type

For which type of result the code block will return; affects how Org processes and inserts results in the Org buffer;

3) format

For the result; affects how Org processes and inserts results in the Org buffer;

4) handling

For processing results after evaluation of the code block;

1.Collection

Collection options specify the results. Choose one of the options; they are mutually exclusive.

  • ‘value’

    Default. Functional mode. Org gets the value by wrapping the code in a function definition in the language of the source block. That is why when using ‘:results value’, code should execute like a function and return a value. For languages like Python, an explicit return statement is mandatory when using ‘:results value’. Result is the value returned by the last statement in the code block.When evaluating the code block in a session (see Environment of a Code Block), Org passes the code to an interpreter running as an interactive Emacs inferior process. Org gets the value from the source code interpreter’s last statement output. Org has to use language-specific methods to obtain the value. For example, from the variable _ in Python and Ruby, and the value of .Last.value in R.

  • ‘output’

    Scripting mode. Org passes the code to an external process running the interpreter. Org returns the contents of the standard output stream as text results.

    When using a session, Org passes the code to the interpreter running as an interactive Emacs inferior process. Org concatenates any text output from the interpreter and returns the collection as a result.

    Note that this collection is not the same as that would be collected from stdout of a non-interactive interpreter running as an external process. Compare for example these two blocks:

    1
    2
    3
    4
    5
    6
    7
    8
    #+BEGIN_SRC python :results output
    print('hello')
    2
    print "bye"
    #+END_SRC
    #+RESULTS:
    : hello
    : bye

    In the above non-session mode, the “2” is not printed; so it does not appear in results.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    #+BEGIN_SRC python :results output :session
    print "hello"
    2
    print "bye"
    #+END_SRC
    #+RESULTS:
    : hello
    : 2
    : bye

    In the above session, the interactive interpreter receives and prints “2”. Results show that.

2. Type

Type tells what result types to expect from the execution of the code block. Choose one of the options; they are mutually exclusive. The default behavior is to automatically determine the result type.

  • ‘table’

  • ‘vector’

    Interpret the results as an Org table. If the result is a single value, create a table with one row and one column. Usage example: ‘:results value table’.
    In-between each table row or below the table headings, sometimes results have horizontal lines, which are also known as “hlines”. The ‘hlines’ argument with the default ‘no’ value strips such lines from the input table. For most code, this is desirable, or else those ‘hline’ symbols raise unbound variable errors. A ‘yes’ accepts such lines, as demonstrated in the following example.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    #+NAME: many-cols
    | a | b | c |
    |---+---+---|
    | d | e | f |
    |---+---+---|
    | g | h | i |
    #+NAME: no-hline
    #+BEGIN_SRC python :var tab=many-cols :hlines no
    return tab
    #+END_SRC
    #+RESULTS: no-hline
    | a | b | c |
    | d | e | f |
    | g | h | i |

    #+NAME: hlines
    #+BEGIN_SRC python :var tab=many-cols :hlines yes
    return tab
    #+END_SRC
    #+RESULTS: hlines
    | a | b | c |
    |---+---+---|
    | d | e | f |
    |---+---+---|
    | g | h | i |
  • ‘list’

    Interpret the results as an Org list. If the result is a single value, create a list of one element.

  • ‘scalar’

  • ‘verbatim’ [vɜ:’beɪtɪm]

    Interpret literally and insert as quoted text. Do not create a table. Usage example: ‘:results value verbatim’.

  • ‘file’

    Interpret as a filename. Save the results of execution of the code block to that file, then insert a link to it. You can control both the filename and the description associated to the link.Org first tries to generate the filename from the value of the ‘file’ header argument and the directory specified using the ‘output-dir’ header arguments. If ‘output-dir’ is not specified, Org assumes it is the current directory.

    1
    2
    3
    #+BEGIN_SRC asymptote :results value file :file circle.pdf :output-dir img/
    size(2cm); draw(unitcircle);
    #+END_SRC

    If ‘file’ is missing, Org generates the base name of the output file from the name of the code block, and its extension from the ‘file-ext’ header argument. In that case, both the name and the extension are mandatory143.

    1
    2
    3
    4
    5
    #+name: circle
    #+BEGIN_SRC asymptote :results value file :file-ext pdf
    size(2cm);
    draw(unitcircle);
    #+END_SRC

    The ‘file-desc’ header argument defines the description (see Link Format) for the link. If ‘file-desc’ has no value, Org uses the generated file name for both the “link” and “description” parts of the link.By default, Org assumes that a table written to a file has TAB-delimited output. You can choose a different separator with the ‘sep’ header argument.

3.Format

Format pertains to the type of the result returned by the code block. Choose one of the options; they are mutually exclusive. The default follows from the type specified above.

  • ‘code’

    Result enclosed in a code block. Useful for parsing. Usage example: ‘:results value code’.

  • ‘drawer’

    Result wrapped in a ‘RESULTS’ drawer. Useful for containing ‘raw’ or ‘org’ results for later scripting and automated processing. Usage example: ‘:results value drawer’.

  • ‘html’

    Results enclosed in a ‘BEGIN_EXPORT html’ block. Usage example: ‘:results value html’.

  • ‘latex’

    Results enclosed in a ‘BEGIN_EXPORT latex’ block. Usage example: ‘:results value latex’.

  • ‘link’

  • ‘graphics’

    Result is a link to the file specified in ‘:file’ header argument. However, unlike plain ‘:file’, nothing is written to the disk. The block is used for its side-effects only, as in the following example:

    1
    2
    3
    #+begin_src shell :results link :file "download.tar.gz"
    wget -c "http://example.com/download.tar.gz"
    #+end_src
  • ‘org’

    Results enclosed in a ‘BEGIN_SRC org’ block. For comma-escape, either TAB in the block, or export the file. Usage example: ‘:results value org’.

  • ‘pp’

    Result converted to pretty-print source code. Enclosed in a code block. Languages supported: Emacs Lisp, Python, and Ruby. Usage example: ‘:results value pp’.

  • ‘raw’

    Interpreted as raw Org mode. Inserted directly into the buffer. Aligned if it is a table. Usage example: ‘:results value raw’.

The ‘wrap’ header argument unconditionnally marks the results block by appending strings to ‘#+BEGIN_’ and ‘#+END_’. If no string is specified, Org wraps the results in a ‘#+BEGIN_results’ … ‘#+END_results’ block. It takes precedent over the ‘results’ value listed above. E.g.,

1
2
3
4
5
6
7
8
#+BEGIN_SRC emacs-lisp :results html :wrap EXPORT markdown
"<blink>Welcome back to the 90's</blink>"
#+END_SRC

#+RESULTS:
#+BEGIN_EXPORT markdown
<blink>Welcome back to the 90's</blink>
#+END_EXPORT

4.Handling

Handling options after collecting the results.

  • ‘silent’

    Do not insert results in the Org mode buffer, but echo them in the minibuffer. Usage example: ‘:results output silent’.

  • ‘replace’

    Default. Insert results in the Org buffer. Remove previous results. Usage example: ‘:results output replace’.

  • ‘append’

    Append results to the Org buffer. Latest results are at the bottom. Does not remove previous results. Usage example: ‘:results output append’.

  • ‘prepend’

    Prepend results to the Org buffer. Latest results are at the top. Does not remove previous results. Usage example: ‘:results output prepend’.

5.Post-processing

The ‘post’ header argument is for post-processing results from block evaluation. When ‘post’ has any value, Org binds the results to *this* variable for easy passing to ‘var’ header argument specifications (see Environment of a Code Block). That makes results available to other code blocks, or even for direct Emacs Lisp code execution.

The following two examples illustrate ‘post’ header argument in action. The first one shows how to attach an ‘ATTR_LATEX’ keyword using ‘post’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#+NAME: attr_wrap
#+BEGIN_SRC sh :var data="" :var width="\\textwidth" :results output
echo "#+ATTR_LATEX: :width $width"
echo "$data"
#+END_SRC

#+HEADER: :file /tmp/it.png
#+BEGIN_SRC dot :post attr_wrap(width="5cm", data=*this*) :results drawer
digraph{
a -> b;
b -> c;
c -> a;
}
#+end_src

#+RESULTS:
:RESULTS:
#+ATTR_LATEX :width 5cm
[[file:/tmp/it.png]]
:END:

The second example shows use of ‘colnames’ header argument in ‘post’ to pass data between code blocks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#+NAME: round-tbl
#+BEGIN_SRC emacs-lisp :var tbl="" fmt="%.3f"
(mapcar (lambda (row)
(mapcar (lambda (cell)
(if (numberp cell)
(format fmt cell)
cell))
row))
tbl)
#+end_src

#+BEGIN_SRC R :colnames yes :post round-tbl[:colnames yes](*this*)
set.seed(42)
data.frame(foo=rnorm(1))
#+END_SRC

#+RESULTS:
| foo |
|-------|
| 1.371 |

Footnotes

Due to the way this header argument is implemented, it implies “:results file”. Therefore if it is set for multiple blocks at once (by a subtree or buffer property for example), all blocks are forced to produce file results. This is seldom desired behavior, so it is recommended to set this header only on a per-block basis. It is possible that this aspect of the implementation might change in the future.

14.6 Exporting Code Blocks

It is possible to export the code of code blocks, the results of code block evaluation, both the code and the results of code block evaluation, or none. Org defaults to exporting code for most languages. For some languages, such as ditaa, Org defaults to results. To export just the body of code blocks, see Literal Examples. To selectively export sub-trees of an Org document, see Exporting.

The ‘exports’ header argument is to specify if that part of the Org file is exported to, say, HTML or LaTeX formats.

  • ‘code’

    The default. The body of code is included into the exported file. Example: ‘:exports code’.

  • ‘results’

    The results of evaluation of the code is included in the exported file. Example: ‘:exports results’.

  • ‘both’

    Both the code and results of evaluation are included in the exported file. Example: ‘:exports both’.

  • ‘none’

    Neither the code nor the results of evaluation is included in the exported file. Whether the code is evaluated at all depends on other options. Example: ‘:exports none’.

To stop Org from evaluating code blocks to speed exports, use the header argument ‘:eval never-export’ (see Evaluating Code Blocks). To stop Org from evaluating code blocks for greater security, set the org-export-use-babel variable to nil, but understand that header arguments will have no effect.

Turning off evaluation comes in handy when batch processing. For example, markup languages for wikis, which have a high risk of untrusted code. Stopping code block evaluation also stops evaluation of all header arguments of the code block. This may not be desirable in some circumstances. So during export, to allow evaluation of just the header arguments but not any code evaluation in the source block, set ‘:eval never-export’ (see Evaluating Code Blocks).

Org never evaluates code blocks in commented sub-trees when exporting (see Comment Lines). On the other hand, Org does evaluate code blocks in sub-trees excluded from export (see Export Settings).

14.7 Extracting Source Code

Extracting source code from code blocks is a basic task in literate programming. Org has features to make this easy. In literate programming parlance, documents on creation are woven with code and documentation, and on export, the code is tangled for execution by a computer. Org facilitates weaving and tangling for producing, maintaining, sharing, and exporting literate programming documents. Org provides extensive customization options for extracting source code.

When Org tangles code blocks, it expands, merges, and transforms them. Then Org recomposes them into one or more separate files, as configured through the options. During this tangling process, Org expands variables in the source code, and resolves any Noweb style references (see Noweb Reference Syntax).

1.Header arguments

The ‘tangle’ header argument specifies if the code block is exported to source file(s).

  • ‘yes’

    Export the code block to source file. The file name for the source file is derived from the name of the Org file, and the file extension is derived from the source code language identifier. Example: ‘:tangle yes’.

  • ‘no’

    The default. Do not extract the code in a source code file. Example: ‘:tangle no’.

  • FILENAME

    Export the code block to source file whose file name is derived from any string passed to the ‘tangle’ header argument. Org derives the file name as being relative to the directory of the Org file’s location. Example: ‘:tangle FILENAME’.

The ‘mkdirp’ header argument creates parent directories for tangled files if the directory does not exist. ‘yes’ enables directory creation and ‘no’ inhibits directory creation.

The ‘comments’ header argument controls inserting comments into tangled files. These are above and beyond whatever comments may already exist in the code block.

  • ‘no’

    The default. Do not insert any extra comments during tangling.

  • ‘link’

    Wrap the code block in comments. Include links pointing back to the place in the Org file from where the code was tangled.

  • ‘yes’

    Kept for backward compatibility; same as ‘link’.

  • ‘org’

    Nearest headline text from Org file is inserted as comment. The exact text that is inserted is picked from the leading context of the source block.

  • ‘both’

    Includes both ‘link’ and ‘org’ options.

  • ‘noweb’

    Includes ‘link’ option, expands Noweb references (see Noweb Reference Syntax), and wraps them in link comments inside the body of the code block.

The ‘padline’ header argument controls insertion of newlines to pad source code in the tangled file.

  • ‘yes’

    Default. Insert a newline before and after each code block in the tangled file.

  • ‘no’

    Do not insert newlines to pad the tangled code blocks.

The ‘shebang’ header argument can turn results into executable script files. By setting it to a string value—for example, ‘:shebang “#!/bin/bash”’—Org inserts that string as the first line of the tangled file that the code block is extracted to. Org then turns on the tangled file’s executable permission.

The ‘tangle-mode’ header argument specifies what permissions to set for tangled files by set-file-modes. For example, to make a read-only tangled file, use ‘:tangle-mode (identity #o444)’. To make it executable, use ‘:tangle-mode (identity #o755)’. It also overrides executable permission granted by ‘shebang’. When multiple source code blocks tangle to a single file with different and conflicting ‘tangle-mode’ header arguments, Org’s behavior is undefined.

By default Org expands code blocks during tangling. The ‘no-expand’ header argument turns off such expansions. Note that one side-effect of expansion by org-babel-expand-src-block also assigns values (see Environment of a Code Block) to variables. Expansions also replace Noweb references with their targets (see Noweb Reference Syntax). Some of these expansions may cause premature assignment, hence this option. This option makes a difference only for tangling. It has no effect when exporting since code blocks for execution have to be expanded anyway.

2.Functions

  • org-babel-tangle

    Tangle the current file. Bound to C-c C-v t.With prefix argument only tangle the current code block.

  • org-babel-tangle-file

    Choose a file to tangle. Bound to C-c C-v f.

3.Hooks

  • org-babel-post-tangle-hook

    This hook is run from within code files tangled by org-babel-tangle, making it suitable for post-processing, compilation, and evaluation of code in the tangled files.

4.Jumping between code and Org

Debuggers normally link errors and messages back to the source code. But for tangled files, we want to link back to the Org file, not to the tangled source file. To make this extra jump, Org uses org-babel-tangle-jump-to-org function with two additional source code block header arguments:

  1. Set ‘padline’ to true—this is the default setting.
  2. Set ‘comments’ to ‘link’, which makes Org insert links to the Org file.

14.8 Languages

Code blocks in the following languages are supported.

Language Identifier Language Identifier
Asymptote ‘asymptote’ Lua ‘lua’
Awk ‘awk’ MATLAB ‘matlab’
C ‘C’ Mscgen ‘mscgen’
C++ ‘C++’144 OCaml ‘ocaml’
Clojure ‘clojure’ Octave ‘octave’
CSS ‘css’ Org mode ‘org’
D ‘D’145 Oz ‘oz’
ditaa ‘ditaa’ Perl ‘perl’
Emacs Calc ‘calc’ Plantuml ‘plantuml’
Emacs Lisp ‘emacs-lisp’ Processing.js ‘processing’
Fortran ‘fortran’ Python ‘python’
Gnuplot ‘gnuplot’ R ‘R’
GNU Screen ‘screen’ Ruby ‘ruby’
Graphviz ‘dot’ Sass ‘sass’
Haskell ‘haskell’ Scheme ‘scheme’
Java ‘java’ Sed ‘sed’
Javascript ‘js’ shell ‘sh’
LaTeX ‘latex’ SQL ‘sql’
Ledger ‘ledger’ SQLite ‘sqlite’
Lilypond ‘lilypond’ Vala ‘vala’
Lisp ‘lisp’

Additional documentation for some languages is at https://orgmode.org/worg/org-contrib/babel/languages.html.

By default, only Emacs Lisp is enabled for evaluation. To enable or disable other languages, customize the org-babel-load-languages variable either through the Emacs customization interface, or by adding code to the init file as shown next.

In this example, evaluation is disabled for Emacs Lisp, and enabled for R.

1
2
3
4
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . nil)
(R . t)))

Note that this is not the only way to enable a language. Org also enables languages when loaded with require statement. For example, the following enables execution of Clojure code blocks:

1
(require 'ob-clojure)

14.9 Editing Source Code

Use C-c ‘ to edit the current code block. It opens a new major-mode edit buffer containing the body of the source code block, ready for any edits. Use C-c ‘ again to close the buffer and return to the Org buffer.

C-x C-s saves the buffer and updates the contents of the Org buffer. Set org-edit-src-auto-save-idle-delay to save the base buffer after a certain idle delay time. Set org-edit-src-turn-on-auto-save to auto-save this buffer into a separate file using Auto-save mode.

While editing the source code in the major mode, the Org Src minor mode remains active. It provides these customization variables as described below. For even more variables, look in the customization group org-edit-structure.

  • org-src-lang-modes

    If an Emacs major-mode named <LANG>-mode exists, where is the language identifier from code block’s header line, then the edit buffer uses that major mode. Use this variable to arbitrarily map language identifiers to major modes.

  • org-src-window-setup

    For specifying Emacs window arrangement when the new edit buffer is created.

  • org-src-preserve-indentation

    Default is nil. Source code is indented. This indentation applies during export or tangling, and depending on the context, may alter leading spaces and tabs. When non-nil, source code is aligned with the leftmost column. No lines are modified during export or tangling, which is very useful for white-space sensitive languages, such as Python.

  • org-src-ask-before-returning-to-edit-buffer

    When nil, Org returns to the edit buffer without further prompts. The default prompts for a confirmation.

Set org-src-fontify-natively to non-nil to turn on native code fontification in the Org buffer. Fontification of code blocks can give visual separation of text and code on the display page. To further customize the appearance of org-block for specific languages, customize org-src-block-faces. The following example shades the background of regular blocks, and colors source blocks only for Python and Emacs Lisp languages.

1
2
3
4
5
6
7
(require 'color)
(set-face-attribute 'org-block nil :background
(color-darken-name
(face-attribute 'default :background) 3))

(setq org-src-block-faces '(("emacs-lisp" (:background "#EEE2FF"))
("python" (:background "#E5FFB8"))))

14.10 Noweb Reference Syntax

Org supports named blocks in Noweb146 style syntax:

1
<<CODE-BLOCK-ID>>

Org can replace the construct with the source code, or the results of evaluation, of the code block identified as CODE-BLOCK-ID.

The ‘noweb’ header argument controls expansion of Noweb syntax references. Expansions occur when source code blocks are evaluated, tangled, or exported.

  • ‘no’

    Default. No expansion of Noweb syntax references in the body of the code when evaluating, tangling, or exporting.

  • ‘yes’

    Expansion of Noweb syntax references in the body of the code block when evaluating, tangling, or exporting.

  • ‘tangle’

    Expansion of Noweb syntax references in the body of the code block when tangling. No expansion when evaluating or exporting.

  • ‘no-export’

    Expansion of Noweb syntax references in the body of the code block when evaluating or tangling. No expansion when exporting.

  • ‘strip-export’

    Expansion of Noweb syntax references in the body of the code block when expanding prior to evaluating or tangling. Removes Noweb syntax references when exporting.

  • ‘eval’

    Expansion of Noweb syntax references in the body of the code block only before evaluating.

In the following example,

1
2
3
4
5
6
7
8
9
#+NAME: initialization
#+BEGIN_SRC emacs-lisp
(setq sentence "Never a foot too far, even.")
#+END_SRC

#+BEGIN_SRC emacs-lisp :noweb yes
<<initialization>>
(reverse sentence)
#+END_SRC

the second code block is expanded as

1
2
3
4
#+BEGIN_SRC emacs-lisp :noweb yes
(setq sentence "Never a foot too far, even.")
(reverse sentence)
#+END_SRC

Noweb insertions honor prefix characters that appear before the Noweb syntax reference. This behavior is illustrated in the following example. Because the ‘<>’ Noweb reference appears behind the SQL comment syntax, each line of the expanded Noweb reference is commented. With:

1
2
3
4
5
#+NAME: example
#+BEGIN_SRC text
this is the
multi-line body of example
#+END_SRC

this code block:

1
2
3
#+BEGIN_SRC sql :noweb yes
---<<example>>
#+END_SRC

expands to:

1
2
3
4
#+BEGIN_SRC sql :noweb yes
---this is the
---multi-line body of example
#+END_SRC

Since this change does not affect Noweb replacement text without newlines in them, inline Noweb references are acceptable.

This feature can also be used for management of indentation in exported code snippets. With:

1
2
3
4
5
6
7
8
9
#+NAME: if-true
#+BEGIN_SRC python :exports none
print('do things when true')
#+end_src

#+name: if-false
#+begin_src python :exports none
print('do things when false')
#+end_src

this code block:

1
2
3
4
5
6
#+begin_src python :noweb yes :results output
if true:
<<if-true>>
else:
<<if-false>>
#+end_src

expands to:

1
2
3
4
if true:
print('do things when true')
else:
print('do things when false')

When expanding Noweb style references, Org concatenates code blocks by matching the reference name to either the code block name or, if none is found, to the ‘noweb-ref’ header argument.

For simple concatenation, set this ‘noweb-ref’ header argument at the sub-tree or file level. In the example Org file shown next, the body of the source code in each block is extracted for concatenation to a pure code file when tangled.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#+BEGIN_SRC sh :tangle yes :noweb yes :shebang #!/bin/sh
<<fullest-disk>>
#+END_SRC
- the mount point of the fullest disk
:PROPERTIES:
:header-args: :noweb-ref fullest-disk
:END:

- query all mounted disks
#+BEGIN_SRC sh
df \
#+END_SRC

- strip the header row
#+BEGIN_SRC sh
|sed '1d' \
#+END_SRC

- output mount point of fullest disk
#+BEGIN_SRC sh
|awk '{if (u < +$5) {u = +$5; m = $6}} END {print m}'
#+END_SRC

By default a newline separates each noweb reference concatenation. To change this newline separator, edit the ‘noweb-sep’ header argument.

Eventually, Org can include the results of a code block rather than its body. To that effect, append parentheses, possibly including arguments, to the code block name, as shown below.

1
<<code-block-name(optional arguments)>>

Note that when using the above approach to a code block’s results, the code block name set by ‘NAME’ keyword is required; the reference set by ‘noweb-ref’ does not work in that case.

Here is an example that demonstrates how the exported content changes when Noweb style references are used with parentheses versus without. With:

1
2
3
4
#+NAME: some-code
#+BEGIN_SRC python :var num=0 :results output :exports none
print(num*10)
#+END_SRC

this code block:

1
2
3
#+BEGIN_SRC text :noweb yes
<<some-code>>
#+END_SRC

expands to:

1
print(num*10)

Below, a similar Noweb style reference is used, but with parentheses, while setting a variable ‘num’ to 10:

1
2
3
#+BEGIN_SRC text :noweb yes
<<some-code(num=10)>>
#+END_SRC

Note that now the expansion contains the results of the code block ‘some-code’, not the code block itself:

1
100

For Noweb literate programming details, see http://www.cs.tufts.edu/~nr/noweb/.

14.11 Library of Babel

The “Library of Babel” is a collection of code blocks. Like a function library, these code blocks can be called from other Org files. A collection of useful code blocks is available on Worg. For remote code block evaluation syntax, see Evaluating Code Blocks.

For any user to add code to the library, first save the code in regular code blocks of an Org file, and then load the Org file withorg-babel-lob-ingest, which is bound to C-c C-v i.

14.12 Key bindings and Useful Functions

Many common Org mode key sequences are re-bound depending on the context.

Active key bindings in code blocks:

Key binding Function
C-c C-c org-babel-execute-src-block
C-c C-o org-babel-open-src-block-result
M-UP org-babel-load-in-session
M-DOWN org-babel-pop-to-session

Active key bindings in Org mode buffer:

Key binding Function
C-c C-v p or C-c C-v C-p org-babel-previous-src-block
C-c C-v n or C-c C-v C-n org-babel-next-src-block
C-c C-v e or C-c C-v C-e org-babel-execute-maybe
C-c C-v o or C-c C-v C-o org-babel-open-src-block-result
C-c C-v v or C-c C-v C-v org-babel-expand-src-block
C-c C-v u or C-c C-v C-u org-babel-goto-src-block-head
C-c C-v g or C-c C-v C-g org-babel-goto-named-src-block
C-c C-v r or C-c C-v C-r org-babel-goto-named-result
C-c C-v b or C-c C-v C-b org-babel-execute-buffer
C-c C-v s or C-c C-v C-s org-babel-execute-subtree
C-c C-v d or C-c C-v C-d org-babel-demarcate-block
C-c C-v t or C-c C-v C-t org-babel-tangle
C-c C-v f or C-c C-v C-f org-babel-tangle-file
C-c C-v c or C-c C-v C-c org-babel-check-src-block
C-c C-v j or C-c C-v C-j org-babel-insert-header-arg
C-c C-v l or C-c C-v C-l org-babel-load-in-session
C-c C-v i or C-c C-v C-i org-babel-lob-ingest
C-c C-v I or C-c C-v C-I org-babel-view-src-block-info
C-c C-v z or C-c C-v C-z org-babel-switch-to-session-with-code
C-c C-v a or C-c C-v C-a org-babel-sha1-hash
C-c C-v h or C-c C-v C-h org-babel-describe-bindings
C-c C-v x or C-c C-v C-x org-babel-do-key-sequence-in-edit-buffer

14.13 Batch Execution

Org mode features, including working with source code facilities can be invoked from the command line. This enables building shell scripts for batch processing, running automated system tasks, and expanding Org mode’s usefulness.

The sample script shows batch processing of multiple files using org-babel-tangle.

1
2
3
4
5
6
7
8
9
10
#!/bin/sh
## Tangle files with Org mode
#
emacs -Q --batch --eval "
(progn
(require 'ob-tangle)
(dolist (file command-line-args-left)
(with-current-buffer (find-file-noselect file)
(org-babel-tangle))))
" "$@"