docs/manual/guide/11-code-blocks.org

b6a348930a231ab1ffd793a69f2d512f8b60bad8
orgstar/docs/manual/guide/11-code-blocks.org

890 lines · 72551 bytes

  1#+TITLE: Code blocks
  2#+DESCRIPTION: Source blocks in orgstar: highlighting, editing, running with Babel, results, header arguments, noweb and tangling.
  3#+LEDE: orgstar runs and tangles source blocks the way Org Babel does, and refuses anything it would run differently.
  4
  5* Source blocks
  6
  7A source block holds code in a named language:
  8
  9#+BEGIN_SRC org
 10,#+begin_src python
 11return 6 * 7
 12,#+end_src
 13#+END_SRC
 14
 15orgstar reads the same syntax Org does: the language after =#+begin_src=, then any switches such as =-i= or =-r=, then header arguments. A =#+NAME:= line above a block names it, so other blocks, =#+CALL:= lines and =:var= references can refer to it.
 16
 17Lines inside a block that start with =*= or =#+= are protected with a leading comma, as Org does (=org-escape-code-in-region=). The comma is removed when the block runs, tangles or exports, and when you edit the block apart.
 18
 19** Syntax highlighting
 20
 21The code in a block is highlighted in the editor on the Mac and on iOS, in the iOS reader, and in the Mac's block editor, in the theme's =syntax-*= colours. Highlighting uses tree-sitter grammars for these language names:
 22
 23| Language names                  | Grammar    |
 24|---------------------------------+------------|
 25| =sh=, =bash=, =shell=, =zsh=    | Bash       |
 26| =python=, =python3=, =py=       | Python     |
 27| =emacs-lisp=, =elisp=           | Emacs Lisp |
 28| =c=                             | C          |
 29| =c++=, =cpp=                    | C++        |
 30| =r=                             | R          |
 31| =js=, =javascript=, =node=      | JavaScript |
 32| =java=                          | Java       |
 33| =scheme=                        | Scheme     |
 34| =clojure=, =clj=                | Clojure    |
 35| =haskell=                       | Haskell    |
 36| =rust=                          | Rust       |
 37| =go=                            | Go         |
 38| =ruby=                          | Ruby       |
 39| =json=                          | JSON       |
 40| =yaml=, =yml=                   | YAML       |
 41| =toml=, =conf-toml=             | TOML       |
 42| =lua=                           | Lua        |
 43
 44Names are matched without regard to case. Blocks in any other language show as plain monospaced text.
 45
 46* Editing a block apart
 47
 48=org-edit-special= edits a block's contents in a separate editor. Put the caret in a =src=, =example= or =export= block (or on a =#+TBLFM:= line; see [[file:10-tables.org][Tables]]) and run *Edit Block*.
 49
 50| Preset | Key                       |
 51|--------+---------------------------|
 52| Emacs  | =C-c '=                   |
 53| Doom   | =C-c '=, or =SPC m '= in normal state |
 54| Mac    | =⌃⌘'=                     |
 55
 56On the Mac the block opens in a sheet titled with the block's kind and language, with the same highlighting as the main editor. The protecting commas are removed while you edit and added back when you save.
 57
 58| Action | Keys                                 |
 59|--------+--------------------------------------|
 60| Save   | =C-c '= or ⌘Return, or *Save Block*  |
 61| Leave  | =C-c C-k= or Escape, or *Cancel*     |
 62
 63If the block changed in the main editor while you edited it, the edit is not saved and the message area says so.
 64
 65On iOS the block opens in a plain text sheet with Cancel and Save buttons.
 66
 67* Running a block
 68
 69=C-c C-c= in a source block runs it (=org-babel-execute-src-block=) and writes its result under it. The same command runs a =#+CALL:= line or an inline =src_= block when the caret is on one.
 70
 71| Preset | Key                                                  |
 72|--------+------------------------------------------------------|
 73| Emacs  | =C-c C-c=                                            |
 74| Doom   | =C-c C-c= in normal, insert and visual state         |
 75| Mac    | =⌃⌘X=                                                |
 76
 77The program runs in the folder of the file, or in =:dir=. It reads the code on standard input. While it runs, the message area shows "Running /language/ block…"; when it ends, it shows "Code block evaluation complete." or the problem.
 78
 79If the program writes to standard error or exits with a non-zero status, the message area shows the exit status and the first line of standard error. The result is still inserted, as Emacs does.
 80
 81The block's text is remembered when the run starts. If you edit the block while it runs, so it can no longer be found, the result is not written.
 82
 83** Languages that run
 84
 85On the Mac, orgstar starts each interpreter outside a =:session= through =/bin/sh=, as Org does, with standard input read from a file. Because an app opened from the Dock does not see your shell's =PATH=, orgstar adds =/opt/homebrew/bin=, =/usr/local/bin=, =/Library/TeX/texbin=, =/usr/bin= and =/bin= to the end of it.
 86
 87| Language                                                         | Program run                                         |
 88|------------------------------------------------------------------+-----------------------------------------------------|
 89| =sh=, =bash=, =zsh=, =fish=, =ksh=, =dash=, =ash=, =csh=, =mksh=, =posh= | The shell of that name                         |
 90| =shell=                                                          | The shell in =SHELL=, or =/bin/sh=                  |
 91| =python=                                                         | =python3=, or the program in =:python=              |
 92| =emacs-lisp=, =elisp=                                            | =emacs -Q --batch=, or the interpreter; see below    |
 93| =ruby=                                                           | =ruby=, or the program in =:ruby=                   |
 94| =js=, =javascript=                                               | =node FILE=, the program written to a file, or JavaScriptCore without node; see below |
 95| =R=                                                              | =Rscript -=                                         |
 96| =awk=                                                            | =awk -f=, the program written to a file             |
 97| =calc=                                                           | orgstar's Calc, or =emacs -Q --batch=; see below    |
 98| =sqlite=                                                         | =sqlite3=, or the SQLite library without it; see below |
 99| =dot=, =plantuml=, =mermaid=                                     | =dot=, =plantuml=, =mmdc=; =dot= and =mermaid= built in without them; see Graphics below |
100| =C=, =C++=, =cpp=, =D=, =java=, =fortran=, =clojure=             | A compiler, or =bb= or =clojure=; see Compiled languages below |
101
102For =js=, =javascript= and =R=, =:cmd= names a different program. Since it runs through =/bin/sh=, a program in =:cmd=, =:python= or =:ruby= can be given with options, such as =:cmd "node --no-warnings"= or =:python "python3 -X utf8"=, or with =~= or a variable, such as =:cmd "~/bin/node"=. =awk= takes =:cmd-line= arguments after its program, and =:in-file= as the file it reads.
103
104Any other language is refused with "No way to run /language/ blocks yet."
105
106A run that takes longer than five minutes is stopped. Runs in a =:session= have no time limit, except in JavaScriptCore and Pyodide.
107
108The [[file:../install.org][Mac App Store version]] starts no programs, so only Emacs Lisp, JavaScript, Python, calc, sqlite, dot and mermaid blocks run there; see /In the Mac App Store version/ below.
109
110** JavaScript in JavaScriptCore
111
112In the Mac App Store version and on iOS, =js= and =javascript= blocks run in JavaScriptCore, the JavaScript engine built into macOS and iOS. The download version uses it when =node=, or the program in =:cmd= after =/bin/sh= expands it, isn't installed; a =:cmd= with options, such as =node --no-warnings=, or with a command substitution, such as =$(which node)=, never runs in JavaScriptCore. A block runs as Emacs runs it, with =node= reading it from a file as a CommonJS module, where =this= is =module.exports= and top-level =var= declarations stay in the block. Its output and result are what node gives:
113
114- =console.log=, =console.info= and =console.debug= write to the output, =console.warn= and =console.error= to the error output, and =console.dir= prints with =util.inspect=. =process.stdout.write= and =process.stderr.write= write text.
115- =require('util')= has =inspect=, =format= and =formatWithOptions=, which print values as Node 26 prints them. =require('process')= has =stdout= and =stderr=.
116- =setTimeout=, =setInterval=, their =clear= functions and =queueMicrotask= work. Timers run after the program, in the order node runs them, and the run ends when none is left. In a =:session=, a block that leaves a timer set, or whose promise callbacks print or throw, is refused, since node's session returns before they run and they print later.
117- An uncaught error ends the run with status 1 and writes its name and message to the error output, such as "ReferenceError: hline is not defined".
118- =require= of any other module fails as it does for a module node can't find: "Error: Cannot find module 'fs'".
119
120A block that uses something only node has fails with "This block uses /name/, which runs only in node.", rather than giving a different result. That covers other members of =process=, =util=, =console=, =require= and =module= (=process.env=, =console.table=, =require.resolve=, =module.id=) and listing their members; Node's other globals (=Buffer=, =fetch=, =URL=, =TextEncoder=, =setImmediate=, =structuredClone=, =SharedArrayBuffer=, =Temporal=, =ReadableStream=); top-level =await=, =import= or =export= statements, which node runs as an ES module, and =import()=; =__filename= and =__dirname=, which name Emacs's temporary file; listing the global object's properties with =Object.getOwnPropertyNames= or =Reflect.ownKeys=, and in a =:session= with =Object.keys= or =for…in=; the source text of a built-in function; an error's =stack=, =Error.stackTraceLimit=, =Error.captureStackTrace= and listing an error's own properties; and printing an =Error=, a =Promise=, an iterator or the global object with =util.inspect=, whose text in node comes from its own engine. There is no access to files, the network or other programs.
121
122Some things still differ from node:
123
124- Error messages written by the engine itself, such as a =TypeError='s, are JavaScriptCore's, as a block that prints =e.message= shows. Only an uncaught =ReferenceError= is written in node's words.
125- A promise rejection nothing handles is not reported, and the run does not stop for it.
126- =:cmd= is ignored.
127
128JavaScriptCore has no way to stop a running program. A block that is canceled, or stopped after five minutes, ends at once, but if its program never finishes it keeps running in the background, on one processor core, until orgstar quits. Cancelling a block in a =:session= discards the session.
129
130** Python in Pyodide
131
132In the Mac App Store version and on iOS, =python= blocks run in Pyodide 314.0.8, which is CPython 3.14 compiled to WebAssembly, built into the app and run in a hidden web view. The download version always runs =python3=. A block runs as Emacs runs it with =python3=, with the same results, output and error output: the body as a function whose =return= value is the result, or with =:results output= what it prints, and with =:session= at top level, where the value is the last expression's. An uncaught error writes its traceback to the error output; outside a session the run ends with status 1, as =python3= does.
133
134What differs from =python3=:
135
136- Only the standard library is there. =numpy=, =matplotlib= and other packages are not, and orgstar doesn't install them: =import numpy= fails with =ModuleNotFoundError=. Loading a package from the network with =pyodide_js.loadPackage= and its URL works, but isn't supported. A block with =:results graphics= fails with "Python blocks can't draw graphics in this version of orgstar: matplotlib isn't included." A =:file= result that is the block's value or output is written as for any other language.
137- The block can reach the network, as a web page can: =urllib.request=, =js.fetch= and =pyodide.http= work.
138- The block can't see your files or start programs. It runs in Pyodide's own file system, in =/home/pyodide=, and files it writes there are not kept. =:dir= must name a folder that exists, but the block doesn't run in it. =input()= reads nothing.
139- =:python= is ignored.
140- Every block runs in one interpreter. A block without a session gets its own variables, but modules it imports stay loaded, with any changes it made to them, until Pyodide is unloaded. A session keeps its variables until then too.
141- Pyodide loads with the first python block, which takes a second or two, and is unloaded after a minute without a python block, or 15 minutes while a session has variables. A block that is canceled, or stopped after five minutes, stops at once and ends every session.
142
143** Compiled languages
144
145On the Mac, =C=, =C++=, =cpp=, =D=, =java=, =fortran= and =clojure= blocks run as Org's =ob-C=, =ob-java=, =ob-fortran= and =ob-clojure= run them. orgstar writes the body, expanded as tangling writes it (see Tangling below), to a source file in a temporary folder, compiles it and runs the program in the file's folder or =:dir=, with a newline on standard input. What the compiler prints is dropped.
146
147| Language        | Commands                                                                         |
148|-----------------+----------------------------------------------------------------------------------|
149| =C=             | =gcc -o bin FLAGS src LIBS=, then =bin CMDLINE=                                  |
150| =C++=, =cpp=    | =g++ -o bin FLAGS src LIBS=, then =bin CMDLINE=                                  |
151| =D=             | =rdmd FLAGS src CMDLINE=, which compiles and runs                                |
152| =fortran=       | =gfortran -o bin FLAGS src=, then =bin CMDLINE=                                  |
153| =java=          | =javac CMPFLAG Class.java=, then =java -cp dir CMDLINE Class CMDARGS=            |
154| =clojure=       | =bb src= (babashka) when =bb= is installed, otherwise =clojure -M src=           |
155
156FLAGS is =:flags=, LIBS is =:libs= or the inherited =LIBS= property, and CMDLINE is =:cmdline=. A Lisp list works for =:flags= and =:libs=; its items are joined with spaces.
157
158| Argument            | Languages             | Effect                                                                                  |
159|---------------------+-----------------------+-----------------------------------------------------------------------------------------|
160| =:flags=            | C, C++, D, Fortran    | Compiler options.                                                                       |
161| =:libs=             | C, C++                | Libraries, after the source file, such as =-lm=.                                        |
162| =:cmdline=          | C, C++, D, Fortran    | The program's arguments.                                                                |
163| =:cmdline=          | Java                  | Options for =java=, before the class name.                                              |
164| =:cmdargs=          | Java                  | The program's arguments.                                                                |
165| =:cmpflag=          | Java                  | Options for =javac=.                                                                    |
166| =:javac=, =:java=   | Java                  | The compiler and runtime commands, with options; =javac= and =java= by default.         |
167| =:classname=        | Java                  | The class to run; a dotted name gives its package.                                      |
168| =:backend=          | Clojure               | =babashka= runs =bb=, =clojure-cli= runs =clojure -M=.                                  |
169| =:includes=, =:defines=, =:namespaces=, =:imports=, =:main=, =:prologue=, =:epilogue=, =:ns=, =:var= | as for tangling | What the expansion writes; see Tangling below. |
170
171When =:imports= is absent, a D block reads the =IMPORTS= property where it is, and a Fortran block without =:includes= or =:defines= reads the =INCLUDES= and =DEFINES= properties, as Org does when it runs them. =:session= is ignored for these languages, as in Org.
172
173Java's defaults are =:results output= and =:dir .= (=org-babel-default-header-args:java=). The =.java= and =.class= files are written in the folder the block runs in, under folders for the class's package (=org/ex/Hello.java= for =:classname org.ex.Hello=), and are left there. The class is =:classname=, the body's own class with its =package=, or =Main=.
174
175Any other Clojure backend is refused: "The cider backend for clojure needs Emacs; orgstar runs babashka or clojure-cli."
176
177Before a run, orgstar checks that each program it needs is on the =PATH= described above. If not, the block fails with "gcc isn't installed, so C blocks can't run." (=g++= for C++, =rdmd=, =gfortran=, or the commands =:javac= and =:java= name). For Clojure without a =:backend=, the message is "Neither bb nor clojure is installed, so clojure blocks can't run."
178
179** The trust prompt
180
181Before a block runs, orgstar asks "Run this /language/ block? (yes, no, always)", as =org-confirm-babel-evaluate= does.
182
183- =yes= runs it this once.
184- =no= does not run it.
185- =always= runs it and remembers the block, so it runs without asking next time.
186
187A remembered block is identified by the file's path and the exact text of the block. Any change to the block, or moving the file, makes orgstar ask again. The remembered hashes are kept in =trusted.json= in orgstar's Application Support folder (=~/Library/Application Support/Orgstar= on the Mac, inside the container in the Mac App Store version). The same file records table formulas you allowed to run Lisp. To forget every choice, delete the file while orgstar is not running.
188
189When a block's =:var= or =:stdin= refers to other blocks that have to run first, you are asked once for all of them. The prompt covers the block you ran and every block its references reach. If any of those blocks changes while the chain runs, orgstar stops with "The blocks changed while running; nothing more was run."
190
191** =:eval=
192
193| Value                                    | Effect                                                     |
194|------------------------------------------+------------------------------------------------------------|
195| =never=, =no=                            | The block does not run: "Evaluation of this /language/ code block is disabled." |
196| =query=                                  | Asks every time, with only =yes= and =no=. A block reached through =:var= with =:eval query= makes the whole chain ask every time. |
197| anything else, or absent                 | Runs after the trust prompt.                                |
198
199=never-export= and =no-export= only stop evaluation during export in Org. orgstar does not run blocks during export, so with these values the block runs from =C-c C-c= like any other.
200
201** Cancelling a run
202
203On the Mac, Edit ▸ Cancel Running Task (⌘.) stops the running block. Its result is not inserted, and the message area shows "Code block canceled." The same command stops an export or table recalculation running in Emacs (see [[file:12-export.org][Export]] and [[file:10-tables.org][Tables]]). With nothing running it shows "Nothing is running". The command is also in the command palette.
204
205Only one block runs at a time. Starting another block cancels the one that is running.
206
207Cancelling a block that runs in a =:session= stops the session's interpreter, so the session's state is lost. The next block in that session starts a new one.
208
209The iOS app has no cancel command.
210
211* Results
212
213The result is written after a =#+RESULTS:= line below the block (=org-babel-insert-result=). Running again replaces it. A named block's result goes under =#+RESULTS: name=, wherever that line is in the file. An unnamed block's result is the =#+RESULTS:= line right after it, past blank lines. The result keeps the block's indentation, so a block inside a list item keeps its result inside the item.
214
215#+BEGIN_SRC org
216,#+begin_src sh
217echo hello
218,#+end_src
219
220,#+RESULTS:
221: hello
222#+END_SRC
223
224By default a result is shaped like this:
225
226- Text of fewer than ten lines gets a =: = prefix on each line.
227- Text of ten lines or more goes in an =#+begin_example= block.
228- A table becomes an aligned Org table.
229
230** Value or output
231
232| Word     | Result                                                                                                  |
233|----------+---------------------------------------------------------------------------------------------------------|
234| =value=  | The value of the block. This is the default.                                                           |
235| =output= | Everything the program printed on standard output.                                                     |
236
237What "value" means depends on the language:
238
239| Language                | Value                                                                                         |
240|-------------------------+-----------------------------------------------------------------------------------------------|
241| Shells, by default      | Standard output, read as a table: tab-separated columns, then comma-separated, then space-separated; a single field is a plain value. |
242| Shells, =:results value= written out | The exit status of the last command.                                             |
243| Python                  | What the block returns. The body runs as a function, so it needs =return=. =:return expr= adds a final =return expr=. |
244| Python in a =:session=  | The value of the last expression.                                                             |
245| =ruby=, =js= in a =:session= | The value of the last expression, read as without a session.                            |
246| Emacs Lisp              | The value of the last form.                                                                   |
247| =ruby=                  | The value of the body, run as a lambda; strings as they are, other values as =inspect= prints them, arrays read as tables with =nil= rows as rules. =:results pp= prints it with =pp=. |
248| =js=, =javascript=      | What the body returns, as =util.inspect= prints it (in JavaScriptCore, orgstar's copy of it), arrays read as tables; it runs as a function, so it needs =return=. |
249| =awk=                   | Standard output, read as a table as for shells.                                               |
250| =R=                     | Standard output, always.                                                                      |
251| C, C++, D               | Standard output without its common indentation, read as a table as for shells.                |
252| Fortran                 | The same, with blank space around the output trimmed.                                         |
253| Java                    | With =:results value=, what the body returns; it runs as =main=, so it needs =return=. Lists and arrays become tables, with =null= rows as rules, and a returned string is written without its quotes. Java's default is =:results output=. |
254| Clojure                 | The value of the last form as Clojure prints it. A number, or a string without its quotes, is written as that; vectors, lists and maps are written as printed, not as tables. |
255
256Python lists of lists become tables, with =None= rows as rules. A flat list becomes a one-row table. Emacs Lisp lists become tables the same way, with =hline= for rules. Numbers are written the way Emacs prints them.
257
258** Result types
259
260| Word                 | Effect                                                                     |
261|----------------------+----------------------------------------------------------------------------|
262| =table=, =vector=    | Read the result as a table. This is the default for values.                |
263| =list=               | Write a plain list, one =- = item per line or per element.                 |
264| =scalar=, =verbatim= | Write the result as text without reading it as a table.                    |
265| =file=               | Write a link to a file (see Results in files below).                       |
266
267=:results verbatim= on an Emacs Lisp value writes it as =prin1= would, with quotes around strings.
268
269With =:results output list=, the list made from the output is written as an example, in lines such as =: - a=, as Org writes it:
270
271#+BEGIN_SRC org
272,#+begin_src sh :results output list
273printf 'a\nb\n'
274,#+end_src
275
276,#+RESULTS:
277: - a
278: - b
279#+END_SRC
280
281** Result formats
282
283| Word     | Written as                                                     |
284|----------+----------------------------------------------------------------|
285| =raw=    | The text as it is, so Org markup in it takes effect.           |
286| =drawer= | Between =:results:= and =:end:=.                                |
287| =code=   | In a =#+begin_src= block of the block's language.               |
288| =org=    | In a =#+begin_src org= block.                                   |
289| =html=   | In a =#+begin_export html= block.                               |
290| =latex=  | In a =#+begin_export latex= block.                              |
291| =pp=     | Python: formatted with =pprint=; written as text.               |
292
293Lines that start with =*= or =#+= inside =code=, =org=, =html= and =latex= results are comma-protected.
294
295** Inserting
296
297| Word      | Effect                                                         |
298|-----------+----------------------------------------------------------------|
299| =replace= | Replace the previous result. This is the default.             |
300| =append=  | Add after the previous result.                                 |
301| =prepend= | Add before the previous result.                                |
302| =silent=  | Show the output in the message area and write nothing.         |
303| =none=, =discard= | Write nothing.                                         |
304
305Words from different groups combine: =:results output list append=. A later word replaces an earlier one from the same group.
306
307** =:wrap=
308
309=:wrap= puts the result in a block, ahead of any format word.
310
311| Value               | Wrapped in                                         |
312|---------------------+----------------------------------------------------|
313| =:wrap= alone       | =#+begin_results= … =#+end_results=                 |
314| =:wrap example=     | =#+begin_example= … =#+end_example=                 |
315| =:wrap src python=  | =#+begin_src python= … =#+end_src=                  |
316| =:wrap export html= | =#+begin_export html= … =#+end_export=              |
317| =:wrap no=, =:wrap nil= | No wrapping                                    |
318
319Inside =example=, =src= and =export= wrappers, lines starting with =*= or =#+= are comma-protected.
320
321** Results in files
322
323With =:results file=, the result is a link instead of text.
324
325| Header        | Effect                                                                                     |
326|---------------+--------------------------------------------------------------------------------------------|
327| =:file name=  | Write the result into =name= and link to it. Without =:results file=, =:file= has no effect, except in graphics blocks. |
328| =:output-dir dir= | Put =:file= under =dir=. The folder must exist.                                        |
329| =:file-desc text= | Give the link a description: =[[file:name][text]]=. An empty =:file-desc= uses the file name. |
330
331A relative =:file= is written in the folder the block ran in: the file's folder, or =:dir=. Without =:file=, =:results file= takes the result itself as the path to link to.
332
333#+BEGIN_SRC org
334,#+begin_src sh :results file :file out.txt :file-desc Output
335echo hello
336,#+end_src
337
338,#+RESULTS:
339[[file:out.txt][Output]]
340#+END_SRC
341
342* Header arguments
343
344** Where they come from
345
346orgstar merges header arguments in this order, each layer overriding the ones before it (=org-babel-get-src-block-info=):
347
3481. =#+PROPERTY: header-args …= in the file, then =header-args= properties of the block's headings, from the outermost heading inwards.
3492. =header-args:LANG= the same way, for blocks in language =LANG=.
3503. The arguments on the =#+begin_src= line.
3514. =#+HEADER:= lines above the block.
3525. For a call, the call's arguments (see Calls below).
353
354A property written with a =+=, such as =header-args+=, adds to the value inherited from above instead of replacing it. In a property drawer, =:header-args:sh:= is one property name, so its value applies only to =sh= blocks.
355
356#+BEGIN_SRC org
357,#+PROPERTY: header-args :results output
358
359,* Scripts
360:PROPERTIES:
361:header-args:sh: :dir /tmp
362:END:
363
364,#+HEADER: :results verbatim
365,#+begin_src sh :var name="world"
366echo "hello $name"
367,#+end_src
368#+END_SRC
369
370Without any of these, a block has =:results replace=, =:exports code=, =:session none=, =:cache no=, =:noweb no=, =:hlines no= and =:tangle no=. An inline =src_= block defaults to =:exports results= and =:hlines yes=.
371
372** Lisp in header values
373
374A header value that starts with =(=, ='=, =`= or =[= and is not in quotes is Lisp, as in =org-babel-read=. orgstar evaluates it with its own Emacs Lisp interpreter, which also knows =buffer-file-name=, =default-directory=, =system-type= and the functions =expand-file-name=, =file-name-directory=, =file-name-nondirectory=, =file-name-sans-extension= and =file-name-as-directory=.
375
376#+BEGIN_SRC org
377,#+begin_src sh :dir (concat "/" "usr") :results output
378pwd
379,#+end_src
380#+END_SRC
381
382A string or number takes the place of the form. Lisp that the interpreter cannot evaluate is refused where it matters: for =:var= ("is Lisp that only Emacs can evaluate"), =:colnames= and =:rownames=, and any header of a =:cache yes= block.
383
384** Header argument reference
385
386| Argument          | Values                                         | Effect                                                                                     |
387|-------------------+------------------------------------------------+--------------------------------------------------------------------------------------------|
388| =:results=        | see Results above                              | How the result is collected, shaped and inserted.                                          |
389| =:wrap=           | block type and parameters                      | Wraps the result in a block.                                                               |
390| =:file=           | file name                                      | Where a file result goes; required for graphics.                                           |
391| =:output-dir=     | folder                                         | Folder for =:file=.                                                                        |
392| =:file-desc=      | text                                           | Description of a file result's link.                                                       |
393| =:var=            | =name=value=                                   | Passes a value in (see Variables below).                                                   |
394| =:colnames=       | =yes=, =no=, Lisp list                         | Header row of table variables (see Tables in variables below).                             |
395| =:rownames=       | =yes=, =no=, Lisp list                         | First column of table variables.                                                           |
396| =:hlines=         | =yes=, =no=                                    | Keep rules in table variables.                                                             |
397| =:separator=      | text                                           | Column separator for tables in shell variables; a tab by default.                          |
398| =:hline-string=   | text                                           | What a rule becomes in a shell variable with =:hlines yes=; =hline= by default.            |
399| =:dir=            | folder                                         | Folder to run in, relative to the file's folder. It must exist.                            |
400| =:session=        | name, =none=                                   | Runs in a long-lived interpreter (see Sessions below). Shells, Python, =ruby=, =js= and =R=; ignored for the compiled languages. |
401| =:stdin=          | name of a table, list or block                 | Feeds the value to standard input. Shells only.                                            |
402| =:cmdline=        | arguments                                      | Command-line arguments. Shells, =dot=, =plantuml=, =mermaid= and the compiled languages only. |
403| =:shebang=        | =#!…= line                                     | Runs the block as a script with this first line. Shells only; also used by tangling.       |
404| =:padline=        | =no=                                           | No blank line after the shebang of a script, or between tangled blocks.                    |
405| =:python=         | program                                        | Python interpreter to use.                                                                 |
406| =:cmd=            | program                                        | Interpreter for =js=, =javascript= and =R=; =:ruby= for =ruby=.                           |
407| =:cmd-line=, =:in-file= | arguments, file                          | =awk=: arguments after the program, and the file it reads.                                 |
408| =:return=         | expression                                     | Python: the value to return.                                                               |
409| =:cache=          | =yes=, =no=                                    | Skip the run when the result is current (see Caching below).                               |
410| =:eval=           | =never=, =no=, =query=, …                      | Whether and how to ask before running (see =:eval= above).                                 |
411| =:post=           | =name(arg=*this*)=                             | Passes the result through another block (see Post-processing below).                       |
412| =:noweb=          | see Noweb below                                | Expands =<<name>>= references.                                                             |
413| =:noweb-ref=      | name                                           | Makes the block part of =<<name>>=.                                                        |
414| =:noweb-sep=      | text                                           | Separator between blocks joined under one =:noweb-ref=; a newline by default.             |
415| =:noweb-prefix=   | =no=                                           | Do not repeat the text before =<<name>>= on each expanded line.                            |
416| =:exports=        | =code=, =results=, =both=, =none=              | What export shows (see [[file:12-export.org][Export]]).                                  |
417| =:tangle=         | see Tangling below                             | Where tangling writes the block.                                                           |
418
419** Arguments that are refused
420
421orgstar does not run a block whose arguments it would handle differently from Emacs. Instead it says why and runs nothing.
422
423| Argument                    | Refused for                                     | Message                                                  |
424|-----------------------------+-------------------------------------------------+----------------------------------------------------------|
425| =:prologue=, =:epilogue=    | graphics (=dot=, =plantuml=, =mermaid=)           | "=:prologue= isn't supported yet; nothing was run."      |
426| =:stdin=, =:shebang=        | languages other than shells                     | "=:stdin= isn't supported yet; nothing was run."         |
427| =:cmdline=                  | languages other than shells, graphics and the compiled languages | "=:cmdline= isn't supported for /language/ yet; nothing was run." |
428| =:session=                  | =awk=, =calc=, =sqlite=, graphics and Emacs Lisp; the compiled languages ignore it | "=:session= isn't supported for /language/ yet; nothing was run." |
429
430* Variables
431
432=:var name=value= passes a value into the block (=org-babel-ref-resolve=). One =:var= can hold several assignments separated by spaces, and you can repeat =:var=. A later assignment to the same name replaces an earlier one.
433
434| Value                          | Meaning                                                                         |
435|--------------------------------+---------------------------------------------------------------------------------|
436| =5=, =2.5=                     | A number.                                                                       |
437| ="two words"=                  | A string. =\n= and =\t= in it are a newline and a tab.                          |
438| ='(1 2)=, =(+ 1 2)=, ='((1 2) hline (3 4))= | Lisp: evaluated to a string, number, list or table.               |
439| =tbl=                          | The table or plain list under =#+NAME: tbl= in the same file.                   |
440| =gen=                          | The result of the source block named =gen=, which runs first.                   |
441| =double(n=4)=                  | The result of the block named =double=, run with =n= set to 4.                  |
442
443#+BEGIN_SRC org
444,#+NAME: nums
445| 1 | 2 |
446| 3 | 4 |
447
448,#+begin_src python :var t=nums :var scale=10
449return [[c * scale for c in row] for row in t]
450,#+end_src
451#+END_SRC
452
453A referenced block runs before the block that refers to it, after the one trust prompt that covers them all. A block with =:cache yes= and a current result gives that result without running. A chain that leads back to itself is refused with "/name/ refers to itself through :var"; a chain through =:post= or a noweb reference names that instead.
454
455A referenced block with =:results file= gives the name of its =:file=, or without =:file= its result as text. The file is written when the block runs.
456
457These are not supported and are refused:
458
459- Indexing into a table, such as =tbl[1,2]=: "References like … aren't supported yet."
460- A name that matches nothing in the file: "Can't find … for :var."
461- References to other files.
462
463How a value reaches the code depends on the language:
464
465| Language   | Scalars                 | Lists                          | Tables                                                       |
466|------------+-------------------------+--------------------------------+--------------------------------------------------------------|
467| bash       | quoted string           | indexed array (=declare -a=)   | two or more columns: associative array keyed by the first column (=declare -A=); one column: indexed array |
468| other shells | quoted string         | one item per line              | rows on lines, cells separated by a tab or =:separator=     |
469| fish       | =set name 'value'=      | as other shells                | as other shells                                              |
470| Python     | literal                 | list                           | list of lists, =None= for rules                              |
471| Emacs Lisp | =let=-bound value       | list                           | list of lists, =hline= for rules                             |
472| Ruby       | =name=value= literal    | array                          | array of arrays, =nil= for rules                             |
473| JavaScript | =var name=value;=       | array                          | array of arrays, =hline= for rules                           |
474| R          | =name <- value=, integers with =L= | one-column data frame | data frame read from tab-separated text, a header when the table has one |
475| awk        | =-v name='value'=        | one item per line              | rows on lines, cells separated by a tab                      |
476
477For =shell= blocks, the bash forms are used when =SHELL= is bash. =:prologue= and =:epilogue= add a line before the variables and one after the body, in every language that runs; in Emacs Lisp only when the block has variables, as =org-babel-expand-body:emacs-lisp= does. C, C++, D, Java, Fortran and Clojure blocks get declarations as their expansion writes them; see Tangling below.
478
479#+BEGIN_SRC org
480,#+NAME: kv
481| a | 1 |
482| b | 2 |
483
484,#+begin_src bash :var t=kv :results output
485echo ${t[a]} ${t[b]}
486,#+end_src
487#+END_SRC
488
489** Tables in variables
490
491A table passed as a variable loses some of its structure first (=org-babel-disassemble-tables=):
492
493- Rules are removed, unless =:hlines yes=.
494- The first row is taken off as column names when =:colnames yes=, or when the table's only rule is under the first row. =:colnames no= keeps it as data.
495- The first column is taken off as row names when =:rownames yes=.
496
497If the result is a table of the same width (for columns) or height (for rows), the names are put back on it (=org-babel-reassemble-table=). Clojure results don't get them back, as in Org. =:colnames= and =:rownames= can also be Lisp lists of names to put on the result, such as =:colnames '("x" "y")=.
498
499#+BEGIN_SRC org
500,#+NAME: tbl
501| a | b |
502|---+---|
503| 1 | x |
504| 2 | y |
505
506,#+begin_src python :var t=tbl
507return [r + ["!"] for r in t]
508,#+end_src
509#+END_SRC
510
511** Standard input and arguments
512
513For shell blocks, =:stdin name= sends a table, list or block result to standard input, a table as tab-separated lines. =:cmdline= gives the script arguments, and =:shebang= its first line. With any of the three, the block is written to an executable script and run by the shell (=org-babel-sh-evaluate=); without =:shebang=, the first line is =#!/usr/bin/env= and the shell's name. A block with =:stdin= or =:cmdline= runs as a script even with a =:session=, and leaves the session untouched; =:shebang= alone runs in the session.
514
515#+BEGIN_SRC org
516,#+begin_src sh :cmdline one "two words" :results output
517for a in "$@"; do echo "[$a]"; done
518,#+end_src
519#+END_SRC
520
521* Sessions
522
523=:session name= runs the block in an interpreter that stays running, so variables, functions and the working folder carry over to the next block in the same session. Sessions work for shells, Python, Ruby, JavaScript (Node, or JavaScriptCore) and R in the Mac download version, and for JavaScript and Python (in Pyodide) on iOS and in the Mac App Store version.
524
525- =:session= with no name uses =*language*=, such as =*sh*=. =:session none= runs without one.
526- A session belongs to one folder, one interpreter and one name. Blocks in different folders, or with different names, do not share state.
527- A session starts in the block's =:dir=, or the file's folder, the first time it is used.
528- A shell session's output is what the block prints. =:results value= gives the exit status of the last command.
529- A Python session runs the block at top level. Its value is the value of the last expression, so =return= is not used.
530- A Ruby session runs each block in the same binding, and a JavaScript session in Node's global context or one JavaScriptCore context, so local variables and =var= and =let= declarations carry over. Their value is the value of the last expression, written as without a session (=inspect=, =util.inspect=); =return= is not used. Errors go to the block's error output and leave the session running.
531- An R session runs each block with =source(…, print.eval = TRUE)= in one =R --slave= process; its result is the output, as without a session.
532
533Emacs runs these with packages beyond Org: inf-ruby for Ruby, ESS for R, and js-comint or skewer for JavaScript; with plain =node=, ob-js refuses sessions. orgstar's sessions don't need them, and their results can differ in detail from those packages' echoed output.
534- Sessions stop when you quit orgstar, or when you cancel a block running in one.
535
536#+BEGIN_SRC org
537,#+begin_src python :session py :results output
538a = 2
539print("set")
540,#+end_src
541
542,#+begin_src python :session py
543a * 3
544,#+end_src
545#+END_SRC
546
547* Caching
548
549With =:cache yes=, orgstar computes a SHA-1 hash of the block's header arguments and expanded body, as =org-babel-sha1-hash= does, and writes it on the results line: =#+RESULTS[hash]:=. When you run the block again and the hash matches, nothing runs and the message area shows the cached value ("Cached: …").
550
551Change the block or its arguments and it runs again. Results inserted with =append= or =prepend= carry no hash. Inline blocks are not cached. A cached block that has Lisp in its header arguments the interpreter cannot evaluate is refused.
552
553The hash of a C, C++, D, Java, Fortran or Clojure block is taken over the body as the language expands it (see Tangling below), with the =IMPORTS=, =INCLUDES= and =DEFINES= properties where the block is, and Java's default header arguments, as Emacs does. A result Emacs wrote for such a block with =:cache yes= is recognised as current, and =C-c C-c= shows it.
554
555* Post-processing
556
557=:post= names a reference that is resolved after the block has run (=org-babel-execute-src-block=). The block's result is bound to =*this*=, and the value of the reference becomes the block's result. The reference is usually a call to a named block that takes =*this*= as an argument; it can pass other arguments as well.
558
559#+BEGIN_SRC org
560,#+NAME: total
561,#+begin_src emacs-lisp :var rows='()
562(append rows (list 'hline (list "sum" (apply #'+ (mapcar #'cadr rows)))))
563,#+end_src
564
565,#+begin_src sh :post total(rows=*this*)
566printf 'a 1\nb 2\n'
567,#+end_src
568
569,#+RESULTS:
570| a   | 1 |
571| b   | 2 |
572|-----+---|
573| sum | 3 |
574#+END_SRC
575
576- =*this*= is the result as a =:var= would get it: a string, a number or a table.
577- With =:results file= and =:file=, the file is written first and =*this*= is the link to it, with its =:file-desc=. The value of the reference then goes in as text, not as a link; use =:results drawer= or =raw= when it is Org markup, such as an =#+ATTR_= line above the link. With =:results file= and no =:file=, =*this*= is the result as text, and the value of the reference becomes the link.
578- The value is inserted according to the block's own =:results=.
579- The block that =:post= calls can have its own =:post=, and =:var= references in it can use =*this*=.
580- With =:cache yes= and a current result, neither the block nor the reference runs.
581- =#+CALL:= lines, inline calls and inline source blocks take =:post= too.
582
583The one trust prompt covers the block and every block the reference runs, and asks every time when any of them has =:eval query=. Before anything runs, orgstar resolves the reference with an empty =*this*=; when that fails, the message says why and nothing runs. That covers a name that isn't a block in the file, a block with =:eval never=, a language orgstar can't run, and a reference that leads back to its own block ("/name/ refers to itself through :post").
584
585* Noweb
586
587A noweb reference =<<name>>= in a block's body stands for other code. Whether references expand depends on =:noweb= and on what is happening:
588
589| =:noweb=        | Running  | Tangling         | Exporting |
590|-----------------+----------+------------------+-----------|
591| =no= (default)  | no       | no               | no        |
592| =yes=           | expands  | expands          | no        |
593| =tangle=        | no       | expands          | no        |
594| =eval=          | expands  | no               | no        |
595| =no-export=     | expands  | expands          | no        |
596| =strip-export=  | expands  | expands          | no        |
597| =strip-tangle=  | expands  | removes the references | no  |
598
599Exported code always shows the references as written; see [[file:12-export.org][Export]].
600
601=<<name>>= expands to the first of these that exists:
602
6031. The contents of the heading whose =ID= property is =name=, or whose =CUSTOM_ID= is =name= without its leading =#=.
6042. The body of the source block named =name=.
6053. The bodies of all blocks with =:noweb-ref name=, joined by each block's =:noweb-sep= (a newline by default).
606
607Blocks under a =COMMENT= heading are skipped. A referenced block expands its own references according to its own =:noweb=, up to 32 levels deep.
608
609Text before the reference on its line is repeated before each line the reference brings in, so references inside comments or indented code keep their prefix. =:noweb-prefix no= turns this off.
610
611#+BEGIN_SRC org
612,#+NAME: greeting
613,#+begin_src sh
614echo hello
615,#+end_src
616
617,#+begin_src sh :noweb yes
618<<greeting>>
619echo world
620,#+end_src
621#+END_SRC
622
623** References that run a block
624
625=<<name()>>= stands for the result of the block named =name=, which runs first, and =<<name(arg=value)>>= runs it with arguments, as =:var x=name(arg=value)= does (=org-babel-ref-resolve=). A result that is a string goes in as it is; a number, list or table goes in as Emacs Lisp prints it, such as =42= or =((1 2) (3 4))=. Text before the reference is repeated before each line of a result of several lines, unless =:noweb-prefix no=.
626
627#+BEGIN_SRC org
628,#+NAME: port
629,#+begin_src emacs-lisp :var base=8000
630(+ base 80)
631,#+end_src
632
633,#+begin_src sh :noweb yes
634echo "listening on <<port(base=3000)>>"
635,#+end_src
636
637,#+RESULTS:
638: listening on 3080
639#+END_SRC
640
641These references expand when the others do for running: with =:noweb= =yes=, =eval=, =no-export=, =strip-export= or =strip-tangle=. With =no= or =tangle=, the text stays as written and nothing runs. A block brought in by =<<name>>= has its own references run in the same way, according to its own =:noweb=.
642
643The rules for =:var= references apply: one trust prompt covers every block that would run, a referenced block with =:cache yes= and a current result gives that result without running, =:eval never= on a referenced block stops the run, and a reference that leads back to its own block is refused with "/name/ refers to itself through a noweb reference".
644
645Export shows these references as written and runs nothing. Tangling does not run blocks; see What tangling refuses below.
646
647* Calls
648
649** =#+CALL:= lines
650
651=#+CALL:= runs a named block with other arguments, as Org's library of Babel calls do (=org-babel-lob-get-info=). Run it with =C-c C-c= on the line.
652
653#+BEGIN_SRC org
654,#+NAME: double
655,#+begin_src sh :var n=2
656echo $((n*2))
657,#+end_src
658
659,#+CALL: double(n=5)
660
661,#+RESULTS:
662: 10
663#+END_SRC
664
665The full form is =#+CALL: name[inside](arguments) end=:
666
667- =name= is the block to run. It must be in the same file.
668- =[inside]= holds header arguments applied to the block, such as =[:results raw]=.
669- =(arguments)= are =:var= assignments, separated by commas.
670- =end= holds header arguments for the call's result, such as =:results verbatim=.
671
672The call also takes the =header-args= and =header-args:LANG= properties, and =#+PROPERTY:= lines, where the call is, with =LANG= the called block's language. They apply after the called block's own header arguments and before =[inside]=, as in Org.
673
674The result goes under the call. A =#+NAME:= line above the =#+CALL:= names the result.
675
676** Inline calls and blocks
677
678An inline source block, =src_sh{echo hi}=, runs with =C-c C-c= on it. Header arguments go in brackets: =src_sh[:var x=3]{echo $x}=. The result is written right after the block as a =results= macro:
679
680#+BEGIN_SRC org
681Text src_sh{echo hi} {{{results(=hi=)}}} end.
682#+END_SRC
683
684Running again replaces the macro. With =:results raw= the result goes in as it is, without the macro. An inline result must be one line, and a table result must be a single cell.
685
686An inline call, =call_double(n=6)=, has the same parts as a =#+CALL:= line: =call_name[inside](arguments)[end]=. =C-c C-c= on an inline call runs it, and its result is written after it as a =results= macro, as for inline blocks. It takes the properties where it is as a =#+CALL:= line does.
687
688* Emacs Lisp blocks
689
690On the Mac, an =emacs-lisp= or =elisp= block runs in a new =emacs -Q --batch= for each run, with lexical binding on. =-Q= means your init file and packages are not loaded, and nothing carries over between runs. orgstar looks for Emacs at =ORGSTAR_EMACS=, then =/opt/homebrew/bin/emacs=, =/usr/local/bin/emacs=, =/Applications/Emacs.app/Contents/MacOS/Emacs=, =/run/current-system/sw/bin/emacs= and =/usr/bin/emacs=. Without Emacs, the block runs in orgstar's own Emacs Lisp interpreter, and a block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, and Emacs isn't installed."
691
692On iOS, Emacs Lisp blocks run in orgstar's own Emacs Lisp interpreter. It has the forms and functions listed under Lisp formulas in [[file:10-tables.org][Tables]]: list, string, number and control forms, regular expressions on strings, =defun=, =pcase=, =cl-loop=, the =seq-= and =cl-= sequence functions, time functions, =princ= and =message=. Like =emacs -Q --batch=, it uses lexical binding, with dynamic binding for variables declared with =defvar=, and the syntax table of Emacs Lisp mode for regular expressions and =capitalize=. A quoted lambda, ='(lambda ...)=, runs with dynamic binding, as in Emacs. A closure can be called, stored and passed to functions such as =mapcar=; a block that takes one apart as a list, compares it or prints it needs Emacs. It has no buffers. A block that uses something the interpreter does not have fails with "This block uses Emacs Lisp that runs only in Emacs, on the Mac." A Lisp error fails the run, as it does in Emacs.
693
694In the [[file:../install.org][Mac App Store version]], Emacs Lisp blocks run in the same interpreter as on iOS. A block that uses something it does not have fails with "This block uses Emacs Lisp that runs only in Emacs."
695
696Variables are bound with =let= around the body. =:results output= collects what the block prints with =princ=, =prin1=, =print= and =terpri=.
697
698* calc blocks
699
700A =calc= block runs as ob-calc runs it in =emacs -Q=, with orgstar's Calc, the one table formulas use. Each line of the body is trimmed and handled in turn; blank lines are skipped:
701
702- A line that is the name of a =:var= puts its value on the stack.
703- A line that starts with ='= runs a stack key on the stack: ='+=, ='-=, ='*=, ='/=, ='^=, ='%= (modulo), ='\= (integer division), ='n= (negate), ='&= (inverse), ='Q= (square root) and ='A= (absolute value).
704- Any other line is a formula. Its value goes on the stack; if it isn't a number, the formula is evaluated again with the block's variables put in, and that goes on the stack as text, as ob-calc does.
705
706The result is the top of the stack, shown with Calc's own settings in =emacs -Q=: 12 significant digits, all of them shown (=1/3= gives =0.333333333333=). A vector is written as a table row and a matrix as a table, unless =:results= asks for a string. =:prologue= and =:epilogue= add lines before and after the body.
707
708Each run starts with an empty stack. In Emacs the Calculator's stack carries over from one block to the next, so a block that relies on what an earlier block left there gives a different result in orgstar.
709
710=:var= values can be numbers, and lists and tables of integers; a table of one row is a vector. Errors that Emacs reports, such as "Too few elements on stack" or a stack key on a formula ("Invalid data object encountered"), fail the run without writing a result.
711
712What orgstar's Calc doesn't do as Emacs's Calc does is refused rather than given a different result: functions and forms table formulas also refuse, Calc's constants such as =pi= and =e= (which Emacs replaces by their values), stack keys other than those above, dates, string variables, variables named like Calc's constants (=e=, =pi=, =i=) or with characters other than letters and digits, lists with fractional numbers, and a =:prologue= or =:epilogue= that is a bare number. The message is "This calc block can't be calculated here:" with the reason. The download version then runs the block in =emacs -Q --batch= when Emacs is installed.
713
714* sqlite blocks
715
716A =sqlite= block runs as ob-sqlite runs it: the body goes to =sqlite3= on standard input, with the options the header arguments name, and the output becomes the result. The download version runs =sqlite3= (macOS has one in =/usr/bin=) and uses the SQLite library only when it isn't installed. The Mac App Store version and iOS run the block in the SQLite library, writing the output as macOS's =sqlite3= writes it.
717
718| Header argument             | Effect                                                                     |
719|-----------------------------+----------------------------------------------------------------------------|
720| =:db file=                  | The database, relative to the file's folder or =:dir=; without it, an in-memory one |
721| =:readonly yes=             | Opens the database read-only                                               |
722| =:csv=, =:list=, =:column=, =:html=, =:line= | The output mode; without one or =:separator=, =csv=          |
723| =:separator s=, =:nullvalue s= | The column separator and the text for NULL, in list mode             |
724| =:colnames yes=             | The first row of the result becomes the table's header                    |
725| =:header=, =:echo=, =:bail= | Pass =-header=, =-echo= and =-bail= to =sqlite3=                           |
726
727As in Emacs, a mode option resets the header, separator and NULL text to that mode's, so =:header= has an effect only with =:separator= alone.
728
729=:var= values replace =$name= in the body, in any case. A table becomes a CSV file and =$name= its path, for =.import=:
730
731#+begin_src org
732,#+begin_src sqlite :var t=prices :db shop.db
733create table if not exists prices(item text, price real);
734.import --csv $t prices
735select item, price * 2 from prices;
736,#+end_src
737#+end_src
738
739The output is read as a table the way ob-sqlite reads it, with =org-table-convert-region=; a single value becomes a scalar. Where that conversion fails in Emacs, as it does for output whose last line is empty in a mode other than =csv=, the run fails with the same message. In =csv= mode =sqlite3= ends lines with CR LF and Emacs keeps the CR, so the last column of each row ends with a CR, which shows as =^M=; orgstar writes the same.
740
741In the Mac App Store version, =:db= must be in a folder orgstar has access to: a folder in the sidebar, or one you granted access to.
742
743Without =sqlite3=, these dot-commands run: =.headers= (=.header=), =.mode= with =list=, =csv=, =column=, =html= or =line=, =.separator= and =.nullvalue= with one plain argument, and =.import FILE TABLE= (with =--csv= or not) into a table that exists, of rows that fit it. Anything else is refused with "This sqlite block can't run here:" and the reason: other dot-commands, header values with characters the shell would read differently (spaces, quotes, =~=, =;=, =|=), BLOB values, control characters other than tab and newline in values, text other than ASCII or values on several lines in =column= mode and in =line= mode's column names, =EXPLAIN= statements, text that isn't UTF-8, and =:echo= unless the result is text (=:results output=, for example). When the refused value comes after other statements, those statements have already run, and the message says so.
744
745* Graphics
746
747=dot= (Graphviz), =plantuml= and =mermaid= blocks draw a picture into =:file=, and the result is a link to it. =:file= is required: "/language/ code blocks need a :file header argument". The file's extension picks the output format; with none, =png= is used.
748
749| Language   | Command                                   |
750|------------+-------------------------------------------|
751| =dot=      | =dot -T/ext/ -o file=                      |
752| =plantuml= | =plantuml -p -t/ext/=, output to the file  |
753| =mermaid=  | =mmdc -i input -o file=                    |
754
755A =plantuml= body without an =@start…= line is wrapped in =@startuml= and =@enduml=. =:cmdline= adds options to the command. =plantuml= must be installed and on the =PATH= described under Languages that run.
756
757Without =dot= or =mmdc=, and in the Mac App Store version and on iOS, orgstar draws =dot= and =mermaid= blocks itself, with Graphviz and mermaid built in:
758
759- It writes SVG and PNG files. Another extension fails with "/language/ blocks draw only SVG and PNG files in this version of orgstar."
760- =:cmdline= may hold =-K/engine/= for =dot=, and =-t /theme/= (=--theme=) and =-b /color/= (=--backgroundColor=) for =mermaid=. Anything else fails with "/language/ blocks with this :cmdline don't run in this version of orgstar."
761- A PNG has the size the picture has at 96 dots per inch, on white unless =-b= says otherwise; a mermaid diagram wider than 800 points is scaled down to that, as =mmdc= does.
762- Mermaid labels are drawn as SVG text, not HTML, so line breaks and Markdown in labels can look different from =mmdc='s.
763- The picture comes from the same Graphviz and mermaid code as the programs use, in the versions orgstar ships (Viz.js 3.31.0 and mermaid 12.3.0), so it can differ in detail from an installed program of another version or with other fonts.
764
765#+BEGIN_SRC org
766,#+begin_src dot :file graph.svg
767digraph { a -> b }
768,#+end_src
769
770,#+RESULTS:
771[[file:graph.svg]]
772#+END_SRC
773
774* Tangling
775
776Tangling writes source blocks to the files their =:tangle= argument names (=org-babel-tangle=).
777
778| Command                 | Emacs and Doom              | Mac     | What it tangles                                   |
779|-------------------------+-----------------------------+---------+---------------------------------------------------|
780| Tangle File             | =C-c C-v t=, =C-c C-v C-t=  | =⌃⌘V=   | Every block in the file                            |
781| Tangle Block            | none                        | =⌃⇧⌘V=  | The block at the caret (Emacs: =C-u C-c C-v t=)    |
782| Tangle Block's Target   | none                        | =⌃⌥⌘V=  | Every block going to the same file as the one at the caret (Emacs: =C-u C-u C-c C-v t=) |
783
784All three are in the Org menu and the command palette. Tangling uses the text in the editor, saved or not, and the message area reports "Tangled /N/ code blocks from /file/".
785
786** =:tangle= and file names
787
788| =:tangle=         | Target                                                                                          |
789|-------------------+-------------------------------------------------------------------------------------------------|
790| =no= (default)    | Not tangled.                                                                                    |
791| =yes=             | The Org file's name with the language's extension, as Org's language files define it (=org-babel-tangle-lang-exts=): =py= for =python=, =rb= for =ruby=, =pl= for =perl=, =cpp= for =C++=, =d= for =D=, =awk=, =sed=, =lua=, =hs= for =haskell=, =java=, =tex= for =latex=, =ly= for =LilyPond=, =F90= for =fortran=, =clj= for =clojure=, =cljs= for =clojurescript=, =cs= for =csharp=, =groovy=, =jl= for =julia=, =lisp=, =max= for =maxima=, =ml= for =ocaml=, =pde= for =processing=, =el= for =emacs-lisp= and =elisp=, and =bib= for =bibtex=. Any other language is its own extension (=notes.sh= for =sh=). |
792| a path            | That file, relative to the Org file's folder. =~= is expanded.                                   |
793| Lisp              | Evaluated as described under Lisp in header values, with =buffer-file-name= set to the Org file. |
794
795Blocks under a =COMMENT= heading, or a heading tagged =ARCHIVE=, are skipped. Blocks going to the same file are written in the order they appear.
796
797#+BEGIN_SRC org
798,#+PROPERTY: header-args:python :tangle script.py
799
800,* Tool
801:PROPERTIES:
802:header-args: :tangle bin/tool.sh :mkdirp yes :shebang "#!/bin/sh"
803:END:
804
805,#+begin_src sh
806echo tool
807,#+end_src
808#+END_SRC
809
810** Tangling arguments
811
812| Argument        | Values                                            | Effect                                                                                       |
813|-----------------+---------------------------------------------------+----------------------------------------------------------------------------------------------|
814| =:mkdirp=       | =yes=                                             | Create the target's folder if it is missing.                                                 |
815| =:tangle-mode=  | =(identity #o755)=, =#o755=, =o755=, =rwxr-xr-x=, =u+x,g-r= | Set the file's mode. A symbolic mode starts from =644=. When several blocks give a mode, the first one counts. |
816| =:shebang=      | =#!…= line                                        | First line of the file, written once. Makes the file mode =755= unless =:tangle-mode= says otherwise. |
817| =:padline=      | =no=                                              | No blank line between this block and the one before it.                                      |
818| =:comments=     | =no=, =link=, =yes=, =org=, =both=, =noweb=       | Comments around each block (below).                                                          |
819| =:noweb=        | see Noweb above                                   | Expand or strip =<<name>>= references.                                                       |
820| =:prologue=, =:epilogue= | text                                     | A line before and after the block's code.                                                    |
821| =:var=          | as for running                                    | Shell scalars become assignments, Python values become assignments, Emacs Lisp values are =let=-bound. For the languages below, as their Org language files write them. |
822| =:no-expand=    | any                                               | Write the body without =:var=, =:prologue=, =:epilogue= or the language's wrapping.          |
823
824A table in =:var= loses its first row when its only rule is under that row, or with =:colnames yes=, and its rules unless =:hlines yes=, as when the block runs. This holds for every language.
825
826=C=, =C++=, =cpp=, =D=, =java=, =fortran= and =clojure= blocks are written as Org's =org-babel-expand-body:LANG= writes them:
827
828| Language       | Written                                                                                                      |
829|----------------+--------------------------------------------------------------------------------------------------------------|
830| =C=, =C++=, =cpp= | =#include= lines from =:includes=, =#define= lines from =:defines=, =using namespace= lines from =:namespaces=, the =:var= declarations with table sizes and column-name helpers, then the body between =:prologue= and =:epilogue=, wrapped in =int main()= unless it has a =main= or =:main no= is given. |
831| =D=            | =module mmm;=, =import= lines from =:imports= (or the =IMPORTS= property, except when tangling) plus =std.stdio= and =std.conv=, the =:var= declarations, and the body wrapped in =int main()= as for C. |
832| =java=         | The body between =:prologue= and =:epilogue=, wrapped in a =main= method when it has no method and in a class when it has none. The class is named by =:classname= or the body's own class; a dotted =:classname= adds a =package= line. =:imports= adds =import= lines, and =:var= values become static fields. |
833| =fortran=      | =#include= and =#define= lines from =:includes= and =:defines= (or the =INCLUDES= and =DEFINES= properties, except when tangling), then the =:var= declarations and the body in =program main=, unless the body has its own =program= statement (then =:var= is refused) or =:main no= is given. |
834| =clojure=      | =(ns …)= from =:ns=, the body in a =let= of the =:var= values, and a printer around it unless =:results output=. |
835
836With =:hlines yes=, a table that keeps rules is refused for C, C++, D and Fortran; Java writes =null= for each rule.
837
838Block switches also apply. =-r= removes coderef labels such as =(ref:name)=, using the format from =-l= if given. =-i= keeps the block's indentation. Otherwise common indentation and surrounding blank lines are removed.
839
840** Comments
841
842| =:comments= | Written                                                                                                  |
843|-------------+----------------------------------------------------------------------------------------------------------|
844| =no=        | The code only.                                                                                           |
845| =link=, =yes= | A comment with a link back to the block before the code, and "/name/ ends here" after it.               |
846| =org=       | The Org text between the heading (or the previous block) and this block, as a comment.                   |
847| =both=      | The Org text and the link comments.                                                                      |
848| =noweb=     | Link comments, plus link comments around each expanded noweb reference.                                  |
849
850The link is relative to the tangled file's folder. /name/ is the block's =#+NAME=, or the heading's title and the block's number under that heading, such as =Setup:2=.
851
852Comments need the language's comment syntax. orgstar knows it for: =emacs-lisp=, =elisp=, =lisp=, =scheme=, =asm= (=;;=); =python=, =ruby=, =perl=, =conf=, =toml=, =makefile=, =awk=, =tcl=, =m4=, =icon=, =desktop= and the shells except =fish= (=#=); =js=, =javascript=, =java=, =cpp=, =C++=, =objc=, =csharp=, =idl=, =pike=, =antlr=, =verilog= (=//=); =c=, =C=, =css= (=/* */=); =lua=, =sql=, =sqlite=, =vhdl= (=--=); =latex=, =tex=, =prolog= (=%%=); =ps=, =metapost= (=%=); =f90=, =dcl= (=!=); =html=, =xml=, =nxml=, =mhtml=, =sgml= (=<!-- -->=); =octave= (=##=); =pascal= (={ }=); =texinfo= (=@c=); =bibtex= (=@Comment=); =nroff= (=\"=); =bat= (=rem=). For any other language, =:comments= other than =no= stops tangling with a message.
853
854** Writing the files
855
856- A file whose contents would not change is left alone, so its modification time stays the same.
857- A read-only file is replaced.
858- Tangling into the Org file itself is refused: "Not allowed to tangle into the same file as self".
859- When a file's mode, from =:shebang= or =:tangle-mode=, can't be set, the other files are still written and their modes set, and the message area says "Tangled /N/ code blocks from /file/, but can't set the mode of /path/: /reason/".
860
861** What tangling refuses
862
863Tangling stops, writes nothing and says why when:
864
865- =:var= refers to a source block, which would have to run: "would run a block while tangling".
866- A noweb reference runs a block, =<<name()>>=, in a block whose =:noweb= expands when tangling: "The noweb reference <<…>> would run a block while tangling, which isn't supported yet; nothing was tangled."
867- A shell block's =:var= is a table or list.
868- =:var= is used in a language other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure.
869- A C, C++, D or Fortran block's =:var= table keeps rules (with =:hlines yes=), or a value has no type the language takes.
870- A Lisp header value cannot be evaluated: "is Lisp tangling can't evaluate yet; nothing was tangled."
871- =:tangle-mode= is in a form it does not read.
872- =:comments= needs a comment syntax it does not know.
873
874* On iOS
875
876- Only Emacs Lisp blocks, in orgstar's own interpreter, JavaScript blocks, in JavaScriptCore (see /JavaScript in JavaScriptCore/ above), Python blocks, in Pyodide (see /Python in Pyodide/ above), and calc, sqlite, dot and mermaid blocks (see above) run. Any other language, compiled languages included, fails with "/language/ blocks need the Mac to run." (for example "C blocks need the Mac to run."), and so does a block whose =:var= refers to a block in another language.
877- JavaScript and Python blocks can use =:session=. There are no other sessions, and no graphics other than dot and mermaid.
878- The trust prompt works the same way, with its own =trusted.json= on the device.
879- There is no cancel command.
880- Tangling works, for files in folders orgstar can write to.
881- Edit Block opens a plain text sheet without highlighting.
882
883See [[file:14-ios.org][iOS]] for the rest of the iOS app.
884
885* In the Mac App Store version
886
887- Only Emacs Lisp blocks, in the same interpreter as on iOS, JavaScript blocks, in JavaScriptCore, Python blocks, in Pyodide, and calc, sqlite, dot and mermaid blocks run. Any other language, compiled languages included, fails with "/language/ blocks don't run in this version of orgstar." A block whose =:var=, =:post= or noweb reference runs a block in another language runs nothing: "This block needs a /language/ block, and /language/ blocks don't run in this version of orgstar; nothing was run."
888- JavaScript and Python blocks can use =:session=. There are no other sessions, and no graphics other than dot and mermaid.
889- The trust prompt works the same way.
890- Tangling works as in the download version, =:shebang= included. A target outside your folders needs access to its folder first: orgstar asks with Grant Access…, as described in [[file:../install.org][Install]]. So does a =:file= result outside them.
Keyboard shortcuts

Global

⌘K
Command palette & jump
/
Focus search
?
Show this help
g d
Dashboard
g e
Explore repositories
g n
Notifications

Repository & editor

t
Find file in repository
y
Copy immutable SHA permalink
g c
Code tab
g i
Issues tab
g m
Merge requests tab
g b
Builds tab
⌘↵
Submit active form