Working with Source Code (Babel)
Org can hold source code as well as prose, and it can do more with that code than display it. It can run a block and write the result back into the document, pass data from a table into a program and from one program into another, extract the code into ordinary source files, and decide what appears when the document is exported. The machinery behind all of this is called Babel (Org Babel), after its ability to mix many programming languages in one file.
This chapter starts with the shape of a code block and the three things Org can do with it. It then covers evaluation and results, header arguments and where they come from, passing data between blocks, sessions and caching, export, tangling and noweb references, and finally running Babel from the command line and the security model that protects you from code you did not write.
Every result shown in this chapter was produced by Org 9.8.13 running in Emacs 31 in batch mode. Python examples ran with Python 3.
Why code blocks exist
Two traditions meet in Babel. The first is literate programming: a program is written as an essay for people, and the compiler receives the code extracted from that essay. The second is reproducible research: the data, the code that analyzes it, the results, and the discussion of those results live in one file, so that anyone can run the analysis again and check the claims.
In practice you use Babel for much smaller things too:
- a notes file where shell commands can be run in place and their output kept next to the explanation;
- an Emacs configuration written as an Org document and extracted into
init.el; - a report whose tables are computed by code at export time;
- a runbook where each step is a block you can execute and record.
A source code block (also code block or src block) is the unit Org works with. Org can do three independent things with one:
| Operation | Command | What happens |
|---|---|---|
| Evaluate | C-c C-c on the block | The code runs; its result is inserted below the block. |
| Tangle | C-c C-v t | The code is written to an external source file. |
| Export | C-c C-e | The code, its result, both, or neither appear in the exported document. |
flowchart LR B["code block"] -->|"C-c C-c"| E["evaluate"] B -->|"C-c C-v t"| T["tangle"] B -->|"C-c C-e"| X["export"] E -->|"result"| R["#+RESULTS: in the Org buffer"] T -->|"expanded body"| F["source file on disk"] X -->|":exports code/results/both/none"| D["HTML, LaTeX, Markdown ..."] X -.->|"may evaluate first"| E
Figure 14.1: One code block feeds three separate operations, and export may trigger evaluation on its own.
Header arguments (covered below) control each operation separately: a block can be tangled but never evaluated, evaluated but never exported, or any other combination.
The anatomy of a code block
A code block sits between #+BEGIN_SRC and #+END_SRC lines. The opening line names the language and may carry switches and header arguments. An optional #+NAME: line above the block gives it a name, which lets other blocks, tables and links refer to it.
#+NAME: version-info
#+BEGIN_SRC emacs-lisp
(format "Org %s on Emacs %d" (org-version) emacs-major-version)
#+END_SRC
The general shape is:
#+NAME: <name>
#+BEGIN_SRC <language> <switches> <header arguments>
<body>
#+END_SRC
The keywords are case-insensitive: #+begin_src works as well as #+BEGIN_SRC. If you omit the language, you cannot give switches or header arguments either, because Org would read the first of them as the language. Names must be unique in a file; with duplicate names, the behavior is undefined.
You rarely type the delimiters by hand. C-c C-, (org-insert-structure-template) asks for a block type and inserts the pair; the entry s in org-structure-template-alist produces a src block. With text selected, the same command wraps the region in the block.
Inline code
For a short computation inside a sentence, use an inline code block:
The answer is src_emacs-lisp{(* 6 7)}.
An inline block may take header arguments in brackets, src_python[:results value]{return 2**10}. Inline blocks cannot have names. After evaluation Org places the result right after the block, wrapped in a results macro so that the next evaluation can find and replace it:
Inline: src_emacs-lisp{(* 6 7)} {{{results(=42=)}}} and src_python[:results value]{return 2**10} {{{results(=1024=)}}}.
The =...= around the value comes from org-babel-inline-result-wrap, whose default "=%s=" formats the result as verbatim text.
Editing a block in its own mode
Typing code directly in the Org buffer works for a few lines. For anything longer, press C-c ' (org-edit-special) inside the block. Org opens a separate buffer in the language’s major mode, with its indentation, completion and linting. C-c ' again writes the code back and closes the buffer; C-x C-s writes it back without closing.
A few variables shape this experience:
| Variable | Effect |
|---|---|
org-src-fontify-natively | Highlight code in the Org buffer using the language’s major mode (default t). |
org-src-tab-acts-natively | Make TAB in a block indent as the language mode would (default t). |
org-src-lang-modes | Map a language name to a major mode, for example ("shell" . sh). |
org-src-window-setup | Where the edit buffer appears (default reorganize-frame). |
org-src-content-indentation | Indentation added to the block body when Org writes it back (default 2). |
org-src-preserve-indentation | When non-nil, keep the body exactly as written, flush left. |
Indentation matters for whitespace-sensitive languages. If Python code inside your blocks shifts in surprising ways, set org-src-preserve-indentation to t and write the code from the first column.
Enabling languages
Org ships a Babel backend for each supported language, in files named ob-<language>.el. Version 9.8.13 includes backends for awk, C (and C++, D), C#, calc, Clojure, CSS, ditaa, Graphviz dot, Emacs Lisp, Eshell, Forth, Fortran, gnuplot, Groovy, Haskell, Java, JavaScript, Julia, LaTeX, LilyPond, Lisp, Lua, Makefile, MATLAB, Maxima, OCaml, Octave, Org, Perl, PlantUML, Processing, Python, R, Ruby, Sass, Scheme, GNU Screen, sed, shell, SQL and SQLite. Many more live in external packages.
By default only Emacs Lisp can be evaluated. The variable org-babel-load-languages lists the languages to activate, and org-babel-do-load-languages sets it and loads the backends:
(org-babel-do-load-languages
'org-babel-load-languages
'((emacs-lisp . t)
(shell . t)
(python . t)))
A nil instead of t disables a language. Loading a backend with require, for example (require 'ob-python), enables that language as well.
The language name on the #+BEGIN_SRC line selects the backend. For shell code you can write shell, or the name of a specific shell (sh, bash, zsh), which also chooses the interpreter.
Evaluating a block
Put point anywhere in a block and press C-c C-c. Org runs the code, collects the result and inserts it after a #+RESULTS: line below the block. If the block is named, the result line repeats the name. Running the block again replaces the old result.
#+NAME: version-info
#+BEGIN_SRC emacs-lisp
(format "Org %s on Emacs %d" (org-version) emacs-major-version)
#+END_SRC
#+RESULTS: version-info
: Org 9.8.13 on Emacs 31
C-c C-v e does the same as C-c C-c on a block. If you would rather keep C-c C-c from ever running code, set org-babel-no-eval-on-ctrl-c-ctrl-c to t.
Org asks for confirmation before each evaluation. That prompt is a security feature, and the last section explains how to tune it. To evaluate many blocks at once, use C-c C-v b (org-babel-execute-buffer) for the whole buffer or C-c C-v s (org-babel-execute-subtree) for the current subtree. To delete a result, use C-c C-v k (org-babel-remove-result-one-or-many).
Value or output: how the result is collected
The first question Org asks about a result is where it comes from. The :results header argument offers two collection modes:
value(the default for most languages) treats the block as the body of a function and takes its return value.outputruns the block as a script and takes everything it printed to standard output.
The difference is clearest in Python, where a value result needs an explicit return:
#+BEGIN_SRC python :results value
return sum(range(1, 11))
#+END_SRC
#+RESULTS:
: 55
#+BEGIN_SRC python :results output
for n in range(1, 4):
print(n, n * n)
#+END_SRC
#+RESULTS:
: 1 1
: 2 4
: 3 9
Without return, a Python value block yields None, even when its last line is an expression:
#+BEGIN_SRC python
x = 21
x * 2
#+END_SRC
#+RESULTS:
: None
Shell blocks print by nature, so their “value” is their standard output. Org then tries to read that output as a table, which is why two lines become a one-column table here:
#+BEGIN_SRC shell
ls /etc/hostname
echo done
#+END_SRC
#+RESULTS:
| /etc/hostname |
| done |
Add :results output when you want the text as it is.
Type, format and handling
After collection, three more classes of :results options decide how the result is interpreted, wrapped and placed. You may combine one option from each class, as in :results output verbatim replace.
flowchart LR C["code runs"] --> K["Collection<br/>value | output"] K -->|"raw result"| T["Type<br/>table, list, scalar, file"] T -->|"Org data"| F["Format<br/>raw, drawer, code, html, org ..."] F -->|"formatted text"| H["Handling<br/>replace, append, silent ..."] H --> B["Org buffer"]
Figure 14.2: A result passes through four independent choices, each set by one word in :results.
Type says what kind of Org object the result should become:
| Type | Result |
|---|---|
table or vector | An Org table; a single value becomes a 1 by 1 table. |
list | An Org plain list. |
scalar or verbatim | Literal text, never converted into a table. |
file | The result is written to a file and a link to it is inserted. |
When you give no type, the backend guesses. A Lisp list of lists becomes a table, and in Python a None row becomes a horizontal rule:
#+BEGIN_SRC python
return [["n", "square"], None, [1, 1], [2, 4], [3, 9]]
#+END_SRC
#+RESULTS:
| n | square |
|---+--------|
| 1 | 1 |
| 2 | 4 |
| 3 | 9 |
The same data can take other shapes:
#+BEGIN_SRC emacs-lisp :results list
'("apples" "pears" "plums")
#+END_SRC
#+RESULTS:
- apples
- pears
- plums
#+BEGIN_SRC emacs-lisp :results verbatim
'(1 2 3)
#+END_SRC
#+RESULTS:
: (1 2 3)
A file result needs a file name from the :file header argument; Org writes the result there and inserts a link:
#+BEGIN_SRC shell :results file :file hello.txt
echo "written by a code block"
#+END_SRC
#+RESULTS:
[[file:hello.txt]]
This is the usual way to include generated images: a plotting block writes a PNG and the link displays it inline. When the code itself writes the file (as a plotting library usually does), add link or graphics (:results file link) so that Org only inserts the link and does not overwrite the file with the block’s return value. The related header arguments :output-dir, :file-ext, :file-desc and :file-mode control the directory, the extension, the link description and the file permissions.
Format decides how the result is wrapped:
| Format | Wrapping |
|---|---|
raw | None: the text is inserted as Org markup. |
drawer | Like raw, but inside a :results: drawer, so Org can find and replace it. |
code | Inside a source block of the same language. |
org | Inside a #+begin_src org block. |
html, latex | Inside an export block for that backend. |
pp | Pretty-printed code (Emacs Lisp, Python, Ruby). |
The drawer format is the practical choice for a block that generates Org text, because a raw result has no end marker and cannot be replaced cleanly on the next run:
#+BEGIN_SRC emacs-lisp :results drawer
"- item one\n- item two"
#+END_SRC
#+RESULTS:
:results:
- item one
- item two
:end:
The separate :wrap header argument wraps the result in any block you name, and it takes precedence over the format:
#+BEGIN_SRC emacs-lisp :wrap quote
"A wrapped result."
#+END_SRC
#+RESULTS:
#+begin_quote
A wrapped result.
#+end_quote
Handling decides what happens to the previous result. replace (default) overwrites it; append and prepend keep it and add the new one below or above; silent shows the result only in the echo area; none computes the result but does not show it (other blocks can still use it); discard throws it away entirely.
The :post header argument runs another named block on the result before insertion. Inside the :post call the variable *this* holds the result, as in :post round-numbers(data=*this*).
Header arguments and where they come from
A header argument is a setting for one aspect of a block, written as a keyword and a value: :results output, :tangle yes, :var n=5. Some apply to all languages; some exist only for one backend (for example :lexical for Emacs Lisp).
Writing the same arguments on every block would be tedious, so Org reads header arguments from several places and merges them. A more local setting always overrides a more general one:
flowchart TB A["org-babel-default-header-args"] -->|"overridden by"| B["org-babel-default-header-args:LANG"] B -->|"overridden by"| C["#+PROPERTY: header-args and :header-args: in drawers"] C -->|"overridden by"| D["header-args:LANG properties"] D -->|"overridden by"| E["arguments on the #+BEGIN_SRC line"] E -->|"overridden by"| F["#+HEADER: lines"] F -->|"overridden by"| G["#+CALL: and call_ arguments"]
Figure 14.3: Header arguments are merged from the most general source to the most specific one, and the last value wins.
The following file shows each level winning in turn. A global default sets source for all Emacs Lisp blocks, and each later level overrides it:
(setq org-babel-default-header-args:emacs-lisp
'((:var . "source=\"global default\"")))
#+PROPERTY: header-args:emacs-lisp :var source="buffer property"
* Default level
#+BEGIN_SRC emacs-lisp
source
#+END_SRC
#+RESULTS:
: buffer property
* Subtree level
:PROPERTIES:
:header-args:emacs-lisp: :var source="subtree property"
:END:
#+BEGIN_SRC emacs-lisp
source
#+END_SRC
#+RESULTS:
: subtree property
#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC
#+RESULTS:
: block line
#+HEADER: :var source="HEADER line"
#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC
#+RESULTS:
: HEADER line
#+NAME: report
#+BEGIN_SRC emacs-lisp :var source="block line"
source
#+END_SRC
#+RESULTS: report
: block line
#+CALL: report(source="CALL arguments")
#+RESULTS:
: CALL arguments
Without the #+PROPERTY line, the first block returns global default.
The levels in practice:
- System-wide defaults.
org-babel-default-header-argsholds the defaults for every block::session none,:results replace,:exports code,:cache no,:noweb no,:hlines no,:tangle no. Inline blocks useorg-babel-default-inline-header-argsinstead, which exports results rather than code. Per-language variables are namedorg-babel-default-header-args:<lang>; for Emacs Lisp the default is((:lexical . "no")), so Emacs Lisp blocks use dynamic binding unless you write:lexical yes. - Buffer-wide. A
#+PROPERTY: header-args ...line applies to the whole file;#+PROPERTY: header-args:python ...applies to Python blocks only. - Subtree. A
header-args(orheader-args:<lang>) property in a heading’s property drawer applies to all blocks in that subtree. These properties are always inherited, whateverorg-use-property-inheritancesays. Writing the property name with a+suffix (:header-args+:) appends to an inherited value instead of replacing it. See Tags, Properties and Column View for property syntax. - Block. Arguments on the
#+BEGIN_SRCline, and on any#+HEADER:lines directly above it.#+HEADER:is useful when the opening line would become too long. - Call. Arguments given in a
#+CALL:line or an inlinecall_override everything else for that call.
To change a global default without losing the others, replace one entry:
(setq org-babel-default-header-args
(cons '(:noweb . "yes")
(assq-delete-all :noweb org-babel-default-header-args)))
When you are unsure which value a block will actually see, put point in it and press C-c C-v I (org-babel-view-src-block-info): it displays the language, name and the merged header arguments. C-c C-v j (org-babel-insert-header-arg) inserts an argument with completion, and C-c C-v c (org-babel-check-src-block) reports misspelled ones.
Passing data between blocks and tables
Most of Babel’s power comes from the :var header argument. It binds a variable in the block to a value, and the value can be a literal, a named table, a named list, a named example block, or the result of another named block. The syntax is the same in every language:
:var NAME=VALUE
Here a table of expenses feeds a Python block, which feeds an Emacs Lisp block:
#+NAME: expenses
| item | amount |
|--------+--------|
| rent | 1200 |
| food | 450 |
| travel | 180 |
#+NAME: total
#+BEGIN_SRC python :var rows=expenses
return sum(amount for _, amount in rows)
#+END_SRC
#+RESULTS: total
: 1830
#+NAME: share
#+BEGIN_SRC emacs-lisp :var sum=total() :var people=3
(/ sum people)
#+END_SRC
#+RESULTS: share
: 610
Several points are visible here:
- A table arrives as a list of rows. Because the table has a header row followed by a rule, Org removed the header before passing it, so
rowscontains only the data rows. total()with parentheses means “evaluate the block namedtotaland use its result”. Inside the parentheses you can pass arguments:total(rows=other-table).- Numbers in tables arrive as numbers, so the code can add them without conversion.
flowchart LR T["#+NAME: expenses<br/>(table)"] -->|":var rows=expenses"| P["#+NAME: total<br/>(python)"] P -->|":var sum=total()"| L["#+NAME: share<br/>(emacs-lisp)"] L -->|"result"| R1["#+RESULTS: share"] L -->|"call_share(people=2)"| I["inline result in a sentence"] N["#+NAME: header-comment"] -->|"noweb reference"| C["#+NAME: config<br/>(:noweb yes)"] C -->|"tangle"| F["source file"]
Figure 14.4: :var passes values and results between blocks at evaluation time, while noweb references splice code into other blocks.
Column names and row names
When the input table has a header row separated by a rule, the default :colnames nil removes the header before the code runs and puts it back on the result. With :colnames yes the first row is treated as a header even without a rule; with :colnames no Org does no header processing at all. Here the header survives the transformation:
#+BEGIN_SRC python :var rows=expenses :colnames yes
return [[item.upper(), amount * 2] for item, amount in rows]
#+END_SRC
#+RESULTS:
| item | amount |
|--------+--------|
| RENT | 2400 |
| FOOD | 900 |
| TRAVEL | 360 |
:rownames yes does the same for the first column. The related :hlines argument decides whether horizontal rules inside a table are passed through (yes) or removed (no, the default for ordinary blocks).
Indexing into a value
Square brackets after a reference select part of it. Indexes start at 0, negative indexes count from the end, a comma separates dimensions, a:b selects an inclusive range, and an empty index or * selects everything in that dimension. Indexing happens before header processing, so the header row and the rule below it count as rows 0 and 1:
#+BEGIN_SRC emacs-lisp :var cell=expenses[2,1]
cell
#+END_SRC
#+RESULTS:
: 1200
Lisp values
A value that starts with (, [, ' or ` is evaluated as Emacs Lisp before the block runs. This gives a block information about its environment, such as the file it lives in:
#+BEGIN_SRC emacs-lisp :var file=(file-name-nondirectory (buffer-file-name))
file
#+END_SRC
#+RESULTS:
: var.org
Values read from tables and lists are never evaluated this way, so a cell containing (a b c) stays a string.
Calling a block like a function
A named block with :var defaults behaves like a function with default arguments. The #+CALL: keyword calls it from anywhere in the document and inserts the result below the call:
#+CALL: share(people=4)
#+RESULTS:
: 457
The full syntax allows header arguments in two places. Arguments in brackets after the name (inside header arguments) apply when the block runs; arguments after the closing parenthesis (end header arguments) apply to the result of the call:
#+CALL: <name>[<inside header arguments>](<arguments>) <end header arguments>
The inline form, call_<name>(<arguments>), puts the result into running text:
Each person pays call_share(people=2) {{{results(=915=)}}} per month.
A block in another file can be called by prefixing its name with the file name: #+CALL: tools.org:clean-data(). Table formulas can call blocks as well, through the org-sbe function described in The Spreadsheet and Plotting.
The environment of a block
Sessions
By default every evaluation starts a fresh interpreter process that ends when the block finishes. This keeps blocks independent, but it also means that a variable defined in one block does not exist in the next. The :session header argument runs blocks in a shared, long-lived interpreter instead:
#+BEGIN_SRC python :session demo
counter = 10
#+END_SRC
#+RESULTS:
: None
#+BEGIN_SRC python :session demo
counter += 5
counter
#+END_SRC
#+RESULTS:
: 15
#+BEGIN_SRC python
counter
#+END_SRC
The last block runs outside the session, where counter is undefined, so the Python process fails and Org inserts no result. Notice also that in a session the value of the last expression is the result, without return, because Org reads it from the interactive interpreter.
Sessions suit exploratory work: load a large data set once and query it from many small blocks. Their cost is hidden state. The document no longer describes the full computation, because the result of a block depends on which blocks ran before it and in what order. Before you share a document built with sessions, restart the session and run the buffer from the top (C-c C-v b).
A session is a buffer you can visit. C-c C-v z (org-babel-switch-to-session-with-code) opens it next to the code. Not every language supports sessions; C and ditaa, for example, do not, and Emacs Lisp blocks always run inside Emacs itself.
Working directory, prologue and epilogue
:dir sets the working directory for one evaluation, and it accepts remote TRAMP paths, so a block can run on another machine. :mkdirp yes creates the directory when it is missing.
#+BEGIN_SRC shell :dir /tmp
pwd
#+END_SRC
#+RESULTS:
: /tmp
:prologue and :epilogue add code before and after the body at execution time, without showing it in the block:
#+BEGIN_SRC shell :prologue "set -e" :epilogue "echo finished"
echo working
#+END_SRC
#+RESULTS:
| working |
| finished |
They are most useful as defaults, for example a reset command before every gnuplot block, set in org-babel-default-header-args:gnuplot.
Controlling when code runs
Caching expensive blocks
With :cache yes, Org stores a SHA1 hash of the block’s code and arguments on the result line. On the next evaluation, if the hash still matches, Org returns the stored result without running the code:
#+NAME: slow
#+BEGIN_SRC emacs-lisp :cache yes
(* 3 14)
#+END_SRC
#+RESULTS[90b23cf30fa76883bba5b3579e5c75468e1a7ff4]: slow
: 42
The hash covers the arguments, including the values of :var references, so a cached block that depends on another block re-runs when the upstream result changes. Caching is safe only for pure computations: code whose result depends only on its inputs. A block that reads the clock, the file system or a random number generator should not be cached, and caching inside sessions can give surprising results. The hash also ignores code pulled in by noweb references.
Limiting evaluation
The :eval header argument decides whether a block may run at all:
| Value | Meaning |
|---|---|
yes | Run, subject to the confirmation setting (default). |
never or no | Never run. |
query | Always ask before running. |
never-export or no-export | Do not run during export, but allow interactive runs. |
query-export | Ask before running during export. |
#+BEGIN_SRC emacs-lisp :eval never
(error "never runs")
#+END_SRC
:eval never is a good way to keep a dangerous or slow block in a document as documentation. :eval never-export is the usual choice for a report whose results you have already computed and checked by hand.
Exporting code blocks
When you export a document, the :exports header argument decides what each block contributes:
| Value | Exported content |
|---|---|
code | The code only (default for ordinary blocks). |
results | The result only (default for inline blocks). |
both | The code followed by the result. |
none | Nothing. |
Given this file:
#+OPTIONS: toc:nil
#+TITLE: Export demo
#+NAME: answer
#+BEGIN_SRC emacs-lisp :exports both
(* 6 7)
#+END_SRC
#+BEGIN_SRC emacs-lisp :exports results
(format "Computed during export: %d" (+ 1 2))
#+END_SRC
#+BEGIN_SRC emacs-lisp :exports none
(message "not exported")
#+END_SRC
#+BEGIN_SRC emacs-lisp
"code only"
#+END_SRC
Inline: src_emacs-lisp{(+ 40 2)}.
the Markdown exporter produces:
(* 6 7)
42
Computed during export: 3
"code only"
Inline: `42`.
Two blocks were evaluated during the export, because their results were needed. Org does not evaluate blocks whose results are not exported (code or none), except blocks that use a session, which follow their :eval setting. Org also evaluates blocks in subtrees excluded from export, but never in commented subtrees.
Two settings turn evaluation off during export:
:eval never-exporton a block (or as a buffer-wide property) stops evaluation but still processes the other header arguments, so existing results are exported as they are.- Setting
org-export-use-babeltonildisables Babel entirely during export. Header arguments then have no effect at all::exportsis ignored, and every block is exported as code.
A name on a block also names its result in the export, so a link to a block exported with :exports results points to the result. The Exporting chapter covers the export process itself.
Tangling: extracting source files
Tangling writes the bodies of code blocks to ordinary source files. It is how a literate program becomes a program again, and how an Org configuration file becomes init.el. The :tangle header argument decides where each block goes:
no(default): the block is not tangled;yes: tangle to a file named after the Org file, with an extension derived from the language;- a file name: tangle to that file, relative to the Org file’s directory.
Several blocks may tangle to the same file; Org writes them in document order. C-c C-v t (org-babel-tangle) tangles the whole buffer, and with a prefix argument only the current block. C-c C-v f (org-babel-tangle-file) asks for a file to tangle.
The following file defines a small Python program and tangles every block to greet.py:
#+PROPERTY: header-args:python :tangle yes :comments link
* Imports
#+BEGIN_SRC python
import sys
#+END_SRC
* Entry point
#+BEGIN_SRC python
def main(name):
print(f"Hello, {name}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "world")
#+END_SRC
Running org-babel-tangle produced greet.py:
# [[file:greet.org::*Imports][Imports:1]]
import sys
# Imports:1 ends here
# [[file:greet.org::*Entry point][Entry point:1]]
def main(name):
print(f"Hello, {name}")
if __name__ == "__main__":
main(sys.argv[1] if len(sys.argv) > 1 else "world")
# Entry point:1 ends here
The comment lines come from :comments link. They let you jump from the tangled file back to the Org source with org-babel-tangle-jump-to-org, and they let org-babel-detangle copy edits made in the tangled file back into the Org blocks. Org reindents the bodies when it writes them back, using org-src-content-indentation.
The tangling header arguments:
| Argument | Purpose |
|---|---|
:comments | no (default), link, org (the preceding text as a comment), both, or noweb (link comments around expanded references too). |
:padline | yes (default) puts a blank line between blocks; no does not. |
:shebang | A first line such as "#!/bin/sh"; the file is also made executable. |
:tangle-mode | File permissions, such as o755, rw-r--r-- or (identity #o444). |
:mkdirp | yes creates missing parent directories. |
:no-expand | Write the body without expanding variables and noweb references. |
Blocks in commented subtrees (headings that start with COMMENT) are never tangled, which gives a quick way to switch off part of a configuration.
Four hooks let you act around tangling: org-babel-pre-tangle-hook runs in the Org buffer before tangling (by default it saves the buffer), org-babel-tangle-body-hook runs on each expanded body, org-babel-post-tangle-hook runs in each tangled file (useful for byte-compiling or formatting), and org-babel-tangle-finished-hook runs at the end in the Org buffer.
Noweb references: composing code from pieces
Tangling block after block in document order works when the order of explanation matches the order the compiler needs. Often it does not: you want to explain the main loop first and the helper functions later, or show a long script in small annotated steps. Noweb references, named after an early literate programming tool, solve this. A block can contain a reference of the form <<name>>, and Org replaces it with the body of the block called name.
Noweb expansion is off by default, because <<...>> can be valid code in many languages. The :noweb header argument turns it on and chooses when it applies:
| Value | Evaluate | Tangle | Export |
|---|---|---|---|
no (default) | no | no | no |
yes | expand | expand | expand |
tangle | no | expand | no |
no-export | expand | expand | no |
strip-export | expand | expand | references removed |
strip-tangle | expand | references removed | expand |
eval | expand | no | no |
Here is a complete literate shell script. The top block shows the overall structure; the details come later, under their own headings:
#+TITLE: A literate backup script
#+PROPERTY: header-args:shell :noweb yes
* The script
The script is assembled from the pieces below.
#+BEGIN_SRC shell :tangle bin/backup.sh :mkdirp yes :shebang "#!/bin/sh"
set -eu
<<settings>>
<<archive>>
#+END_SRC
* Settings
#+NAME: settings
#+BEGIN_SRC shell
SRC="$HOME/notes"
DEST="/tmp/backup"
#+END_SRC
* Steps
:PROPERTIES:
:header-args:shell+: :noweb-ref archive
:END:
** Make sure the destination exists
#+BEGIN_SRC shell
mkdir -p "$DEST"
#+END_SRC
** Write the archive
#+BEGIN_SRC shell
tar -czf "$DEST/notes-$(date +%F).tar.gz" -C "$SRC" .
#+END_SRC
Tangling creates bin/backup.sh with mode rwxr-xr-x (because of :shebang) and this content:
#!/bin/sh
set -eu
SRC="$HOME/notes"
DEST="/tmp/backup"
mkdir -p "$DEST"
tar -czf "$DEST/notes-$(date +%F).tar.gz" -C "$SRC" .
Two kinds of reference appear in this example:
<<settings>>refers to the block namedsettings.<<archive>>refers to every block whose:noweb-refheader argument isarchive. Here the property drawer of the “Steps” heading gives that argument to both blocks below it, and Org concatenates their bodies in document order, separated by newlines (change the separator with:noweb-sep). This is how you split one logical piece of code across several explained steps.
Only the top block has a :tangle argument, so the pieces are tangled only through the references.
Inserting results instead of code
Parentheses after the name, as in <<name()>> or <<name(arg=value)>>, insert the result of evaluating the named block rather than its body. Noweb also respects a prefix: when a reference has text before it on the line, every line of the inserted text gets the same prefix. That is how a multi-line block can be turned into a comment, or indented to the right level:
#+NAME: today
#+BEGIN_SRC emacs-lisp
"2026-11-19"
#+END_SRC
#+NAME: header-comment
#+BEGIN_SRC text
Generated from notes.org.
Do not edit by hand.
#+END_SRC
#+NAME: config
#+BEGIN_SRC shell :noweb yes
# <<header-comment>>
BUILD_DATE=<<today()>>
#+END_SRC
C-c C-v v (org-babel-expand-src-block) shows how a block will look after expansion, without running it. For config it shows:
# Generated from notes.org.
# Do not edit by hand.
BUILD_DATE=2026-11-19
Set :noweb-prefix no when you want a multi-line expansion inserted as it is, for example inside a string literal. Note that noweb expansion copies code only; the :var arguments of the referenced block are not carried along.
The Library of Babel
Named blocks are reusable within a file, and file.org:name makes them reusable across files. The Library of Babel goes one step further: it is a global collection of named blocks that any Org file can call by name alone. You add the named blocks of a file to it with org-babel-lob-ingest (C-c C-v i):
* Reusable blocks
#+NAME: word-count
#+BEGIN_SRC emacs-lisp :var text=""
(length (split-string text))
#+END_SRC
After ingesting this file, any Org buffer can call the block:
#+CALL: word-count(text="Org mode keeps code and prose together")
#+RESULTS:
: 7
To have the library available in every session, ingest your library files from your init file:
(with-eval-after-load 'org
(org-babel-lob-ingest "~/org/library.org"))
Key bindings
Babel commands live under the prefix C-c C-v; each key also works with Control held (C-c C-v C-t equals C-c C-v t). C-c C-v h lists them all.
| Key | Command | Purpose |
|---|---|---|
C-c C-c, C-c C-v e | org-babel-execute-src-block / org-babel-execute-maybe | Evaluate the block at point. |
C-c ' | org-edit-special | Edit the block in its language’s mode. |
C-c C-v b | org-babel-execute-buffer | Evaluate all blocks in the buffer. |
C-c C-v s | org-babel-execute-subtree | Evaluate all blocks in the subtree. |
C-c C-v k | org-babel-remove-result-one-or-many | Remove the result (all results with a prefix). |
C-c C-v n, C-c C-v p | org-babel-next-src-block / org-babel-previous-src-block | Move between blocks. |
C-c C-v g | org-babel-goto-named-src-block | Jump to a named block. |
C-c C-v o | org-babel-open-src-block-result | Open the result in a separate buffer. |
C-c C-v v | org-babel-expand-src-block | Preview the expanded body. |
C-c C-v I | org-babel-view-src-block-info | Show the merged header arguments. |
C-c C-v d | org-babel-demarcate-block | Split the block at point, or wrap the region in a new block. |
C-c C-v t | org-babel-tangle | Tangle the buffer. |
C-c C-v f | org-babel-tangle-file | Tangle a file. |
C-c C-v i | org-babel-lob-ingest | Add a file’s blocks to the Library of Babel. |
C-c C-v z | org-babel-switch-to-session-with-code | Show the session buffer. |
Running Babel from the command line
Babel works without an interactive Emacs, which makes it suitable for build scripts and continuous integration. Start Emacs with --batch, load Org, and call the same functions the keys call. This script tangles every file given on the command line:
#!/bin/sh
# tangle.sh FILE...
emacs -Q --batch --eval "
(progn
(require 'ob-tangle)
(dolist (file command-line-args-left)
(with-current-buffer (find-file-noselect file)
(org-babel-tangle))))
" "$@"
Tangling does not run code, so it needs no confirmation settings. Evaluation does, and in batch mode there is no one to answer the prompt. For a script that evaluates a document you trust, set the confirmation variable inside the batch run only:
;; run-notebook.el: emacs -Q --batch -l run-notebook.el notebook.org
(require 'org)
(org-babel-do-load-languages
'org-babel-load-languages '((emacs-lisp . t) (shell . t) (python . t)))
(let ((org-confirm-babel-evaluate nil))
(with-current-buffer (find-file-noselect (car command-line-args-left))
(org-babel-execute-buffer)
(save-buffer)))
The let binding limits the change to this one run; your normal Emacs keeps asking. The examples in this chapter were produced with a script of this kind.
Code evaluation and security
A code block is a program. Evaluating a block from an Org file you downloaded is as risky as running a script from the same source: it can delete files, read secrets or send data over the network. Export is a second path to the same risk, because exporting a document evaluates every block whose results are exported. Org therefore treats evaluation as something you must allow, block by block.
The central setting is org-confirm-babel-evaluate:
t(the default): Org asks before evaluating each block, with a question such as “Evaluate this python code block (total) on your system?”.nil: Org evaluates without asking.- a function: Org calls it with the language and the expanded body, and asks only if the function returns non-
nil.
The function form gives a middle ground. This configuration skips the prompt for two diagram languages whose blocks only draw pictures, and keeps it for everything else:
(defun my-babel-confirm (lang _body)
"Ask before evaluating any block except diagram blocks."
(not (member lang '("dot" "ditaa"))))
(setq org-confirm-babel-evaluate #'my-babel-confirm)
Org protects this variable from the files it opens. Its safe-local-variable property accepts only the value t, so a file cannot switch confirmation off through file-local variables. A malicious file can still put :eval yes on its blocks, but yes only means “evaluate, subject to org-confirm-babel-evaluate”, so the prompt still appears.
Some practical rules follow from this:
- Keep the default
tglobally. If the prompts become tiresome, use a function that exempts specific languages, or bind the variable tonilwithletin scripts that process your own files, as in the batch example above. - Read a document before you evaluate or export it, when it comes from someone else. Header arguments count as code too: a
:varvalue that starts with(is Emacs Lisp, evaluated when the block runs. - Mark blocks that must never run with
:eval never, and blocks that must not run during export with:eval never-export. - To export untrusted documents, set
org-export-use-babeltonil. Org then evaluates nothing during export and ignores all header arguments. - If you want
C-c C-cnever to run code by accident, setorg-babel-no-eval-on-ctrl-c-ctrl-ctotand useC-c C-v edeliberately.
Code blocks are not the only executable content in Org. shell: and elisp: links run code when you follow them, and their prompts are controlled by org-link-shell-confirm-function and org-link-elisp-confirm-function (both yes-or-no-p by default). Table formulas also run Calc or Emacs Lisp code. The Org Beyond the Basics chapter discusses these together.
Further reading
- Org manual: Working with Source Code, Structure of Code Blocks, Using Header Arguments, Environment of a Code Block
- Org manual: Evaluating Code Blocks, Results of Evaluation, Exporting Code Blocks
- Org manual: Extracting Source Code, Noweb Reference Syntax, Library of Babel
- Org manual: Languages, Editing Source Code, Key bindings and Useful Functions, Batch Execution, Code Evaluation Security
- Source: lisp/ob-core.el (evaluation, header arguments, results), lisp/ob-tangle.el, lisp/ob-exp.el