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.