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

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 |

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.

#+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 ‘:mkdir 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 of 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.