Movatterモバイル変換


[0]ホーム

URL:


Next:, Previous:, Up:Working with Source Code   [Contents][Index]


16.4 Environment of a Code Block

Passing arguments

Use ‘var’ for passing arguments to source code blocks. The specificsof variables in code blocks vary by the source language and arecovered in the language-specific documentation. The syntax for ‘var’,however, is the same for all languages. This includes declaringa variable, and assigning a default value.

The following syntax is used to pass arguments to code blocks usingthe ‘var’ header argument.

:var NAME=ASSIGN

NAME is the name of the variable bound in the code blockbody.ASSIGN is a literal value, such as a string,a number, a reference to a table, a list, a literal example, anothercode block—with or without arguments—or the results of evaluatinga code block.ASSIGN may specify a filename for referencesto elements in a different file, using a ‘:’ to separate the filenamefrom the reference.

:var NAME=FILE:REFERENCE

When ‘FILE’ does not exist, the reference is searched in the currentfile, 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 thecolumn, containing labels for the columns, or the rows, in thetable.

The ‘colnames’ header argument accepts ‘yes’, ‘no’, or ‘nil’ values.The default value is ‘nil’: if an input table has columnnames—because the second row is a horizontal rule—then Orgremoves the column names, processes the table, puts back the columnnames, and then writes the table to the results block. Using ‘yes’,Org does the same to the first non-hline row, even if the initialtable does not contain any horizontal rule. When set to ‘no’, Orgdoes not pre-process column names at all.

#+NAME: less-cols| a ||---|| b || c |#+BEGIN_SRC python :var tab=less-cols :colnames nilreturn [[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, processesthe table, puts back the first column, and then writes the table tothe results block. The default is ‘no’, which means Org does notpre-process the first column. Note that Emacs Lisp code blocksignore ‘rownames’ header argument because of the ease oftable-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 yesreturn [[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 witha 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. Nestedlist items are ignored.

code block without arguments

A code block name, as assigned by ‘NAME’ keyword from the exampleabove, 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 byparentheses 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 theend. If an index is separated by commas then each subsequent sectionindexes as the next dimension. Note that this indexing occursbefore other table-related header arguments are applied, such as‘hlines’, ‘colnames’ and ‘rownames’. The following example assignsthe last cell of the first row the table ‘example-table’ to thevariable ‘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 variablevalues. In that case the entire inclusive range is referenced. Forexample 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 toreference 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. Indexreferencing can handle any number of dimensions. Commas delimitmultiple 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 variableindexing. 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. Todifferentiate a value from Lisp code, Org interprets any valuestarting with ‘(’, ‘[’, ‘'’ or ‘`’ as Emacs Lisp code. The result ofevaluating that code is then assigned to the value of that variable.The following example shows how to reliably query and pass the filename of the Org mode buffer to a code block using headers. We needreliability here because the file’s name could change once the code inthe 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 mistakenlyevaluated 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’ headerargument is for running multiple source code blocks under one session.Org runs code blocks with the same session name in the sameinterpreter 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 thatsession. For example, ‘:session STRING’ names it ‘STRING’. If‘session’ has no value, then the session name is derived from thesource language identifier. Subsequent blocks with the same sourcecode language use the same session. Depending on the language,state variables, code from other blocks, and the overall interpretedenvironment may be shared. Some interpreted languages supportconcurrent sessions when subsequent source code language blockschange session names.

Only languages that provide interactive evaluation can have sessionsupport. Not all languages provide this support, such as C and ditaa.Even languages, such as Python and Haskell, that do supportinteractive evaluation impose limitations on allowable languageconstructs that can run interactively. Org inherits those limitationsfor those code blocks running in a session.

Choosing a working directory

The ‘dir’ header argument specifies the default directory during codeblock execution. If it is absent, then the directory associated withthe current buffer is used. In other words, supplying ‘:dirDIRECTORY’ temporarily has the same effect as changing the currentdirectory withM-x cdRET DIRECTORY, and then not setting‘dir’. Under the surface, ‘dir’ simply sets the value of the Emacsvariabledefault-directory. Setting ‘mkdirp’ header argument toa non-nil value creates the directory, if necessary.

Setting ‘dir’ to the symbolattach or the string"'attach" willset ‘dir’ to the directory returned by(org-attach-dir), set ‘:mkdiryes’, and insert any file paths, as when using ‘:results file’, whichare under the node’s attachment directory using ‘attachment:’ linksinstead of the usual ‘file:’ links. Any returned path outside of theattachment directory will use ‘file:’ links as per usual.

For example, to save the plot file in the ‘Work/’ folder of the homedirectory—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 remotedirectory 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 Orgfile. Then Org also inserts a link to the remote file, thanks toEmacs Tramp. Org constructs the remote path to the file name from‘dir’ anddefault-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 fora new session. But Org does not alter the directory of an alreadyexisting session.

Do not use ‘dir’ with ‘:exports results’ or with ‘:exports both’ toavoid Org inserting incorrect links to remote files. That is becauseOrg does not expanddefault directory to avoid some underlyingportability issues.

Inserting headers and footers

The ‘prologue’ header argument is for appending to the top of the codeblock for execution, like a reset instruction. For example, you mayuse ‘:prologue "reset"’ in a Gnuplot code block or, for every suchblock:

(add-to-list 'org-babel-default-header-args:gnuplot             '((:prologue . "reset")))

Likewise, the value of the ‘epilogue’ header argument is for appendingto the end of the code block for execution.


Next:Evaluating Code Blocks, Previous:Using Header Arguments, Up:Working with Source Code   [Contents][Index]


[8]ページ先頭

©2009-2025 Movatter.jp