Source blocks (Babel)
#+NAME: hello
#+begin_src python :results output :var n=3
for i in range(n): print("hi", i)
#+end_src
Babel follows Emacs Org 9.8: the same header arguments, the same way values are read from programs and written back (tables, lists, : lines), the same #+RESULTS placement, :cache hashes and tangled files, so a file gives the same results in both editors.
| <C-c><C-c> or <prefix>be | Execute the block, #+CALL line, inline src block or inline call at the cursor (asynchronously). With a count (C-u) a :cache yes block runs even when its hash is unchanged. |
| <prefix>bb / bs | Execute every src block, #+CALL line, inline src block and inline call of the buffer / subtree, in order. |
| <prefix>bk | Remove the result. With a count (C-u), remove every result in the buffer. |
| <prefix>bn / bp | Next / previous block. |
| <prefix>' | Edit the block in a buffer with the language's filetype, the cursor at the same place in the code (and back in the block where it was in the code on leaving). With a count (C-u) on a block with a :session, show the session instead. See org-babel-edit-special. |
| <prefix>bt | Tangle the file (:Org tangle). With a count of 1 (C-u) only the block at the cursor; with 2 or more (C-u C-u) the blocks with the same :tangle value. |
| <prefix>bf | Tangle another file. |
| <prefix>bv | Show the expanded block (noweb, :prologue, variables, :epilogue) in a split. |
| <prefix>bI / bc | Show the block's merged header args / report a header arg of the #+begin_src line that looks like a misspelt one (within 2 edits of a known name, like Emacs). |
| <prefix>bj | Insert a header argument (names and values completed). |
| <prefix>bg / br | Go to a named block / a named result. |
| <prefix>bu | Go to the head of the block. |
| <prefix>bo | Open the result (follows a file link, or shows it). |
| <prefix>bd | Split the block at the cursor into two (mid-line at the cursor's column), re-indent the blocks like org-indent-block and go to the last one; in Visual mode wrap the selection in a new block (or, inside a block, make it a block of its own); elsewhere insert a block, in the blank lines after a block of the same language without asking for one. |
| <prefix>bi | Add the named blocks of a file to the Library of Babel, so #+CALL, :var and noweb can use them everywhere (also <C-c><C-v><Tab>). |
| <prefix>bz / bZ | Show the block's session (with a count, first assign its :var values there); bZ also opens the edit buffer. |
| <prefix>bl | Send the block to its session and show the session. |
| <prefix>bK | Kill the block's session. |
| <prefix>bC | Cancel the evaluation of the block at the cursor (elsewhere: the only one running, or pick one); with a count, every running evaluation. See org-babel-async. |
| <prefix>ba | Show the block's hash (the one :cache yes stores). |
| <prefix>bh | List the Babel key bindings. |
| <prefix>bm | Select the block body (Visual line mode). |
| <prefix>bx | Run Normal-mode keys in the block's edit buffer and write the result back (e.g. gg=G to reindent). |
| <Tab> on #+RESULTS | Fold / unfold the result (org-babel-hide-result-toggle); :Org babel_hide_all_results folds every result. |
<C-c><C-c> on the hash of #+RESULTS[hash]: | Copy the hash to the unnamed register and show it (org-babel-hash-at-point, :Org babel_hash_at_point). |
| :Org babel_remove_inline_result | Remove the {{{results(...)}}} after the inline src block or inline call at the cursor, with the white space before it (org-babel-remove-inline-result; <prefix>bk does not remove inline results, like Emacs). |
| #+CALL: name(n=5) | Execute a named block with arguments (C-c C-c on it). #+NAME: above a call names its results. Arguments without name= fill the block's variables in order: #+CALL: add(10, 20). |
| src_lua{return 1} | Inline block: C-c C-c on it inserts or replaces {{{results(=1=)}}} after it. :results raw inserts the bare value; tables, lists and multi-line results are an error ("Inline error: ... cannot be used"). |
| call_name(n=5) | Inline call, same as above. |
Evaluation
Before a block runs you are asked "Evaluate this LANG code block on your system?" unless babel.confirm_evaluate is false. It can also be a function function(lang, body) return true end that decides (like Emacs' org-confirm-babel-evaluate). :eval query always asks, :eval no and :eval never (or :noeval) never run, :eval never-export/no-export only skip export, :eval query-export asks when exporting. Executing the buffer or a subtree asks for every block, like Emacs. With babel.no_eval_on_ctrl_c_ctrl_c C-c C-c does not evaluate blocks.
Errors: whatever a program writes to stderr, and its exit code when it fails, go to the *Org-Babel Error Output* buffer (shown in a split); the result keeps the standard output only, like org-babel-eval. A missing reference or an inline result that cannot be inserted stops the execution of the buffer.
Running in the background
C-c C-c, <prefix>bb and <prefix>bs never block Neovim: the code runs as a separate process (or in its session) and its result is inserted when it is done; executing the buffer or a subtree still runs the blocks one after the other, in order. Meanwhile:
- A spinner is drawn after the first line of the running block (virtual text, highlight group
OrgBabelRunning; the buffer does not change), with the seconds elapsed after the first one.babel.spinnersets its frames (false: a still "executing…"),babel.spinner_intervalthe milliseconds between them. - What the program prints (standard output and error) shows as it arrives, as virtual lines below the block: a header with the spinner and the seconds elapsed (and "last 10 of 57 lines" once some are hidden), then the last
babel.live_outputlines (default 10;falseor 0 turns this off). Colour codes and control characters are dropped, and after a carriage return only what follows it shows (progress bars). They are virtual text (highlight groupsOrgBabelRunningandOrgBabelOutput): the result inserted when the run ends is the same as without them, and they go away then, or when the run is cancelled or fails. Blocks run as a separate process stream this way (shell, Python, C, ... without:session); session blocks and Lua blocks run inside Neovim show their result only. - You can keep editing. The result follows its block when lines are added or removed above it. Without a placeholder (below), a result is discarded with a warning when its block was changed or deleted during the run.
- With
babel.async = trueevery run first writes a placeholder id as the result, like:asyncsession blocks in Emacs (see Sessions below): the result replaces the placeholder wherever the block is then, even if the block was edited; if the placeholder was deleted, the result is discarded with a warning.:async noon a block (or indefault_header_args) keeps it out. The placeholder and the result are one undo step, when nothing else changed the buffer in between. - <prefix>bC (
:Org babel_cancel) cancels the evaluation at the cursor: its process is killed (with its child processes), or its session sent an interrupt (C-c). A placeholder becomes: [ Babel evaluation cancelled ]; without one the previous result stays as it was. Executing the buffer or a subtree stops there. Not on a running block, it cancels the only running evaluation, or asks which one; with a count, all of them. Unloading (:bwipeout,:bdelete) a buffer cancels its evaluations; quitting Neovim cancels them all. - A program still running after
babel.timeoutms (Emacs has no timeout) is killed the same way, with its child processes, in the background or not: the output so far is the result, and the error output says it timed out (exit code 124).
What needs a value at once still waits for it, as in Emacs, with no spinner or placeholder: export, the blocks a :var reference, a noweb call or :post evaluates, and org-sbe in table formulas. Lua blocks run inside Neovim (unless babel.languages.lua.cmd names an interpreter), so they hold Neovim while they run and cannot be cancelled; so do the few steps of some language ports that wait for a helper tool (LaTeX image conversion, screen).
Hooks are User autocommands: OrgBabelAfterExecute (after a result is inserted; data has bufnr, lang, name, result), OrgBabelTanglePre, OrgBabelTangleBody (the body being tangled is in require("org.babel.tangle").body, which the callback may change), OrgBabelTanglePost (per written file, data.file) and OrgBabelTangleFinished.
Results
A block's result is its value (:results value, the default) or what it prints (:results output). Like Emacs:
- Python, Ruby and JavaScript values are read from their printed form:
[[1,2],None,[3,4]]is a table with a hline,1.0, big integers,True,Nonekeep their spelling, a dict stays text (a table with:results table, akey :: valuelist with:results list),:results verbatim/pp/scalarkeep the text (pprint for pp). - Shell blocks default to their output (
:results valueis the exit status). Unlessoutput,verbatim,raw,org,html,code,pporfileis given, the text is read likeorg-babel-import-elisp-from-file: several lines become a table split at tabs, commas or runs of spaces, numbers are read, one line stays text (echo a bgives: a b,printf 'a\nb\n'a two-row table). - sqlite runs
sqlite3 -csv(-headerwith:colnames yes) and passes:header :echo :bail :csv :column :html :line :list :separator :nullvalue(and:readonly yes) to it. - Lua blocks run inside Neovim (not an external
lualike Emacs): a returned table becomes a table or list,return "a", "b"givesa, b,nilgivesnil. Code runs in the editor process: it can use thevimAPI, butos.exit()or a blocking loop affects Neovim, andbabel.timeoutcannot stop it.printgoes to the result.
Results are inserted after #+RESULTS: like org-babel-insert-result: text as : lines (an example block from babel.min_lines_for_block_output lines), lists as tables (with :results list as a plain list), raw, drawer (:results: ... :end:), org, html, latex, code and :wrap as in Emacs. A paragraph below #+RESULTS: is not part of the result and stays when the result is replaced.
Sessions
:session [name] runs the block in a live interpreter (a REPL) shared by every block with the same language and name (no name = default), so variables, imports, functions and the working directory persist between blocks, like Emacs' comint sessions. Supported: shells (sh, bash, zsh, fish), python, js/node, ruby (irb), R, julia, ocaml, scheme, haskell (ghci), SQL (sqlite3, psql, mysql) and lua (lua sessions keep their globals inside Neovim; what a function from an earlier block prints goes to the block that calls it). Other languages ignore :session with a warning.
- The REPL runs in a terminal buffer named like Emacs:
*shell*,*Python*,*ruby*,*Javascript REPL*,*R*,*julia*,*OCaml*,*scheme*,*ob-haskell*,*SQL*(*lua*for lua) for the default session,*name*for:session name(a name that already has earmuffs is used as is, so:session *Python*is the default python session). <prefix>bz (C-c C-v C-z) shows it; type into it (Insert mode) to use the REPL: what you define there is seen by the next block, and the other way round. A session of another language with the same name gets*name*<2>. - Each evaluation is written to a file and the REPL is sent one line that runs it and prints begin / end-of-evaluation markers (like ob-comint's eoe indicator); the result is what the code printed between them. Shells
.(source) the file, socd, variables and functions stay. python, ruby, node and R define a small helper at start-up that evaluates the file in the REPL's global scope (irb's own binding, so irb locals are shared). julia's helper (loaded withjulia -L) runs the file inMain; the OCaml toplevel reads it with#use(the helpers come from an-initfile, which first#uses your own.ocamlinit); a scheme REPLloads a small program that evaluates the forms one by one in(interaction-environment). julia, ocaml and scheme show the block's code in the REPL buffer before its output. ghci and the SQL clients read a file that prints the markers itself (:script,.read,\i,source). A line half-typed at the prompt is discarded (C-u) before a block is sent. :results valueis the value of the last expression, formatted like Emacs (python uses ob-python's__org_babel_python_format_value; R writes it as a tab-separated table like ob-R; julia writes it with CSV.jl as without a session; ocaml parses the toplevel's lastname : type = valueanswer like ob-ocaml; schemewrites the last form's value; haskell keepsitafter the last line in__LAST_VALUE_IMPROBABLE_NAME__and prints it withshow, quotes removed, like ob-haskell; SQL blocks are tables as without a session, see below), or the returned value (lua); shells use their output unless:results valueis explicit, which gives the exit status.:results outputis what the REPL printed, with stderr merged, prompts and the input echo left out.- The session starts in the block's
:dir. Shells start without their start-up files (bash--norc, zsh-f, fish--no-config) for a predictable prompt; python runspython3 -i(your PYTHONSTARTUP is still loaded), ruby runsirbnext to the configuredruby(a:rubyheader argument is the REPL command itself, like Emacs), js runs a node REPL, R runsRnext to the configuredRscript, julia runsjulia -i --banner=no --color=no --history-file=no(cmd; asession_cmdis used as it is), ocaml runscmd(ocaml, orsession_cmd) and scheme the REPL of its implementation (:scheme, elseimpl): guile (guile --no-auto-compile), chez (scheme), chicken (csi), chibi, gambit (gsi), racket (racket -i) or mit (mit-scheme --quiet), or the commandsession_commandsgives it. One scheme session runs one implementation. haskell runs thecmdofbabel.languages.haskell(ghci). A top-levellet/constin a js session becomesvar, so blocks can be evaluated again. - haskell: a definition of several lines (a type signature and its equations, an indented body) is sent between
:{and:}; code that has:{itself is sent as it is. - SQL (
sqliteblocks, andsqlblocks with no:engineor:engine sqlite,postgresql/postgresormysql/mariadb) keeps one client connected (sqlite3, psql, mysql), so temporary tables, settings and variables last from one block to the next. The block that starts the session gives the connection::db(sqlite3),:dbhost,:dbport,:dbuser,:dbpassword,:databaseand:cmdlinelike the one-shot command line of ob-sql; later blocks only send their code. Each block first sets the output format (sqlite3 CSV with its:colnames,:separator,:nullvalueand format headers; psql unaligned and tab-separated,:colnames nofor no header), so results are tables as without a session. A last statement without;gets one. mysql runs in batch mode (-B --force, with--commandsfor MySQL 9 clients); its:colnames nois read when the session starts. Errors are printed in the result and the session goes on. A:sessionwith another engine is an error. - <prefix>bl (C-c C-v C-l) runs the block in its session and shows it. <prefix>bK kills the session: the interpreter is stopped and its buffer wiped, like killing the session buffer in Emacs; wiping the buffer yourself does the same. When the interpreter exits (
exit()), the next block starts a new one. - Every evaluation runs in the background, so Neovim never blocks (in Emacs only
:asyncevaluations do); requests to one session run in order. Without:async, a result is discarded (with a warning) when its block was edited during the run. Cancelling one (org-babel-async) interrupts the REPL with C-c and drops its result; the session keeps running for the next block. :async(or:async yes) on a session block works like Emacs (org-babel-comint-async):#+RESULTS:gets a placeholder id at once, and the result replaces that placeholder when it arrives, even if the block was edited or moved meanwhile. Deleting the placeholder discards the result.:async no,:session none, export,:varreferences and:results silent/none/append/prependrun without a placeholder; lua sessions finish at once and ignore it.babel.async = truegives every block a placeholder, with a session or not (org-babel-async).
Languages
babel.languages maps a language name to { cmd = "...", ext = "...", default_header_args = {...} }. default_header_args are that language's defaults (Emacs org-babel-default-header-args:LANG). Emacs enables only emacs-lisp (org-babel-load-languages); the plugin enables shells, python, lua, js/ts, ruby, perl, php, R, go, rust, sqlite, sql, C, C++/cpp and D as well, and the ports of org-babel-languages. :python, :ruby and :cmd (js) choose the interpreter of one block, like Emacs.
- emacs-lisp (elisp): run in a separate Emacs,
emacs -Q --batch(babel.emacs_lisp = { command = "emacs", args = { "-Q", "--batch" } }; drop-Qto load your init file), wrapped like ob-emacs-lisp::varvalues are bound as quoted Lisp data,:lexical,:prologueand:epilogueapply, the value is printed withprin1and read back (lists become tables),:results outputcollects whatprinc/printwrite,pp/codeusepp-to-string. That Emacs is not the editor: each evaluation starts a fresh process, so there are no buffers, no state between blocks and no sessions. Without Emacs (command = falseor not installed) side-effect-free code runs on the Lisp interpreter of table formulas (org-table-calc). - python:
:return expr(the value ofexpr),:preamble, and:results graphics file :file x.png(the matplotlib figure is saved). - C, C++ (cpp) and D (ob-C): compiled with gcc / g++ (rdmd for D) and run;
:includes <stdio.h>,:defines N 5,:namespaces std,:flags -O2,:libs -lm,:main no,:cmdline args; table variables become arrays withNAME_rows/NAME_cols(andNAME_h(row, "col")with:colnames yes). - sql (ob-sql):
:engine postgresql|mysql|mssql|sqsh|vertica|monetdb|dbiruns that client with:dbhost :dbport :dbuser :dbpassword :database(:out-file); without:enginethe plugin runs sqlite3 with:db.$namein the body is replaced by:var name(a table becomes a CSV file name). - Value conversion like ob-python / ob-ruby / ob-lua:
hline_tois the text an hline of a table variable becomes (python and lua "None", ruby "nil"; in Neovim's Lua,Noneis nil),None_to(python, lua) andnil_to(ruby) what a None / nil of a list result becomes ("hline"); luamultiple_values_separator(", ") joins several returned values.lua = { cmd = "lua" }(or luajit, ...) runs lua blocks in that interpreter like ob-lua instead of inside Neovim.python = { session_cmd = "ipython -i" }starts sessions with that command as it is (org-babel-python-command-session);session_cmdof julia and ocaml, andscheme = { session_commands = { guile = "guile -q" } }, likewise name the REPL of their sessions. - Shells:
babel.shell_names(org-babel-shell-names: sh bash zsh fish csh ash dash ksh mksh posh) run like sh, as the program of that name;babel.shell_results_defaults_to_output = falsemakes a block without:resultswords give its exit status.
Ports of Emacs ob-LANG.el, enabled by default; each babel.languages entry holds that file's options (named after the Emacs variables, see org-config). Programs that are missing give an error when a block runs. C-c C-v v shows the body as the Emacs expand function makes it. Command lines (a build, a compiled program) run with sh -c when sh is on $PATH, else with 'shell' and 'shellcmdflag' (cmd.exe, PowerShell on Windows); with PowerShell, a line that starts with a quoted program gets the call operator &.
- plantuml: to the
:file(-tpng,-tsvg, ... from its extension;:results verbatimgives the text),:varas!define, @startuml / @enduml added.exec_mode"jar" (java -jarjar_path,:javaoptions) or "plantuml" (executable_path),args({ "-headless" }),svg_text_to_path(inkscape). - ditaa: NAME.png by default (
:file-ext png),.svgwith --svg,.epsand.pdfwith DitaaEps.jar (and epstopdf);exec_mode"jar" (java_exec-jarjar_path) or "ditaa" (exec),:cmdline,:java. - gnuplot:
:file(terminal from its extension,terms),:term,:title,:set '("grid"),:line,:xlabels,:ylabels,:timefmt,:timeind,:missing; a table variable is written to a data file whose name replaces$name.:results outputgives what gnuplot printed. - latex: the body is the result (
:results latex);:varnames are replaced. With:file: .png like LaTeX previews (process_alist.png, latex + dvipng;:buffer nodraws black on transparent), .svg through a PDF andpdf_svg_process(preamble,begin_env,end_env), .pdf with the LaTeX export's compiler (:fit,:border,:pdfheight,:pdfwidth,:headers,:packages), other images with:imagemagick yes(:iminoptions,:imoutoptions), .html withhtlatex, .tikz as it is. - lilypond: engraved to the
:file(png, pdf or eps). Arrange mode (:Org babel_lilypond_toggle_arrange_mode): evaluating a block tangles all lilypond blocks to FILE.ly (:Org babel_lilypond_tangle), engraves it (gen_png,gen_html,gen_pdf,gen_svg,use_eps), then opens the PDF and plays the MIDI file withcommands. Toggles:babel_lilypond_toggle_{arrange_mode,png_generation,html_generation,pdf_generation,pdf_display,midi_play}. - java: the body is wrapped in a class and a main method (
:classname,:imports, apackageline), compiled with javac (:cmpflag) and run with java (:cmdline,:cmdargs);:results valuereturns the value of the main method. Default:results output :dir .. - csharp: a .NET project (
:usings '("System.Text"),:class,:main no,:references,:framework,:nugetconfig) restored, built and run with dotnet. - haskell: sent to ghci (
cmd), or compiled with ghc for:compile yes(:flags,:libs).:Org babel_haskell_export_to_lhsexports the file to FILE.lhs (with a count, runs lhs2tex to FILE.tex). - clojure, clojurescript: babashka, clojure-cli or nbb (
backend, or:backend),:ns,:varasletbindings. - lisp (Common Lisp): evaluated by
cmd(sbcl --script) with*default-pathname-defaults*set to the block's directory (dir_fmt) and:package. - scheme: guile by default (
impl,:scheme chez|chicken|chibi|racket| ...,commands); the value of the last form,:varasdefine. - fortran: compiled with gfortran (
cmd), wrapped inprogram main;:flags,:cmdline,:includes,:defines,:main no. - julia, groovy, ocaml, maxima:
:varand value results like their ob-LANG.el (julia writes the value with CSV.jl and DataFrames.jl; groovy ignores:varlike Emacs; maxima:batch,:graphics-pkg). - processing: HTML running the sketch with processing.js;
:Org babel_processing_view_sketchruns it with processing-java. - screen: the block is pasted into the screen session
:session("default"), started in:terminal(xterm) running:cmd(sh);:Org babel_screen_testchecks the setup. - calc: no program needed; each line runs on a Calc stack (the Calc of table formulas, 12 digits, degrees). A
:varname pushes its value, a line'KEYruns that Calc key on the stack ('+ '- '* '/ '^ '% '\ ': '| 'Bon two values,'n '& 'Q 'L 'E 'S 'C 'T 'A 'F 'R '!on one,'Ppushes pi), another line is a formula whose value is pushed (:varnames replaced). The top of the stack is the result: a matrix gives a table, a vector a row (:results verbatim: the text). - dot (Graphviz):
cmd :cmdline -o :file(:cmdlinedefaults to-Tand the file's extension,:cmdreplacescmd),$NAMEreplaced by:var NAME. The diagrams extension (org-extensions-diagrams) replaces it while it handles dot. - sed:
cmd -f SCRIPT :cmd-line :in-file;:stdin reffeeds a value. - sass:
cmd :cmdline IN OUT; the CSS is the result, or goes to:file. - octave, matlab: the code with
name=value;lines is fed tocmd(octave -q,matlab -nosplash); a value result is written by the wrapper of ob-octave to a file read back as a table; a graphics:fileis printed withprint -dpng. - forth: the lines run in gforth (
cmd);:results outputgives what each line printed, the default the last line's (:session noneis an error like Emacs). - awk:
cmd -f SCRIPT :cmd-line -v NAME='VALUE'... :in-file(cmd"awk"); a table variable is passed tab-separated, a list one element per line;:stdin reffeeds a value the same way. - css, makefile: the body is the result; nothing runs.
- org: the body is raw Org with
$NAMEreplaced by:var NAME;:results latex,htmlorasciigive its body-only export. The defaults are:results raw silentand:exports code, so add:results replaceto insert it.
Header arguments
Header arguments merge like Emacs: babel.default_header_args (inline blocks: default_inline_header_args, #+CALL: the called block's, then default_lob_header_args), the language's default_header_args, the header-args and header-args:LANG properties (the nearest headline that sets one wins; header-args+: adds to the inherited value; #+PROPERTY: applies when no headline sets it), the #+begin_src line, then #+HEADER: lines (the last wins). Lisp in header arguments: like org-babel-read, :var x=(+ 1 2) and the values of :dir, :file, :output-dir, :file-desc, :file-ext, :tangle, :results, :exports, :session, :cmdline, :prologue, :epilogue, :wrap, :shebang, :mkdirp, :eval, :cache, :noweb and :comments that start with ( (:dir (concat (getenv "HOME") "/tmp")) are evaluated: on the Lisp interpreter of table formulas, else in a separate emacs --batch with Org loaded (babel.emacs_lisp). A header value that can't be evaluated is kept as text; a :var form is an error.
| :results | output|value; replace|append|prepend|silent|none|discard; verbatim|scalar|table|vector|list|file; raw|org|drawer|html| latex|code|pp|link|graphics |
| :var | name=value, name="string", name=named-table, name=list, name=table[1,2], name=table[1:3,-1] (0-based ranges and negative indices count every row, the header and hlines included; [,1] = a column). A reference to a src block or #+CALL evaluates it: name=block, name=block(x=1), name=block(1, 2), name=block[:results output](x=1), name=block(x=1)[0]; name=block[] is its body text. Other forms: file.org:name, an ID or CUSTOM_ID (the headline's text), Emacs Lisp literals '(1 2 3) and forms (+ 1 2) (see "Lisp in header arguments" above). Bash gets tables as associative arrays and lists as arrays; sqlite/sql replace $name. |
| :hlines | yes: keep the hlines of table variables (None / nil / hline) |
| :separator | cell separator of tables given to shells (default: tab) |
| :stdin | ref: feed a value to the stdin of a shell block |
| :session | [name]: see Sessions above |
| :colnames | a table variable whose 2nd row is the only hline loses its header row; yes always takes the first row as names and puts them back on a table result of the same width (the default, like Emacs 9.8, does not put them back); no keeps the header as data; '(a b) names the result's columns |
| :rownames | yes: the same for the first column |
| :wrap | [type [params]] wrap the result in #+begin_type (default results), e.g. :wrap src python, :wrap export html; :wrap no inserts the result as it is |
| :cache | yes: store a hash in #+RESULTS[hash]: and reuse the result while the parameters and body are unchanged. The hash is computed like org-babel-sha1-hash, so it matches Emacs (babel.hash_show_time adds the date). Works on #+CALL too. |
| :file | with :results file the result is written to the file (relative to :dir; the directory must exist) and a link is inserted (relative to the Org file); :results file link / graphics only links. :output-dir (created), :file-ext (with #+NAME), :file-mode (identity #o755), :sep (for tables), :file-desc (no value = the file name, [] = none) |
| :dir :cmdline :prologue :epilogue :noweb-ref | supported, with :mkdirp yes (for :dir); the shell of a shell block reads its :cmdline (:cmdline "a 'b c' $HOME" gives three arguments) |
| :noweb | yes|no|tangle|eval|no-export|strip-export|strip-tangle| tangle-eval. Every <<ref>> of a line is expanded (references may contain spaces: <<add(a=3, b=4)>>); blocks sharing a :noweb-ref are joined with :noweb-sep (default a newline); :noweb-prefix no stops repeating the text before the reference. <<name(x=1)>> inserts the result of evaluating the block; <<id>> of a headline with that CUSTOM_ID or ID inserts its text. Blocks in COMMENT subtrees are skipped. |
| :exports | code|results|both|none (for export) |
| :post | name(arg=*this*): run the named block on the result; its result is inserted instead |
| :tangle :comments :padline :shebang :tangle-mode :no-expand | see below |
Switches: -i keeps the indentation of the lines (like src_preserve_indentation, Emacs org-src-preserve-indentation), otherwise the common indentation of a block is removed before it runs; -n / +n number lines and -r / -l "fmt" handle coderefs (always removed before a block runs). Labels are (ref:name) unless a block has -l "fmt" or coderef_label_format sets another default (org-coderef-label-format).
Tangling
:tangle yes|FILE writes a block to a file (yes: the Org file's name with the extension of babel.tangle_lang_exts or the language name, as Emacs: python → .py, sh → .sh, bash → .bash). Like org-babel-tangle:
- the Org buffer is saved first; blocks in COMMENT and :ARCHIVE: subtrees are skipped;
:varassignments,:prologue/:epilogueand noweb references (:noweb yes|tangle) are written;-rremoves coderef labels; unchanged files are not rewritten. :comments link(andyes) wraps each block in[[file:x.org::*Heading][Heading:N]]...Heading:N ends herecomments (N counts the blocks of the entry; a named block uses its name; the link is relative to the tangled file,babel.tangle_use_relative_file_links),:comments orgwrites the Org text before the block as comments,bothdoes both,nowebalso wraps every noweb expansion. The formats arebabel.tangle_comment_format_beg/_end. The Org text of:comments orgloses its common indentation, or goes through the functionbabel.process_comment_text(org-babel-process-comment-text).- an existing target is overwritten in place; with
babel.tangle_remove_file_before_write= true it is deleted and recreated (a symlink is replaced by a file), with "auto" (the default) only when it is read-only, with false never (org-babel-tangle-remove-file-before-write). :padline noremoves the blank line between blocks;:shebanggoes on the first line and makes the file executable;:mkdirp yescreates the directory;:tangle-mode o755,(identity #o755),rwxr-xr-xoru+x(added tobabel.tangle_default_file_mode) set the mode.
From a tangled file:
| :Org tangle_jump | jump to the Org block the cursor is in (org-babel-tangle-jump-to-org) |
| :Org detangle [file] | copy the edited bodies back into the Org blocks (org-babel-detangle; needs link comments) |
| :Org tangle_clean | remove the link comments and noweb references (Emacs 9.8's org-babel-tangle-clean removes nothing because of a bug; this does what its documentation says) |
:Org babel_load_file [file] tangles the lua blocks of an Org file to FILE.lua (again only when the Org file is newer) and runs it with dofile, the Lua counterpart of org-babel-load-file (e.g. an init.org).
Library of Babel and tables
org-sbe works in Emacs Lisp table formulas:
| 2 | 4 |
#+TBLFM: $2='(org-sbe "square" (x $1))
evaluates the block square with x set to the first column ($$1 passes the field as a string, a first string argument holds header arguments).
Export
With babel.evaluate_on_export = true (the default, Emacs org-export-use-babel) exporting first evaluates, in a copy of the buffer, the blocks and #+CALL lines with :exports results|both, inline src blocks and calls, and :exports code|none blocks that use a session; each one is confirmed like any evaluation. :eval never-export|no-export blocks keep their existing results. With false, export uses the #+RESULTS already in the buffer.
The exported code of a block is babel.exp_code_template (org-babel-exp-code-template, default "#+begin_src %lang%switches%header-args\n%body\n#+end_src"), of an inline src block babel.exp_inline_code_template; %lang, %name, %body, %switches, %header-args and %ARG for each header argument (printed like Emacs: %exports gives "code", %var gives (x . 1)) are filled in. babel.exp_call_line_template (default "") is exported in place of #+CALL lines and call_ objects, with %line for the call, e.g. "\n: call: %line". Results with ten or more lines use #+BEGIN_EXAMPLE with babel.uppercase_example_markers (org-babel-uppercase-example-markers).
<prefix>' (C-c ') also edits, like org-edit-special: example, export and comment blocks, LaTeX environments, : fixed-width areas, the body of an inline src block (kept on one line), the definition of the footnote at the cursor (inline definitions cannot contain blank lines), a LaTeX fragment ($x$, \(x\), \[x\]); it visits the file of an INCLUDE, SETUPFILE or BIBLIOGRAPHY keyword, runs deadline / schedule on a planning line and the date prompt on a timestamp, and follows a link. Elsewhere: "No special environment to edit here".
:w refuses conflicting edits to the source. Review both versions and use :w! to overwrite an intact tracked region, or :wq! to overwrite and close. Deleted or wholly replaced regions and wiped source buffers cannot be forced; copy the edit contents manually to the intended location. Example editing honors -i, src_preserve_indentation, and edit_src_content_indentation.
Edit buffers, like Emacs' org-src buffers:
- the winbar says "Edit, then exit with ‘<C-c>'’ or abort with ‘<C-c><C-k>’" (the first
mappings.edit_srckeys;edit_src_persistent_message = falsehides it). - <prefix>' on a region that already has an edit buffer asks "Return to existing edit buffer ([n] will revert changes)?": yes shows it again, no discards it and opens a new one. With
src_ask_before_returning_to_edit_buffer = falseit goes back at once.:Org edit_src_continuegoes back without asking to the edit buffer of the region at the cursor (org-edit-src-continue, Emacs' mouse-1 on it). edit_src_auto_save_idle_delay = Nwrites the edit buffer back to the Org buffer after N seconds without changes (0: never).edit_src_turn_on_auto_save = truesaves its contents, when idle ('updatetime'), toorg-src-XXXXXX-%Y-%d-%m.txtnext to the Org file, like Emacs' auto-save; the file is left there, as in Emacs.- the filetype comes from
src_lang_modes(org-src-lang-modes:C→c,elisp→lisp, the shells →sh, ...), else from the language's extension; the same table picks the syntax used to highlight blocks.:areas getedit_fixed_width_region_mode(a filetype or a function of the buffer; none by default). - the edit buffer of a block with a
:sessionis associated with it (org-src-associate-babel-session):mappings.edit_src.send_to_session(<C-c><C-c>, <prefix>e) sends the buffer, or in Visual mode the selected lines, to the session (started when needed) and shows it.
The body of a src block is highlighted in its language, like Emacs' org-src-fontify-natively. When Neovim has a tree-sitter parser and a highlights query for the language (Neovim bundles c, lua, markdown, query, vim and vimdoc; nvim-treesitter or treesitter-parsers add more), the body is drawn with tree-sitter's captures, the @keyword.lua, @string.c, ... groups Neovim uses for a buffer of that language, so it looks the same as in a file of that language and your colorscheme's tree-sitter colors apply. Injected languages are highlighted too (the inline markup of a markdown block, Vim script in a Lua vim.cmd() string) in blocks of up to 1,000 lines. Only the blocks on screen are parsed, each once for its text: moving around or editing elsewhere doesn't parse a block again; a longer block is parsed again from the tree it had after an edit in it. Other languages get their Vim syntax (syntax/<lang>.vim) included into the buffer's syntax. The language name goes through src_lang_modes first (elisp → lisp, shell → sh → the bash parser). ui.src_highlight_engine chooses: "auto" (the default), "treesitter" (languages without a parser stay plain) or "syntax" (always the Vim syntax); ui.src_highlight = false turns both off. A parser installed while the file is open is used after <C-c><C-c> on a #+ line (which refreshes the buffer's setup) or when the file is opened again. As in Emacs, a block shows its text as typed: the Vim syntax of json and markdown blocks is included without its concealing (g:vim_json_conceal, g:markdown_syntax_conceal stay as you set them for your own files). TAB on a line of a src block (src_tab_acts_natively, default true) indents it for its language, like a round trip through the edit buffer: the body gets the block's content indentation and the line the indentation that the filetype's 'indentexpr' (or 'cindent') computes, or that of the line above when the filetype has none. :Org escape_code_in_region / unescape_code_in_region add or remove the comma that protects lines starting with * or #+ in the selected lines (org-escape-code-in-region).
Not supported
- emacs-lisp sessions, and emacs-lisp code that acts on the editor (buffers, windows, the Org document): it runs in a separate Emacs (see Languages above).
- Header values in Lisp run without your Emacs session: functions and variables you defined there don't exist (see "Lisp in header arguments"), and without an Emacs executable only the forms the table formula interpreter knows are evaluated.
org-babel-load-filefor Emacs Lisp, and Emacs hook functions (hooks areUserautocommands instead).:results xmp(Ruby rcodetools), Indium js sessions, SQL sessions of engines other than sqlite3, PostgreSQL and MySQL, and:dbconnection(Emacs'sql-connection-alist).- Attachment links for
:fileresults inside the attachment directory (attachment:links) and:dir 'attach.