---
title: "Run code"
description: "Add a Run code button that runs the example in the browser and shows the output under the block."
url: "https://ewels.github.io/starlight-codeblocks/features/run-code/"
markdown: "https://ewels.github.io/starlight-codeblocks/features/run-code.md"
section: "Copy and run"
site: "starlight-codeblocks documentation"
context: "This page is from the documentation of starlight-codeblocks. A plugin for Starlight and Astro that adds focus, line states, annotations, API auto-linking and 24 more features to the code blocks of a site."
index: "https://ewels.github.io/starlight-codeblocks/llms.txt"
---

# Run code

> Add a Run code button that runs the example in the browser and shows the output under the block.

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.

````md
```py runnable
from 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

| 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.args="<arguments>"` | 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

The language of the block chooses the runtime. Three languages work with no set-up:

| Language | Fence language | Runtime |
|---|---|---|
| Python | `py`, `python`, `pycon` | [Pyodide](https://pyodide.org/), 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](https://sucrase.io/) removes the types. |

- For other languages, a site adds a runtime in the [`runtimes` option](#options). The guide to [adding a runtime](https://ewels.github.io/starlight-codeblocks/extend/add-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()](https://ewels.github.io/starlight-codeblocks/reference/expressive-code-plugins/#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

The Python runtime reads the `import` lines of the code before it runs it, and installs the packages they need:

1. 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](https://pyodide.org/en/stable/usage/packages-in-pyodide.html) has them all.
2. Other imports install from [PyPI](https://pypi.org/) with [micropip](https://micropip.pyodide.org/), under the name of the import. This works for pure Python packages: packages with a wheel that ends in `py3-none-any.whl`.

PyPI reads `_`, `-` and `.` in a package name as the same character, and ignores case. So `import rich_click` installs the `rich-click` package, with no attribute.

When the package name is a different name, not only a different spelling, 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](https://ewels.github.io/starlight-codeblocks/features/line-states/) 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.

### Command line arguments

`runnable.args` gives the code the arguments of a command line. Separate the arguments with spaces, and put quotes around an argument that has spaces, such as `runnable.args="--name 'Ada Lovelace'"`. The title of the block is the name of the program. A block without a title runs as `main.py`.

In Python, `sys.argv` holds the name and the arguments, as it does for `python hello.py --count 2`. So a command line tool made with [argparse](https://docs.python.org/3/library/argparse.html), [Click](https://click.palletsprojects.com/) or [Typer](https://typer.tiangolo.com/) runs with no change to its code:

- `sys.exit()` ends the run as it ends a program, with no traceback. An exit message that is not a number shows as standard error.
- The `COLUMNS` environment variable is the width of the output panel, in characters. Help text that reads it, such as the help of argparse and Rich, fits the panel. Click makes its help at least 50 characters wide, so on a narrow screen its help can scroll.

The JavaScript and TypeScript runtimes do not read the arguments.

### 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:

````md
```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

`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 the Python runtime sets the `FORCE_COLOR` environment variable for a run with `ansi` output.

`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](https://ewels.github.io/starlight-codeblocks/reference/style-settings/) give the output a font that has them, such as Fira Code, and a line height near 1.25:

```js title="ec.config.mjs"
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

`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

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

### JavaScript, with standard error

`console.log()` goes to standard output and `console.error()` to standard error:

````md
```js runnable
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.');
```
````

### TypeScript

A TypeScript block runs after the runtime removes the types:

````md
```ts runnable
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`);
```
````

### 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:

````md
```py runnable
from tabulate import tabulate

print(tabulate([["S1", 1520], ["S2", 1610]], headers=["Sample", "Reads"]))
```
````

### A package with another name

The import is `slugify`, but the package is `python-slugify`, so `runnable.packages` names it:

````md
```py runnable runnable.packages="python-slugify"
from slugify import slugify

print(slugify("Hello, World: Run Code!"))
```
````

### A command line tool

The title gives the program name in the usage line, and `runnable.args` gives the arguments. The code is the same as in a file that runs in a terminal:

````md
```py runnable title="hello.py" runnable.args="--help"
import click

@click.command()
@click.option("--count", default=1, help="Number of greetings.")
@click.argument("name")
def hello(count, name):
    """Greet NAME, COUNT times."""
    for _ in range(count):
        click.echo(f"Hello, {name}!")

if __name__ == "__main__":
    hello()
```
````

The help of a [Typer](https://typer.tiangolo.com/) app needs two packages that Pyodide does not install with Rich, so add `runnable.packages="markdown-it-py pygments"` to the fence line. For the colours of [rich-click](https://ewels.github.io/rich-click/) or Typer, add [`runnable.outputLang=ansi`](#output-in-a-language).

### An error

An error in Python shows the traceback, from the line of the example that failed:

````md
```py runnable
counts = {"passed": 3, "failed": 0}
print(counts["passed"] / counts["failed"])
```
````

### 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:

````md
```js runnable
let ready = false;
while (!ready) {}
```
````

### 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:

````md
```sh
nextflow run hello.nf
# [!output]
N E X T F L O W  ~  version 25.04.0
Launching hello.nf [nice_curie] DSL2
executor >  local (3) # [!wait 1500]
[4e/8a1f2c] sayHello (3) | 3 of 3 ✔
Hello world!
Bonjour le monde!
Hola mundo!
```
````

### A failed run

The run log prints as standard output, then the error as standard error, so readers see where the run failed:

````md
```sh
nextflow 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

Marks point readers at the lines that matter in both parts of a failed run. Each mark shows when its line prints:

````md
```sh
nextflow 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

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:

````md
```sh
# [!output]
Pulling nextflow-io/hello ...
 downloaded from https://github.com/nextflow-io/hello.git # [!wait 1000]
Hello world!
```
````

### 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:

````md
```sh runnable.static runnable.outputLang=ansi
python 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

The code prints terminal colour codes, and `runnable.outputLang=ansi` shows them as colours:

````md
```js runnable runnable.outputLang=ansi
const green = (text) => `\x1b[32m${text}\x1b[0m`;
const bold = (text) => `\x1b[1m${text}\x1b[0m`;
console.log(`${green('✔')} Built in ${bold('2.1s')}`);
```
````

In Python, [Rich](https://rich.readthedocs.io/) prints its colours, because the runtime sets `FORCE_COLOR` for a run with `ansi` output:

````md
```py runnable runnable.outputLang=ansi
from rich import print

print("[bold green]✔ Built[/bold green] in 2.1s")
```
````

### A command that runs Python

The terminal shows the command, and the button runs the Python after `[!run]`:

````md
```sh
python greet.py --name Ada --count 2
# [!run lang=python]
for _ in range(2):
    print("Hello, Ada!")
```
````

### 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:

````md
```py runnable runnable.button="title"
print(sorted(["chr2", "chr10", "chr1"], key=lambda c: int(c[3:])))
```
````

## Behaviour

- Running code:
  - The button is under the block, in the style of the [code walkthrough](https://ewels.github.io/starlight-codeblocks/features/code-walkthrough/) buttons. The `button` option 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 `label` and `againLabel` options 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](https://ewels.github.io/starlight-codeblocks/features/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 `await` is 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.
- Scripted output:
  - The panel shows "Running…", then the lines of output, with `outputDelay` milliseconds (200 by default) before each line. With `0`, 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 with `runnable.outputFile` and no `runnable`, 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.
- Output:
  - Long lines of output scroll sideways, as code does, so that tables and panels keep their shape. With the `wrap` attribute, 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 `outputLabel` option 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 `codeblocksRunnable` style 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.
- 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 <kbd>Enter</kbd> or <kbd>Space</kbd>.
- Print:
  - The button does not print.
- Without JavaScript:
  - The button is hidden.

## Options

### `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`

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`, `javascript` and `typescript`

### `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`

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`

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`

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`

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`

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`:

```js title="astro.config.mjs"
codeblocks({
  runnable: {
    runtimes: { ruby: './src/runtimes/ruby.ts' },
    timeout: 5000,
  },
});
```

The guide to [adding a runtime](https://ewels.github.io/starlight-codeblocks/extend/add-a-runtime/) shows how to write one.

- [Configuration](https://ewels.github.io/starlight-codeblocks/configuration/): Learn how to set options for the whole site, or for a single code block.

## Limitations

- The code must be complete to run. Put the imports and set-up in [hidden lines](https://ewels.github.io/starlight-codeblocks/features/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 `import` modules, 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.outputLang` shows `ansi` colours only. Other languages show as plain text, with a build warning.
- In the `<Code>` component, the path of `runnable.outputFile` is relative to the project root, because the block is not on a Markdown page.
- Marks on lines of output need line states. With the `lineStates` option 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

- [Open in playground](https://ewels.github.io/starlight-codeblocks/features/open-in-playground/): send the code to an online playground, for languages that cannot run in the browser.
- [Hidden lines](https://ewels.github.io/starlight-codeblocks/features/hidden-lines/): keep the code complete for the **Run code** button, while readers see only the part you explain.
- [Add a runtime](https://ewels.github.io/starlight-codeblocks/extend/add-a-runtime/): run another language, with the interface that the built-in runtimes use.
