A code block in Starlight shows code, but readers must copy it to a terminal to see what it does. The runnable attribute adds a Run code button under the block. The button runs the code in the browser and shows the output above the button.
Readers see
from statistics import mean, stdev
reads = [1520, 1610, 1480, 1575]print(f"mean {mean(reads):.0f}, sd {stdev(reads):.1f}")You write
```py runnablefrom statistics import mean, stdev
reads = [1520, 1610, 1480, 1575]print(f"mean {mean(reads):.0f}, sd {stdev(reads):.1f}")```Click Run code. The first time, the browser downloads Python (Pyodide, a build of Python for the browser), which takes a few seconds. The output panel shows “Loading the Python runtime…” until it is ready, then the output of the code.
Syntax
Section titled “Syntax”| Syntax | Where |
|---|---|
runnable |
Code block fence line |
runnable.label="<text>", runnable.againLabel="<text>" |
Code block fence line |
runnable.timeout=<ms> |
Code block fence line |
runnable.packages="<name> <name>" |
Code block fence line |
runnable.button="below", runnable.button="title", runnable.button="both" |
Code block fence line |
[!run], [!run lang=<language>], [!run end] |
Comment in the code, on its own line |
[!output], [!output stdout], [!output stderr], [!output end], with lang=<language> after the stream |
Comment in the code, on its own line |
[!wait <ms>] |
Comment at the end of a line of output |
[!code highlight], [!code error], [!code warning], [!code info], [!code success] |
Comment at the end of a line of output |
runnable.output="<text>", runnable.outputDelay=<ms> |
Code block fence line |
runnable.outputFile="<path>" |
Code block fence line |
runnable.outputLang=<language> |
Code block fence line |
runnable.static |
Code block fence line |
Languages
Section titled “Languages”The language of the block chooses the runtime. Three languages work with no set-up:
| Language | Fence language | Runtime |
|---|---|---|
| Python | py, python, pycon |
Pyodide, a build of Python for the browser. It downloads from a CDN on the first click. |
| JavaScript | js, javascript, mjs, cjs |
The browser’s own JavaScript engine, in a web worker. |
| TypeScript | ts, typescript, mts, cts |
The JavaScript runtime, after Sucrase removes the types. |
- For other languages, a site adds a runtime in the
runtimesoption. The guide to adding a runtime shows how. - A site runtime for Python, JavaScript or TypeScript replaces the built-in one.
- Sites without
codeblocks()add each runtime themselves, as in Without codeblocks().
In JavaScript and TypeScript, console.log() and console.info() go to standard output. console.error() and console.warn() go to standard error. The code runs as the body of an async function, so await works at the top level. The code cannot use import statements.
The TypeScript runtime removes the types and does not check them. Code with a type error runs, as it would with tsx or Node.js. The runtime downloads Sucrase (about 50 kB) on the first click of a TypeScript block.
Python packages
Section titled “Python packages”The Python runtime reads the import lines of the code before it runs it, and installs the packages they need:
- Packages that are part of Pyodide install from the Pyodide CDN. Pyodide has about 350 packages, such as NumPy, pandas, SciPy and scikit-learn. The Pyodide package list has them all.
- Other imports install from PyPI with micropip, under the name of the import. This works for pure Python packages: packages with a wheel that ends in
py3-none-any.whl.
When the package name is not the import name, add runnable.packages to the fence line. For example, import slugify needs the python-slugify package. Without the attribute, the runtime would install the package called slugify, which is a different one. Separate several packages with spaces. A name can have a version, such as tabulate==0.9.0. The packages install before the code runs, and a package that does not install shows an error in the panel.
For code that cannot run in the browser, such as a command line tool, write its output in the block. The lines after [!output] are the output. They leave the code, and the button prints them a line at a time, as if the code ran. [!output end] ends the output, for code after it. Without it, the output goes to the next [!run] line or the end of the block.
The lines after [!output stderr] print as standard error, and the lines after [!output stdout] as standard output again. Each switch starts a new part of the output, as in a real run.
The block needs no runnable attribute and no runtime, so it works in every language. [!wait <ms>] on a line of output waits that long before the next line.
[!code highlight] and the line state directives mark a line of output, as they mark a line of code. [!wait] and a mark can share one comment, such as # [!wait 1000] [!code highlight]. Ranges on the fence line, such as {2}, count the lines of code only.
runnable.output on the fence line does the same, with \n for each new line.
Output from a file
Section titled “Output from a file”runnable.outputFile reads the output from a file when the site builds, such as a file that a tool writes from a real run. The path is relative to the page, as the path of an image is:
```sh runnable.outputFile="./output/check.ansi"make check```The output in a file is from a run before the build, so the block shows it from the start, as runnable.static does. Add runnable to the fence line to show the Run code button, which prints the output a line at a time.
The file is the whole output, as in runnable.output. Directives in it, such as [!wait], stay as text. A file that ends in .ansi is in the ansi language, unless the block sets runnable.outputLang. Output on the fence line replaces [!output] lines in the block. If the file is missing, the build gives a warning, and the block shows its [!output] lines or runnable.output, if it has them. In astro dev, a change to the file reloads the page.
Output in a language
Section titled “Output in a language”runnable.outputLang on the fence line highlights the scripted output in a language. With ansi, the terminal colour codes in the output become colours, as in a terminal. Other languages, such as json or yaml, highlight as code does.
With ansi, the output of a real run shows its colours too. Python libraries such as Rich print colours only to a terminal, so set the FORCE_COLOR environment variable in the code, or in hidden lines.
lang= on an [!output] line sets the language of the lines after it, up to the next [!output] line. For example, [!output stderr lang=txt] keeps an error in plain text in a block of ansi output. txt and plaintext keep the stream colours.
Libraries such as Rich draw panels with box-drawing characters. Many code fonts do not have them, so the lines of a panel do not join. The codeblocksRunnable.outputFontFamily and outputLineHeight style settings give the output a font that has them, such as Fira Code, and a line height near 1.25:
export default { styleOverrides: { codeblocksRunnable: { outputFontFamily: "'Fira Code', monospace", outputLineHeight: '1.25' }, },};In ansi output, \e[, \x1b[, \033[ and \u001b[ stand for the escape character. This lets you write colour codes on the fence line, or by hand in the block. For output that prints \e[ itself, such as a regular expression, write \\e[. On the fence line, Expressive Code removes one backslash first, so write \\\\e[ there. A file from runnable.outputFile holds the escape character itself, so \e[ in a file stays as text.
Output from the start
Section titled “Output from the start”runnable.static shows the scripted output under the block when the page loads, with no button. The output is part of the page, so the block needs no JavaScript. Use it to show what a command prints, as a screenshot of a terminal would.
Other code to run
Section titled “Other code to run”The lines after [!run] are the code that runs, in place of the code that readers see. They leave the block, up to [!run end], the next [!output] line or the end of the block. With lang=, they run on the runtime of that language. So a terminal block can show a command, and run Python that prints what the command prints. The copy button copies the command.
Examples
Section titled “Examples”JavaScript, with standard error
Section titled “JavaScript, with standard error”console.log() goes to standard output and console.error() to standard error:
const sizes = [3, 1, 4, 1, 5];const total = sizes.reduce((sum, size) => sum + size, 0);console.log('Total:', total);console.error('Sizes of 1 are deprecated.');```js runnableconst sizes = [3, 1, 4, 1, 5];const total = sizes.reduce((sum, size) => sum + size, 0);console.log('Total:', total);console.error('Sizes of 1 are deprecated.');```TypeScript
Section titled “TypeScript”A TypeScript block runs after the runtime removes the types:
interface Sample { id: string; reads: number;}
const samples: Sample[] = [ { id: 'S1', reads: 1520 }, { id: 'S2', reads: 1610 },];const total = samples.reduce((sum: number, s: Sample) => sum + s.reads, 0);console.log(`${samples.length} samples, ${total} reads`);```ts runnableinterface Sample { id: string; reads: number;}
const samples: Sample[] = [ { id: 'S1', reads: 1520 }, { id: 'S2', reads: 1610 },];const total = samples.reduce((sum: number, s: Sample) => sum + s.reads, 0);console.log(`${samples.length} samples, ${total} reads`);```A package that Pyodide does not have
Section titled “A package that Pyodide does not have”Tabulate is not part of Pyodide, so the runtime installs it from PyPI. The import name is the package name, so the block needs no attribute:
from tabulate import tabulate
print(tabulate([["S1", 1520], ["S2", 1610]], headers=["Sample", "Reads"]))```py runnablefrom tabulate import tabulate
print(tabulate([["S1", 1520], ["S2", 1610]], headers=["Sample", "Reads"]))```A package with another name
Section titled “A package with another name”The import is slugify, but the package is python-slugify, so runnable.packages names it:
from slugify import slugify
print(slugify("Hello, World: Run Code!"))```py runnable runnable.packages="python-slugify"from slugify import slugify
print(slugify("Hello, World: Run Code!"))```An error
Section titled “An error”An error in Python shows the traceback, from the line of the example that failed:
counts = {"passed": 3, "failed": 0}print(counts["passed"] / counts["failed"])```py runnablecounts = {"passed": 3, "failed": 0}print(counts["passed"] / counts["failed"])```The timeout
Section titled “The timeout”Code that never ends stops at the timeout. This loop waits for a value that never changes, so the panel shows the timeout message after 5 seconds:
Scripted output
Section titled “Scripted output”This command cannot run in the browser, so the block has the output that the command prints. The lines show one at a time, 200 milliseconds apart, with a longer wait while the task runs:
nextflow run hello.nf```shnextflow run hello.nf# [!output]N E X T F L O W ~ version 25.04.0Launching hello.nf [nice_curie] DSL2executor > local (3) # [!wait 1500][4e/8a1f2c] sayHello (3) | 3 of 3 ✔Hello world!Bonjour le monde!Hola mundo!```A failed run
Section titled “A failed run”The run log prints as standard output, then the error as standard error, so readers see where the run failed:
nextflow run hello-channels.nf```shnextflow run hello-channels.nf# [!output]executor > local (1)[a8/1f6ead] sayHello (1) | 0 of 1 # [!wait 1000]# [!output stderr]ERROR ~ Error executing process > 'sayHello (1)'
Caused by: Missing output file(s) `[Hello, Bonjour, Hola]-output.txt` expected by process `sayHello (1)````Marks in the output
Section titled “Marks in the output”Marks point readers at the lines that matter in both parts of a failed run. Each mark shows when its line prints:
nextflow run hello-channels.nf```shnextflow run hello-channels.nf# [!output]executor > local (1)[a8/1f6ead] sayHello (1) | 0 of 1[Hello, Bonjour, Hola] # [!code highlight] [!wait 1000]# [!output stderr]ERROR ~ Error executing process > 'sayHello (1)' # [!code error]
Caused by: Missing output file(s) `[Hello, Bonjour, Hola]-output.txt` expected by process `sayHello (1)` # [!code highlight]```Output only
Section titled “Output only”A block with only output shows the button in the middle of the empty code area. The button fades out when a reader clicks it, and the output takes its place:
```sh# [!output]Pulling nextflow-io/hello ... downloaded from https://github.com/nextflow-io/hello.git # [!wait 1000]Hello world!```Coloured terminal output
Section titled “Coloured terminal output”The help text of a command line tool has colours. runnable.outputLang=ansi shows them, and runnable.static shows the output with no button:
python hello.py --helpUsage: hello.py [OPTIONS] Greets NAME for a total of COUNT times. ╭─ Options ───────────────────────────────╮ │ --count INTEGER Number of greetings. │ │ --name TEXT The person to greet. │ ╰─────────────────────────────────────────╯
```sh runnable.static runnable.outputLang=ansipython hello.py --help# [!output]\e[33mUsage:\e[0m \e[1mhello.py\e[0m [OPTIONS]
Greets NAME for a total of COUNT times.
\e[2m╭─ Options ───────────────────────────────╮\e[0m\e[2m│\e[0m \e[1;36m--count\e[0m \e[1;33mINTEGER\e[0m Number of greetings. \e[2m│\e[0m\e[2m│\e[0m \e[1;36m--name\e[0m \e[1;33mTEXT \e[0m The person to greet. \e[2m│\e[0m\e[2m╰─────────────────────────────────────────╯\e[0m```Coloured output from a run
Section titled “Coloured output from a run”The code prints terminal colour codes, and runnable.outputLang=ansi shows them as colours:
const green = (text) => `\x1b[32m${text}\x1b[0m`;const bold = (text) => `\x1b[1m${text}\x1b[0m`;console.log(`${green('✔')} Built in ${bold('2.1s')}`);```js runnable runnable.outputLang=ansiconst green = (text) => `\x1b[32m${text}\x1b[0m`;const bold = (text) => `\x1b[1m${text}\x1b[0m`;console.log(`${green('✔')} Built in ${bold('2.1s')}`);```A command that runs Python
Section titled “A command that runs Python”The terminal shows the command, and the button runs the Python after [!run]:
python greet.py --name Ada --count 2```shpython greet.py --name Ada --count 2# [!run lang=python]for _ in range(2): print("Hello, Ada!")```The button in the title bar
Section titled “The button in the title bar”runnable.button="title" puts the button in the title bar, as the copy button is. both shows the button in both places:
print(sorted(["chr2", "chr10", "chr1"], key=lambda c: int(c[3:])))```py runnable runnable.button="title"print(sorted(["chr2", "chr10", "chr1"], key=lambda c: int(c[3:])))```Behaviour
Section titled “Behaviour”- Running code:
- The button is under the block, in the style of the code walkthrough buttons. The
buttonoption moves it to the title bar, or shows it in both places. - The runtime loads only when a reader clicks Run code for the first time. A page with runnable blocks loads a small script, and no runtime.
- After the first run, the button reads Run again. Each run replaces the output of the run before it. The
labelandagainLabeloptions change the two texts, for example for a site in another language. - The code that runs is the copied text of the block, or the lines after
[!run]. Directives are removed, and hidden lines are kept. The values that readers type into fill-in placeholders are part of it too. For a Python session with>>>prompts, only the commands run, as Copy commands copies them. They run as in the Python REPL, so the output shows the value of each expression. - Every runtime runs the code in a web worker, so the page stays responsive while code runs. Each run starts with no names from earlier runs. In Python,
__name__is"__main__". - In JavaScript and TypeScript, a run ends when the top-level code is done. Output from a timer or a callback that the code does not
awaitis lost. - A run stops after 10 seconds, with a message in the panel. The download of the runtime and of the packages that the code imports does not count towards this time.
- The button is under the block, in the style of the code walkthrough buttons. The
- Scripted output:
- The panel shows “Running…”, then the lines of output, with
outputDelaymilliseconds (200 by default) before each line. With0, all the lines show at once.[!wait]changes the wait after one line. - Scripted output shows as standard output, and the lines after
[!output stderr]as standard error. The button does not run the code, and the block needs no runtime. - The output lines are not part of the code that readers see or copy.
- A mark on a line of output shows the tint, the bar, the name and the message that it shows on a line of code. The text of the line takes the colour of the name, so that it stays readable on the tint.
- A block with only output has no copy button. Its Run code button is in the middle of the empty code area, and fades out on the first click. Keyboard focus then moves to the output.
- With
runnable.static, or withrunnable.outputFileand norunnable, the output panel shows from the start, and the block has no button. A block with only output shows the panel in place of the code area.
- The panel shows “Running…”, then the lines of output, with
- Output:
- Long lines of output scroll sideways, as code does, so that tables and panels keep their shape. With the
wrapattribute, they wrap. A panel with lines that scroll takes keyboard focus, so readers can scroll it with the arrow keys. - The output panel has no visible label; the
outputLabeloption shows the label “Output” at its top. Standard output shows in green. Standard error shows in red, with a bar at its start, so the colour is not the only difference. - Output in a language has the colours of the language in place of green or red. In scripted output, each colour is lightened or darkened to 4.5:1 on its background in each theme, so terminal colours and dim text stay readable. A background colour shows as a light tint. A marked line of output shows its text in the colour of the mark.
- In the output of a run, the 16 terminal colours come from the theme at 4.5:1, through the
codeblocksRunnablestyle settings. Dim text takes the muted text colour, and a background colour shows as a light tint, so the text on it stays readable. Colours from the 256-colour palette and RGB colours show as the code prints them.
- Long lines of output scroll sideways, as code does, so that tables and panels keep their shape. With the
- Keyboard and screen readers:
- The output panel is a polite live region, except with
runnable.static, where the output does not change. Screen readers announce the loading message and the output when they change. - Screen readers read “Output” before the output, with or without
outputLabel, and “Error:” before standard error. Before a line of output with a line state, they read the name of the state, as for a line of code. - The button keeps the keyboard focus during a run, so readers can run the code again with Enter or Space.
- The output panel is a polite live region, except with
- Print:
- The button does not print.
- Without JavaScript:
- The button is hidden.
Options
Section titled “Options”runnable
Section titled “runnable”Adds a button that runs the code in the browser. Set it to false to turn the feature off. runnable attributes then have no effect.
- Type
false | object- Default
- On
runnable.runtimes
Section titled “runnable.runtimes”Runtime modules by language: a package path, or a path from the project root. The site entries are added to the built-in Python, JavaScript and TypeScript runtimes, or replace them.
- Type
Record<string, string>- Default
python,javascriptandtypescript
runnable.timeout
Section titled “runnable.timeout”Milliseconds before a run stops, from 1 to 2147483647, the largest delay browsers accept. A code block can set its own on its fence line.
- Type
number- Default
10000
runnable.label
Section titled “runnable.label”The text of the button, in place of the translations. A code block can set its own on its fence line.
- Type
string- Default
'Run code', or its translation
runnable.againLabel
Section titled “runnable.againLabel”The text of the button after the first run, in place of the translations. A code block can set its own on its fence line.
- Type
string- Default
'Run again', or its translation
runnable.button
Section titled “runnable.button”Where the button goes: under the block, in the title bar, or both. A code block can set its own on its fence line.
- Type
'below' | 'title' | 'both'- Default
'below'
runnable.outputDelay
Section titled “runnable.outputDelay”Milliseconds between the lines of scripted output (runnable.output), so that it prints as if the code ran. 0 prints it all at once. A code block can set its own on its fence line.
- Type
number- Default
200
runnable.outputLabel
Section titled “runnable.outputLabel”Shows an **Output** label at the top of the output panel. Screen readers hear the label either way.
- Type
boolean- Default
false
A runtime module is a package path, or a path from the project root. This site gives runs 5 seconds, and a site with a Ruby runtime adds it to runtimes:
codeblocks({ runnable: { runtimes: { ruby: './src/runtimes/ruby.ts' }, timeout: 5000, },});The guide to adding a runtime shows how to write one.
Limitations
Section titled “Limitations”- The code must be complete to run. Put the imports and set-up in hidden lines if they distract from the example.
- The Python runtime has no standard input, so
input()fails. - Python packages from PyPI must be pure Python. A package with compiled code works only if it is part of Pyodide.
- JavaScript and TypeScript code cannot
importmodules, and has no access to the page. - TypeScript blocks with JSX (
tsx) do not run. - The Python runtime loads Pyodide from the jsDelivr CDN, and packages from PyPI. Every runtime runs its worker from a
blob:URL. A Content Security Policy must allow all three. - To stop a Python run, the runtime ends its worker. The next run downloads the runtime again, from the browser cache if the browser kept it.
- In the output of a real run,
runnable.outputLangshowsansicolours only. Other languages show as plain text, with a build warning. - In the
<Code>component, the path ofrunnable.outputFileis relative to the project root, because the block is not on a Markdown page. - Marks on lines of output need line states. With the
lineStatesoption off,[!code highlight]on a line of output gives a warning. Other directives that mark lines, such as[!code focus]or[!code ++], have no effect on a line of output.
Related
Section titled “Related”- Open in playground: send the code to an online playground, for languages that cannot run in the browser.
- Hidden lines: keep the code complete for the Run code button, while readers see only the part you explain.
- Add a runtime: run another language, with the interface that the built-in runtimes use.