Skip to main content

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

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

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.

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

A literal example block named with a β€˜NAME’ keyword.

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

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.