GNU Emacs
Org
Working with Source Code

Working with Source Code

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 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:

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

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.

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

Features Overview

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 the "liveliness" of each source code block by tweaking the header arguments (see Using Header Arguments) for compiling, execution, extraction, and exporting.

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 backends 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.

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:

#+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:

src_<language>{<body>}

or

src_<language>[<header arguments>]{<body>}
#+NAME: <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. Inline code blocks cannot have a name.
#+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.
<language>

Optional. It is the identifier of the source code language in the block. See Languages, for identifiers of supported languages.

When <language> identifier is omitted, the block also cannot have <switches> and <header arguments>. Otherwise, the first switch/argument will be treated as <language>.

Language identifier is also used to fontify code blocks in Org buffers, when org-src-fontify-natively is set to non-nil. See Editing Source Code.

<switches>

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

<header arguments>

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 subtrees of the Org document.

<body>
Source code in the dialect of the specified language identifier.

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.

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:

:session    => "none"
:results    => "replace"
:exports    => "code"
:cache      => "no"
:noweb      => "no"
:hlines     => "no"
:tangle     => "no"

Inline source blocks (see Structure of Code Blocks) use slightly different default header arguments defined in org-babel-default-inline-header-args:

:session    => "none"
:results    => "replace"
:exports    => "results"
:hlines     => "yes"

The most notable difference between default header arguments for inline and normal source blocks is :exports argument. For inline source blocks, results of evaluation are exported by default; not the code.

Unlike the default values, header arguments set using Org mode properties (see Header arguments in Org mode properties) do apply to both the normal source blocks and inline source blocks.

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

(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 <LANG> is the name of the language. For details, see the language-specific online documentation at https://orgmode.org/worg/org-contrib/babel/.

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.

#+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 subtree 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 subtree.

* 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:<LANG> where <LANG> is the language identifier. For example,

* 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.

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.

#+NAME: factorial
#+BEGIN_SRC haskell :results silent :exports code :var n=0
  fac 0 = 1
  fac n = n * fac (n-1)
#+END_SRC

The same header arguments in an inline code block:

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:

#+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:

#+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.

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

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

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

Environment of a Code Block

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.

: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. ASSIGN may specify a filename for references to elements in a different file, using a : to separate the filename from the reference.

:var NAME=FILE:REFERENCE

When FILE does not exist, the reference is searched in the current file, using the verbatim reference. This way, :var table=tbl:example will be searched inside the current buffer.

Here are examples of passing values by reference:

table

A table named with a NAME keyword.

#+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
: 4

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 non-hline 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.

#+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.

#+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 |

To refer to a table in another file, join the filename and table name with a colon, for example: :var table=other-file.org:example-table.

list

A simple named list.

#+NAME: example-list
- simple
  - not
  - nested
- list

#+BEGIN_SRC emacs-lisp :var x=example-list
  (print x)
#+END_SRC

#+RESULTS:
| simple | list |

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

code block without arguments

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

#+BEGIN_SRC emacs-lisp :var length=table-length()
  (* 2 length)
#+END_SRC

#+RESULTS:
: 8
code block with arguments

A code block name, as assigned by NAME keyword, followed by parentheses and optional arguments passed within the parentheses. The block is evaluated with point at its location.

#+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
literal example, or code block contents

A code block or literal example block named with a NAME keyword, followed by brackets (optional for example blocks).

#+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:

#+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.

#+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.

#+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.

#+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.

#+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.

#+NAME: table
| (a b c) |

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

#+RESULTS:
: (a b c)

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.

none
Default. Each code block gets a new interpreter process to execute. The process terminates once the block is evaluated.
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.

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 DIRECTORY temporarily has the same effect as changing the current directory with M-x cd RET DIRECTORY, and then not setting dir. Under the surface, dir simply sets the value of the Emacs variable default-directory. Setting mkdirp header argument to a non-nil value creates the directory, if necessary.

Setting dir to the symbol attach or the string "'attach" will set dir to the directory returned by (org-attach-dir), set :mkdirp yes, and insert any file paths, as when using :results file, which are under the node's attachment directory using attachment: links instead of the usual file: links. Any returned path outside the attachment directory will use file: links as per usual.

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

#+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:

#+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:

[[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.

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:

(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.

Evaluating Code Blocks

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

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. More details in Results of Evaluation.

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 block(note: 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.) 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 block49 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:

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

The syntax for inline named code blocks is:

... 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.

<name>

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 <name> 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:

#+CALL: file.org:clear-data()
<arguments>

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.

<inside header arguments>
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.
<end header arguments>
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.

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.

yes
Org evaluates the source code, possibly asking permission according to org-confirm-babel-evaluate.
never or no
Org never evaluates the source code.
query
Org prompts the user for permission to evaluate the source code.
never-export or no-export
Org does not evaluate the source code when exporting, yet the user can evaluate it interactively.
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 and Security Issues).

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).

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

no
Default. No caching of results; code block evaluated every time.
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.

#+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

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:

Collection
For how the results should be collected from the code block;
Type
For which type of result the code block will return; affects how Org processes and inserts results in the Org buffer;
Format
For the result; affects how Org processes results;
Handling
For inserting results once they are properly formatted.

Collection

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

value

Default for most Babel libraries49. 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 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.

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. The result type detection depends on the code block language, as described in the documentation for individual languages. See Languages.

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.

#+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
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.

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

If file header argument 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 mandatory.

Result can also be interpreted as path to file. See :results link.

#+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 is present but has no value, the file value is used as the link description. When this argument is not present, the description is omitted. If you want to provide the file-desc argument but omit the description, you can provide it with an empty vector (i.e., :file-desc []).

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.

The file-mode header argument defines the file permissions. To make it executable, use :file-mode (identity #o755).

#+BEGIN_SRC shell :results file :file script.sh :file-mode (identity #o755)
  echo "#!/bin/bash"
  echo "echo Hello World"
#+END_SRC

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.

raw
Interpreted as raw Org mode. Inserted directly into the buffer. Aligned if it is a table. Usage example: :results value raw.
code
Result enclosed in a code block. Useful for parsing. Usage example: :results value code.
drawer
Results are added directly to the Org file as with raw, but are wrapped in a RESULTS drawer or results macro (for inline code blocks), 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

When used along with file type, the result is a link to the file specified in :file header argument. However, unlike plain file type, code block output is not written to the disk. The block is expected to generate the file by its side effects only, as in the following example:

#+begin_src shell :results file link :file "org-mode-unicorn.svg"
  wget -c "https://orgmode.org/resources/img/org-mode-unicorn.svg"
#+end_src

#+RESULTS:
[[file:org-mode-unicorn.svg]]

If :file header argument is omitted, interpret source block result as the file path.

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.

The wrap header argument unconditionally marks the results block by appending strings to #+BEGIN_ and #+END_, except if the value is nil or no. 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.,

#+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

Handling

Handling options after collecting the results. Choose one of the options; they are mutually exclusive.

replace
Default. Insert results in the Org buffer. Remove previous results. Usage example: :results output replace.
silent
Do not insert results in the Org mode buffer, but echo them in the minibuffer. Usage example: :results output silent.
none
Compute results, but do not do anything with them. No inserting in the Org mode buffer nor echo them in the minibuffer. The results can still be used when referenced from another code block. Usage example: :results none.
discard
Ignore the results completely. This option is similar to none, but no processing is performed on the return value. Calling the code block programmatically (see How to evaluate source code) or by reference (see Passing arguments and Noweb Reference Syntax) will always yield nil.
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.

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.

#+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.

#+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 |

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 and results for inline code blocks. For some languages, such as ditaa, Org defaults to results both in ordinary source blocks and in inline source blocks. To export just the body of code blocks, see Literal Examples. To selectively export subtrees of an Org document, see Exporting.

The exports header argument specifies whether 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 are 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 are included in the exported file. Whether the code is evaluated at all depends on other options. Example: :exports none.

If a source block is named using the NAME keyword, the same name will be assigned to the results of evaluation. This way, fuzzy links pointing to the named source blocks exported using :exports results will remain valid and point to the results of evaluation.

Results of evaluation of a named block can also be explicitly named using a separate NAME keyword. The name value set via the NAME keyword will be preferred over the parent source block.

#+NAME: code name
#+BEGIN_SRC emacs-lisp :exports both value
(+ 1 2)
#+END_SRC

#+NAME: results name
#+RESULTS: code name
3

This [[#code-name][link]] will point to the code block.
Another [[#results-name][link]] will point to the results.

Explicit setting of the result name may be necessary when a named code block is exported using :exports both. Links to such a block may point arbitrarily either to the code block or to its results when the results do not have a distinct name.

Note that all the links pointing to a source block exported using :exports none will be broken. This will cause the export process to fail, unless broken links are allowed during export (see Export Settings).

You can prevent Org from evaluating code blocks for speed or security reasons:

  • To speed up export, use the header argument :eval never-export (see Evaluating Code Blocks).
  • For greater security, set the org-export-use-babel variable to nil, but understand that header arguments will have no effect in this case.

If results of evaluation are not marked for export (:exports code or :exports none), Org will not evaluate them, even for :eval yes. The only exception is when a code block uses :session - such blocks are evaluated according to their :eval header argument.

Turning off evaluation comes in handy when batch processing. For example, markup languages for wikis 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 subtrees when exporting (see Comment Lines). On the other hand, Org does evaluate code blocks in subtrees excluded from export (see Export Settings).

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).

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.

Additionally, code blocks inside commented subtrees (see Comment Lines) are never exported.

The mkdirp header argument creates parent directories for tangled files if the directory does not exist. A yes value enables directory creation whereas no inhibits it.

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.

Do note that Org will use org-store-link (Handling Links) to store link to code block. Such link may not be unique if the parent heading title is a duplicate of earlier heading or changes after tangling. We recommend setting org-id-link-to-org-use-id to t to make sure that the link points to the correct heading.

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. Permissions are given by an octal value, which can be provided calling the identity function on an elisp octal value. For instance, to create a read-only file one may use :tangle-mode (identity #o444). To reduce the verbosity required, a octal shorthand is defined, oXXX (o for octal). Using this, our read-only example is :tangle-mode o444. Omitting the o prefix will cause the argument to be interpreted as an integer, which can lead to unexpected results (444 is the same as o674). Two other shorthands are recognized, ls-style strings like rw-r--r--, and chmod-style permissions like g+w. Note that chmod-style permissions are based on org-babel-tangle-default-file-mode, which is #o644 by default.

When :tangle-mode and :shebang are both specified, the give :tangle-mode will override the permissions from :shebang. When multiple source code blocks tangle to a single file with 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.

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.

Tangle hooks

org-babel-pre-tangle-hook

This hook is run before the tangle process begins. The active buffer is buffer to be tangled.

org-babel-tangle-body-hook

This hook is run from a temporary buffer containing expanded code of every tangled code block. The hook can modify the expanded code as needed. The contents of the current buffer will be used as actual code block expansion.

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.

org-babel-tangle-finished-hook

This hook is run after post-tangle hooks, in the original buffer.

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.

Languages

Code blocks in dozens of languages are supported. See Worg website for language-specific documentation.

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.

(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:

(require 'ob-clojure)

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 <LANG> is the language identifier from code block's header line, then the edit buffer uses that major mode. If the major mode does not exist, or the language identifier is omitted, then the edit buffer falls back to Fundamental 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.

Fontification of code blocks can give visual separation of text and code on the display page. Set org-src-fontify-natively to non-nil to turn on native code fontification in the Org buffer. The fontification follows the major mode used to edit the code block (see org-src-lang-modes above).

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.

(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"))))

Noweb Reference Syntax

Source code blocks can include references to other source code blocks, using a noweb(note: For noweb literate programming details, see https://www.cs.tufts.edu/~nr/noweb/.) style syntax:


where CODE-BLOCK-ID refers to either the NAME of a single source code block, or a collection of one or more source code blocks sharing the same noweb-ref header argument (see Using Header Arguments). Org can replace such references with the source code of the block or blocks being referenced, or, in the case of a single source code block named with NAME, with the results of an evaluation of that block.

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.
strip-tangle
Expansion of noweb syntax references in the body of the code block when evaluating or exporting. Removes noweb syntax references when 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 most simple case, the contents of a single source block is inserted within other blocks. Thus, in following example,

#+NAME: initialization
#+BEGIN_SRC emacs-lisp
  (setq sentence "Never a foot too far, even.")
#+END_SRC

#+BEGIN_SRC emacs-lisp :noweb yes
#+html: <span id="initialization"></span>
  
  (reverse sentence)
#+END_SRC

the second code block is expanded as

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

Note that noweb expansion does not automatically carry over :var

header arguments50.

You may also include the contents of multiple blocks sharing a common noweb-ref header argument, which can be set at the file, subtree, or code block 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.

#+BEGIN_SRC sh :tangle yes :noweb yes :shebang #!/bin/sh
#+html: <span id="fullest-disk"></span>
  
#+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 use a different separator, edit the noweb-sep header argument.

Alternatively, Org can include the results of evaluation of a single code block rather than its body [(note: The reference is evaluated with point at the referenced block, using its header arguments (including inherited)). Evaluation occurs when parentheses, possibly including arguments, are appended to the code block name, as shown below.

<<NAME(optional arguments)>>

Note that in this case, a code block name set by NAME keyword is required; the reference set by noweb-ref will not work when evaluation is desired.

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

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

this code block:

#+BEGIN_SRC text :noweb yes
#+html: <span id="some-code"></span>
  
#+END_SRC

expands to:

print(num*10)

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

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

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

100

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:

#+NAME: example
#+BEGIN_SRC text
  this is the
  multi-line body of example
#+END_SRC

this code block:

#+BEGIN_SRC sql :noweb yes
#+html: <span id="example"></span>
 ---
#+END_SRC

expands to:

#+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:

#+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:

#+begin_src python :noweb yes :results output
if true:
#+html: <span id="if-true"></span>
    
else:
#+html: <span id="if-false"></span>
    
#+end_src

expands to:

if true:
    print('do things when true')
else:
    print('do things when false')

This prefix behavior can be turned off in a block by setting the noweb-prefix header argument to no, as in:

#+BEGIN_SRC elisp :noweb-prefix no
#+html: <span id="example"></span>
  (setq example-data "")
#+END_SRC

which expands to:

(setq example-data "this is the
multi-line body of example")

When in doubt about the outcome of a source code block expansion, you can preview the results with the following command:

C-c C-v v or C-c C-v C-v (org-babel-expand-src-block)

Expand the current source code block according to its header arguments and pop open the results in a preview buffer.

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 with org-babel-lob-ingest, which is bound to C-c C-v i.

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

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.

#!/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))))
  " "$@"

Footnotes

  1. 49

    Actually, the constructs call_<name>() and src_<lang>{} are not evaluated when they appear in a keyword (see Summary of In-Buffer Settings).

    Backrefs: 1 2

  2. 50

    In the following example, attempting to evaluate the second code block will give an error, because the variables defined in the first code block will not be defined in the second block.

    #+NAME: get-prompt
    #+BEGIN_SRC emacs-lisp :var prompt="root> " :var command="ls"
      (concat prompt command)
    #+END_SRC
    
    #+RESULTS: get-prompt
    : root> ls
    
    #+BEGIN_SRC emacs-lisp :noweb yes
      <<get-prompt>>
    #+END_SRC
    

    The previous block is expanded without setting prompt and command values.

    #+BEGIN_SRC emacs-lisp
      (concat prompt command)
    #+END_SRC
    

    Backrefs: 1

Manual
Org Mode 9.8.5
Source
View upstream