krz/orgstar

A native macOS editor for org-mode files. editor org-mode swift

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

778058aafc7ddacee4a613b1da87c60aa0c8e113
orgstar/docs/manual/guide/11-code-blocks.org rendered · source · history · blame · raw

667 lines · 45226 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
 21On the Mac, the code in a block is highlighted in the editor and in the block editor. 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. The iOS app does not highlight code.
 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 through =/usr/bin/env=. 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=; see Emacs Lisp blocks below     |
 93| =ruby=                                                           | =ruby=                                              |
 94| =js=, =javascript=                                               | =node=                                              |
 95| =R=                                                              | =Rscript -=                                         |
 96| =awk=                                                            | =awk -f /dev/stdin=                                 |
 97| =dot=, =plantuml=, =mermaid=                                     | =dot=, =plantuml=, =mmdc=; see Graphics below       |
 98
 99For =ruby=, =js=, =javascript=, =R= and =awk=, =:cmd= names a different program. These languages always return their standard output, and =:var= is refused for them.
100
101Any other language is refused with "No way to run /language/ blocks yet."
102
103A run that takes longer than five minutes is stopped. Runs in a =:session= have no time limit.
104
105** The trust prompt
106
107Before a block runs, Orgstar asks "Run this /language/ block? (yes, no, always)", as =org-confirm-babel-evaluate= does.
108
109- =yes= runs it this once.
110- =no= does not run it.
111- =always= runs it and remembers the block, so it runs without asking next time.
112
113A 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). The same file records table formulas you allowed to run Lisp. To forget every choice, delete the file while Orgstar is not running.
114
115When 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."
116
117** =:eval=
118
119| Value                                    | Effect                                                     |
120|------------------------------------------+------------------------------------------------------------|
121| =never=, =no=                            | The block does not run: "Evaluation of this /language/ code block is disabled." |
122| =query=                                  | Asks every time, with only =yes= and =no=. A block reached through =:var= with =:eval query= makes the whole chain ask every time. |
123| anything else, or absent                 | Runs after the trust prompt.                                |
124
125=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.
126
127** Cancelling a run
128
129On 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.
130
131Only one block runs at a time. Starting another block cancels the one that is running.
132
133Cancelling 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.
134
135The iOS app has no cancel command.
136
137* Results
138
139The 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.
140
141#+BEGIN_SRC org
142,#+begin_src sh
143echo hello
144,#+end_src
145
146,#+RESULTS:
147: hello
148#+END_SRC
149
150By default a result is shaped like this:
151
152- Text of fewer than ten lines gets a =: = prefix on each line.
153- Text of ten lines or more goes in an =#+begin_example= block.
154- A table becomes an aligned Org table.
155
156** Value or output
157
158| Word     | Result                                                                                                  |
159|----------+---------------------------------------------------------------------------------------------------------|
160| =value=  | The value of the block. This is the default.                                                           |
161| =output= | Everything the program printed on standard output.                                                     |
162
163What "value" means depends on the language:
164
165| Language                | Value                                                                                         |
166|-------------------------+-----------------------------------------------------------------------------------------------|
167| 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. |
168| Shells, =:results value= written out | The exit status of the last command.                                             |
169| Python                  | What the block returns. The body runs as a function, so it needs =return=. =:return expr= adds a final =return expr=. |
170| Python in a =:session=  | The value of the last expression.                                                             |
171| Emacs Lisp              | The value of the last form.                                                                   |
172| =ruby=, =js=, =R=, =awk= | Standard output, always.                                                                     |
173
174Python 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.
175
176** Result types
177
178| Word                 | Effect                                                                     |
179|----------------------+----------------------------------------------------------------------------|
180| =table=, =vector=    | Read the result as a table. This is the default for values.                |
181| =list=               | Write a plain list, one =- = item per line or per element.                 |
182| =scalar=, =verbatim= | Write the result as text without reading it as a table.                    |
183| =file=               | Write a link to a file (see Results in files below).                       |
184
185=:results verbatim= on an Emacs Lisp value writes it as =prin1= would, with quotes around strings.
186
187** Result formats
188
189| Word     | Written as                                                     |
190|----------+----------------------------------------------------------------|
191| =raw=    | The text as it is, so Org markup in it takes effect.           |
192| =drawer= | Between =:results:= and =:end:=.                                |
193| =code=   | In a =#+begin_src= block of the block's language.               |
194| =org=    | In a =#+begin_src org= block.                                   |
195| =html=   | In a =#+begin_export html= block.                               |
196| =latex=  | In a =#+begin_export latex= block.                              |
197| =pp=     | Python: formatted with =pprint=; written as text.               |
198
199Lines that start with =*= or =#+= inside =code=, =org=, =html= and =latex= results are comma-protected.
200
201** Inserting
202
203| Word      | Effect                                                         |
204|-----------+----------------------------------------------------------------|
205| =replace= | Replace the previous result. This is the default.             |
206| =append=  | Add after the previous result.                                 |
207| =prepend= | Add before the previous result.                                |
208| =silent=  | Show the output in the message area and write nothing.         |
209| =none=, =discard= | Write nothing.                                         |
210
211Words from different groups combine: =:results output list append=. A later word replaces an earlier one from the same group.
212
213** =:wrap=
214
215=:wrap= puts the result in a block, ahead of any format word.
216
217| Value               | Wrapped in                                         |
218|---------------------+----------------------------------------------------|
219| =:wrap= alone       | =#+begin_results= … =#+end_results=                 |
220| =:wrap example=     | =#+begin_example= … =#+end_example=                 |
221| =:wrap src python=  | =#+begin_src python= … =#+end_src=                  |
222| =:wrap export html= | =#+begin_export html= … =#+end_export=              |
223| =:wrap no=, =:wrap nil= | No wrapping                                    |
224
225Inside =example=, =src= and =export= wrappers, lines starting with =*= or =#+= are comma-protected.
226
227** Results in files
228
229With =:results file=, the result is a link instead of text.
230
231| Header        | Effect                                                                                     |
232|---------------+--------------------------------------------------------------------------------------------|
233| =:file name=  | Write the result into =name= and link to it. Without =:results file=, =:file= has no effect, except in graphics blocks. |
234| =:output-dir dir= | Put =:file= under =dir=. The folder must exist.                                        |
235| =:file-desc text= | Give the link a description: =[[file:name][text]]=. An empty =:file-desc= uses the file name. |
236
237A 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.
238
239#+BEGIN_SRC org
240,#+begin_src sh :results file :file out.txt :file-desc Output
241echo hello
242,#+end_src
243
244,#+RESULTS:
245[[file:out.txt][Output]]
246#+END_SRC
247
248* Header arguments
249
250** Where they come from
251
252Orgstar merges header arguments in this order, each layer overriding the ones before it (=org-babel-get-src-block-info=):
253
2541. =#+PROPERTY: header-args …= in the file, then =header-args= properties of the block's headings, from the outermost heading inwards.
2552. =header-args:LANG= the same way, for blocks in language =LANG=.
2563. The arguments on the =#+begin_src= line.
2574. =#+HEADER:= lines above the block.
2585. For a call, the call's arguments (see Calls below).
259
260A 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.
261
262#+BEGIN_SRC org
263,#+PROPERTY: header-args :results output
264
265,* Scripts
266:PROPERTIES:
267:header-args:sh: :dir /tmp
268:END:
269
270,#+HEADER: :results verbatim
271,#+begin_src sh :var name="world"
272echo "hello $name"
273,#+end_src
274#+END_SRC
275
276Without 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=.
277
278** Lisp in header values
279
280A 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=.
281
282#+BEGIN_SRC org
283,#+begin_src sh :dir (concat "/" "usr") :results output
284pwd
285,#+end_src
286#+END_SRC
287
288A 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.
289
290** Header argument reference
291
292| Argument          | Values                                         | Effect                                                                                     |
293|-------------------+------------------------------------------------+--------------------------------------------------------------------------------------------|
294| =:results=        | see Results above                              | How the result is collected, shaped and inserted.                                          |
295| =:wrap=           | block type and parameters                      | Wraps the result in a block.                                                               |
296| =:file=           | file name                                      | Where a file result goes; required for graphics.                                           |
297| =:output-dir=     | folder                                         | Folder for =:file=.                                                                        |
298| =:file-desc=      | text                                           | Description of a file result's link.                                                       |
299| =:var=            | =name=value=                                   | Passes a value in (see Variables below).                                                   |
300| =:colnames=       | =yes=, =no=, Lisp list                         | Header row of table variables (see Tables in variables below).                             |
301| =:rownames=       | =yes=, =no=, Lisp list                         | First column of table variables.                                                           |
302| =:hlines=         | =yes=, =no=                                    | Keep rules in table variables.                                                             |
303| =:separator=      | text                                           | Column separator for tables in shell variables; a tab by default.                          |
304| =:hline-string=   | text                                           | What a rule becomes in a shell variable with =:hlines yes=; =hline= by default.            |
305| =:dir=            | folder                                         | Folder to run in, relative to the file's folder. It must exist.                            |
306| =:session=        | name, =none=                                   | Runs in a long-lived interpreter (see Sessions below). Shells and Python only.             |
307| =:stdin=          | name of a table, list or block                 | Feeds the value to standard input. Shells only.                                            |
308| =:cmdline=        | arguments                                      | Command-line arguments. Shells, =dot=, =plantuml= and =mermaid= only.                      |
309| =:shebang=        | =#!…= line                                     | Runs the block as a script with this first line. Shells only; also used by tangling.       |
310| =:padline=        | =no=                                           | No blank line after the shebang of a script, or between tangled blocks.                    |
311| =:python=         | program                                        | Python interpreter to use.                                                                 |
312| =:cmd=            | program                                        | Interpreter for =ruby=, =js=, =javascript=, =R= and =awk=.                                 |
313| =:return=         | expression                                     | Python: the value to return.                                                               |
314| =:cache=          | =yes=, =no=                                    | Skip the run when the result is current (see Caching below).                               |
315| =:eval=           | =never=, =no=, =query=, …                      | Whether and how to ask before running (see =:eval= above).                                 |
316| =:noweb=          | see Noweb below                                | Expands =<<name>>= references.                                                             |
317| =:noweb-ref=      | name                                           | Makes the block part of =<<name>>=.                                                        |
318| =:noweb-sep=      | text                                           | Separator between blocks joined under one =:noweb-ref=; a newline by default.             |
319| =:noweb-prefix=   | =no=                                           | Do not repeat the text before =<<name>>= on each expanded line.                            |
320| =:exports=        | =code=, =results=, =both=, =none=              | What export shows (see [[file:12-export.org][Export]]).                                  |
321| =:tangle=         | see Tangling below                             | Where tangling writes the block.                                                           |
322
323** Arguments that are refused
324
325Orgstar does not run a block whose arguments it would handle differently from Emacs. Instead it says why and runs nothing.
326
327| Argument                    | Refused for                                     | Message                                                  |
328|-----------------------------+-------------------------------------------------+----------------------------------------------------------|
329| =:prologue=, =:epilogue=, =:post= | every language when running (tangling uses =:prologue= and =:epilogue=) | "=:prologue= isn't supported yet; nothing was run."      |
330| =:stdin=, =:shebang=        | languages other than shells                     | "=:stdin= isn't supported yet; nothing was run."         |
331| =:cmdline=                  | languages other than shells and graphics        | "=:cmdline= isn't supported for /language/ yet; nothing was run." |
332| =:session=                  | languages other than shells and Python          | "=:session= isn't supported for /language/ yet; nothing was run." |
333| =:var=                      | =ruby=, =js=, =javascript=, =R=, =awk=          | "=:var= isn't supported for /language/ yet."             |
334
335* Variables
336
337=: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.
338
339| Value                          | Meaning                                                                         |
340|--------------------------------+---------------------------------------------------------------------------------|
341| =5=, =2.5=                     | A number.                                                                       |
342| ="two words"=                  | A string. =\n= and =\t= in it are a newline and a tab.                          |
343| ='(1 2)=, =(+ 1 2)=, ='((1 2) hline (3 4))= | Lisp: evaluated to a string, number, list or table.               |
344| =tbl=                          | The table or plain list under =#+NAME: tbl= in the same file.                   |
345| =gen=                          | The result of the source block named =gen=, which runs first.                   |
346| =double(n=4)=                  | The result of the block named =double=, run with =n= set to 4.                  |
347
348#+BEGIN_SRC org
349,#+NAME: nums
350| 1 | 2 |
351| 3 | 4 |
352
353,#+begin_src python :var t=nums :var scale=10
354return [[c * scale for c in row] for row in t]
355,#+end_src
356#+END_SRC
357
358A 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".
359
360These are not supported and are refused:
361
362- Indexing into a table, such as =tbl[1,2]=: "References like … aren't supported yet."
363- A name that matches nothing in the file: "Can't find … for :var."
364- References to other files.
365
366How a value reaches the code depends on the language:
367
368| Language   | Scalars                 | Lists                          | Tables                                                       |
369|------------+-------------------------+--------------------------------+--------------------------------------------------------------|
370| bash       | quoted string           | indexed array (=declare -a=)   | two or more columns: associative array keyed by the first column (=declare -A=); one column: indexed array |
371| other shells | quoted string         | one item per line              | rows on lines, cells separated by a tab or =:separator=     |
372| fish       | =set name 'value'=      | as other shells                | as other shells                                              |
373| Python     | literal                 | list                           | list of lists, =None= for rules                              |
374| Emacs Lisp | =let=-bound value       | list                           | list of lists, =hline= for rules                             |
375
376For =shell= blocks, the bash forms are used when =SHELL= is bash.
377
378#+BEGIN_SRC org
379,#+NAME: kv
380| a | 1 |
381| b | 2 |
382
383,#+begin_src bash :var t=kv :results output
384echo ${t[a]} ${t[b]}
385,#+end_src
386#+END_SRC
387
388** Tables in variables
389
390A table passed as a variable loses some of its structure first (=org-babel-disassemble-tables=):
391
392- Rules are removed, unless =:hlines yes=.
393- 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.
394- The first column is taken off as row names when =:rownames yes=.
395
396If 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=). =:colnames= and =:rownames= can also be Lisp lists of names to put on the result, such as =:colnames '("x" "y")=.
397
398#+BEGIN_SRC org
399,#+NAME: tbl
400| a | b |
401|---+---|
402| 1 | x |
403| 2 | y |
404
405,#+begin_src python :var t=tbl
406return [r + ["!"] for r in t]
407,#+end_src
408#+END_SRC
409
410** Standard input and arguments
411
412For 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.
413
414#+BEGIN_SRC org
415,#+begin_src sh :cmdline one "two words" :results output
416for a in "$@"; do echo "[$a]"; done
417,#+end_src
418#+END_SRC
419
420* Sessions
421
422=: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 and Python on the Mac.
423
424- =:session= with no name uses =*language*=, such as =*sh*=. =:session none= runs without one.
425- A session belongs to one folder, one interpreter and one name. Blocks in different folders, or with different names, do not share state.
426- A session starts in the block's =:dir=, or the file's folder, the first time it is used.
427- A shell session's output is what the block prints. =:results value= gives the exit status of the last command.
428- A Python session runs the block at top level. Its value is the value of the last expression, so =return= is not used.
429- Sessions stop when you quit Orgstar, or when you cancel a block running in one.
430
431#+BEGIN_SRC org
432,#+begin_src python :session py :results output
433a = 2
434print("set")
435,#+end_src
436
437,#+begin_src python :session py
438a * 3
439,#+end_src
440#+END_SRC
441
442* Caching
443
444With =: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: …").
445
446Change 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.
447
448C, C++, D, Fortran and Clojure blocks don't run in Orgstar, but their hash is taken over the body as tangling expands it (see Tangling below), 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.
449
450* Noweb
451
452A noweb reference =<<name>>= in a block's body stands for other code. Whether references expand depends on =:noweb= and on what is happening:
453
454| =:noweb=        | Running  | Tangling         | Exporting |
455|-----------------+----------+------------------+-----------|
456| =no= (default)  | no       | no               | no        |
457| =yes=           | expands  | expands          | no        |
458| =tangle=        | no       | expands          | no        |
459| =eval=          | expands  | no               | no        |
460| =no-export=     | expands  | expands          | no        |
461| =strip-export=  | expands  | expands          | no        |
462| =strip-tangle=  | expands  | removes the references | no  |
463
464Exported code always shows the references as written; see [[file:12-export.org][Export]].
465
466=<<name>>= expands to the first of these that exists:
467
4681. The contents of the heading whose =ID= property is =name=, or whose =CUSTOM_ID= is =name= without its leading =#=.
4692. The body of the source block named =name=.
4703. The bodies of all blocks with =:noweb-ref name=, joined by each block's =:noweb-sep= (a newline by default).
471
472Blocks under a =COMMENT= heading are skipped. A referenced block expands its own references according to its own =:noweb=, up to 32 levels deep.
473
474Text 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.
475
476#+BEGIN_SRC org
477,#+NAME: greeting
478,#+begin_src sh
479echo hello
480,#+end_src
481
482,#+begin_src sh :noweb yes
483<<greeting>>
484echo world
485,#+end_src
486#+END_SRC
487
488A reference that runs a block, =<<name()>>=, is refused: "Noweb references that run a block (…) aren't supported yet; nothing was run."
489
490* Calls
491
492** =#+CALL:= lines
493
494=#+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.
495
496#+BEGIN_SRC org
497,#+NAME: double
498,#+begin_src sh :var n=2
499echo $((n*2))
500,#+end_src
501
502,#+CALL: double(n=5)
503
504,#+RESULTS:
505: 10
506#+END_SRC
507
508The full form is =#+CALL: name[inside](arguments) end=:
509
510- =name= is the block to run. It must be in the same file.
511- =[inside]= holds header arguments applied to the block, such as =[:results raw]=.
512- =(arguments)= are =:var= assignments, separated by commas.
513- =end= holds header arguments for the call's result, such as =:results verbatim=.
514
515The 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.
516
517The result goes under the call. A =#+NAME:= line above the =#+CALL:= names the result.
518
519** Inline calls and blocks
520
521An 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:
522
523#+BEGIN_SRC org
524Text src_sh{echo hi} {{{results(=hi=)}}} end.
525#+END_SRC
526
527Running 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.
528
529An 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.
530
531* Emacs Lisp blocks
532
533On 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 fails with "Emacs isn't installed, so Emacs Lisp blocks can't run."
534
535On iOS, Emacs Lisp blocks run in Orgstar's own Emacs Lisp interpreter. It covers ordinary list, string, number and control forms, =princ= and =message=. 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.
536
537Variables are bound with =let= around the body. =:results output= collects what the block prints with =princ=, =prin1=, =print= and =terpri=.
538
539* Graphics
540
541=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.
542
543| Language   | Command                                   |
544|------------+-------------------------------------------|
545| =dot=      | =dot -T/ext/ -o file=                      |
546| =plantuml= | =plantuml -p -t/ext/=, output to the file  |
547| =mermaid=  | =mmdc -i input -o file=                    |
548
549A =plantuml= body without an =@start…= line is wrapped in =@startuml= and =@enduml=. =:cmdline= adds options to the command. The program must be installed and on the =PATH= described under Languages that run.
550
551#+BEGIN_SRC org
552,#+begin_src dot :file graph.svg
553digraph { a -> b }
554,#+end_src
555
556,#+RESULTS:
557[[file:graph.svg]]
558#+END_SRC
559
560* Tangling
561
562Tangling writes source blocks to the files their =:tangle= argument names (=org-babel-tangle=).
563
564| Command                 | Emacs and Doom              | Mac    | What it tangles                                   |
565|-------------------------+-----------------------------+--------+---------------------------------------------------|
566| Tangle File             | =C-c C-v t=, =C-c C-v C-t=  | =⌃⌘V=  | Every block in the file                            |
567| Tangle Block            | none                        | none   | The block at the caret (Emacs: =C-u C-c C-v t=)    |
568| Tangle Block's Target   | none                        | none   | Every block going to the same file as the one at the caret (Emacs: =C-u C-u C-c C-v t=) |
569
570All 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/".
571
572** =:tangle= and file names
573
574| =:tangle=         | Target                                                                                          |
575|-------------------+-------------------------------------------------------------------------------------------------|
576| =no= (default)    | Not tangled.                                                                                    |
577| =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=). |
578| a path            | That file, relative to the Org file's folder. =~= is expanded.                                   |
579| Lisp              | Evaluated as described under Lisp in header values, with =buffer-file-name= set to the Org file. |
580
581Blocks under a =COMMENT= heading, or a heading tagged =ARCHIVE=, are skipped. Blocks going to the same file are written in the order they appear.
582
583#+BEGIN_SRC org
584,#+PROPERTY: header-args:python :tangle script.py
585
586,* Tool
587:PROPERTIES:
588:header-args: :tangle bin/tool.sh :mkdirp yes :shebang "#!/bin/sh"
589:END:
590
591,#+begin_src sh
592echo tool
593,#+end_src
594#+END_SRC
595
596** Tangling arguments
597
598| Argument        | Values                                            | Effect                                                                                       |
599|-----------------+---------------------------------------------------+----------------------------------------------------------------------------------------------|
600| =:mkdirp=       | =yes=                                             | Create the target's folder if it is missing.                                                 |
601| =: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. |
602| =:shebang=      | =#!…= line                                        | First line of the file, written once. Makes the file mode =755= unless =:tangle-mode= says otherwise. |
603| =:padline=      | =no=                                              | No blank line between this block and the one before it.                                      |
604| =:comments=     | =no=, =link=, =yes=, =org=, =both=, =noweb=       | Comments around each block (below).                                                          |
605| =:noweb=        | see Noweb above                                   | Expand or strip =<<name>>= references.                                                       |
606| =:prologue=, =:epilogue= | text                                     | A line before and after the block's code.                                                    |
607| =: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. |
608| =:no-expand=    | any                                               | Write the body without =:var=, =:prologue=, =:epilogue= or the language's wrapping.          |
609
610A 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.
611
612=C=, =C++=, =cpp=, =D=, =java=, =fortran= and =clojure= blocks are written as Org's =org-babel-expand-body:LANG= writes them:
613
614| Language       | Written                                                                                                      |
615|----------------+--------------------------------------------------------------------------------------------------------------|
616| =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. |
617| =D=            | =module mmm;=, =import= lines from =:imports= plus =std.stdio= and =std.conv=, the =:var= declarations, and the body wrapped in =int main()= as for C. |
618| =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. |
619| =fortran=      | =#include= and =#define= lines from =:includes= and =:defines=, 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. |
620| =clojure=      | =(ns …)= from =:ns=, the body in a =let= of the =:var= values, and a printer around it unless =:results output=. |
621
622With =:hlines yes=, a table that keeps rules is refused for C, C++, D and Fortran; Java writes =null= for each rule.
623
624Block 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.
625
626** Comments
627
628| =:comments= | Written                                                                                                  |
629|-------------+----------------------------------------------------------------------------------------------------------|
630| =no=        | The code only.                                                                                           |
631| =link=, =yes= | A comment with a link back to the block before the code, and "/name/ ends here" after it.               |
632| =org=       | The Org text between the heading (or the previous block) and this block, as a comment.                   |
633| =both=      | The Org text and the link comments.                                                                      |
634| =noweb=     | Link comments, plus link comments around each expanded noweb reference.                                  |
635
636The 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=.
637
638Comments 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.
639
640** Writing the files
641
642- A file whose contents would not change is left alone, so its modification time stays the same.
643- A read-only file is replaced.
644- Tangling into the Org file itself is refused: "Not allowed to tangle into the same file as self".
645
646** What tangling refuses
647
648Tangling stops, writes nothing and says why when:
649
650- =:var= refers to a source block, which would have to run: "would run a block while tangling".
651- A shell block's =:var= is a table or list.
652- =:var= is used in a language other than shells, Python, Emacs Lisp, C, C++, D, Java, Fortran and Clojure.
653- A C, C++, D or Fortran block's =:var= table keeps rules (with =:hlines yes=), or a value has no type the language takes.
654- A Lisp header value cannot be evaluated: "is Lisp tangling can't evaluate yet; nothing was tangled."
655- =:tangle-mode= is in a form it does not read.
656- =:comments= needs a comment syntax it does not know.
657
658* On iOS
659
660- Only Emacs Lisp blocks run, in Orgstar's own interpreter. Any other language fails with "/language/ blocks need the Mac to run.", and so does an Emacs Lisp block whose =:var= refers to a block in another language.
661- There are no sessions and no graphics.
662- The trust prompt works the same way, with its own =trusted.json= on the device.
663- There is no cancel command.
664- Tangling works, for files in folders Orgstar can write to.
665- Edit Block opens a plain text sheet without highlighting.
666
667See [[file:14-ios.org][iOS]] for the rest of the iOS app.