---
title: Code blocks
subtitle: Pre-highlighted with Shiki at build time (light / dark themes), with zero cost in the browser. Supports titles, line highlighting, focus, diffs, max lines, multi-language tab groups, and language sync.
description: Code fence meta syntax (title, line highlighting, focus, startLine, maxLines, wordWrap, showLineNumbers, for, collapsible, diff), end-of-line annotations, and the CodeGroup, CodeBlock, and Code components.
---

## Basic usage

````mdx
```python
import requests

resp = requests.get("https://api.example.com/v1/sites")
print(resp.json())
```
````

```python
import requests

resp = requests.get("https://api.example.com/v1/sites")
print(resp.json())
```

Every code block has a copy button in the top-right corner. `bash` / `shell` code blocks show a `$` prompt instead of line numbers (continuation lines show `>`), and the prompt isn't copied.

## Meta syntax cheat sheet

The part after the language is called the **meta**, and its options can be combined:

| Syntax | Effect |
|---|---|
| ` ```js Example title ` | Bare text after the language becomes the title |
| ` ```js title="client.ts" ` | Title (`filename=` also works) |
| ` ```js {2-4, 6} ` | Highlight lines 2–4 and 6 (`highlight={2-4}` or `lines=` also work) |
| ` ```js focus={2-4} ` | Focus these lines and dim the rest (restored on hover) |
| ` ```js startLine={6} ` | Start line numbers at 6 |
| ` ```py maxLines=10 ` | Cap the height above 10 lines and scroll inside; default 20, `maxLines=0` means no limit |
| ` ```py maxLines=10 collapsible ` | Use a "Show more" collapse instead of scrolling |
| ` ```txt wordWrap ` | Wrap long lines |
| ` ```bash showLineNumbers={false} ` | Hide line numbers and prompts; `showLineNumbers` forces them on |
| ` ```py for="install" ` | Custom sync group instead of syncing by language |
| ` ```js diff ` | Show lines starting with `+` / `-` as added / removed |
| ` ```diff ` | The diff language |

## Titles and line highlighting

````mdx
```ts title="src/client.ts" {3-5}
import { createClient } from "@acme/sdk";

const client = createClient({
  apiKey: process.env.ACME_API_KEY,
});
```
````

```ts title="src/client.ts" {3-5}
import { createClient } from "@acme/sdk";

const client = createClient({
  apiKey: process.env.ACME_API_KEY,
});
```

## Focus and starting line

```ts title="handler.ts" focus={3-4} startLine={20}
export async function handler(req: Request) {
  const body = await req.json();
  const event = verifySignature(body, req.headers.get("x-signature"));
  await queue.publish(event);
  return new Response(null, { status: 204 });
}
```

## End-of-line annotations

Add annotations in comment form at the end of a line; they're removed at build time and turned into styles:

- `// [!code ++]` / `// [!code --]`: added / removed line
- `// [!code focus]`: focus
- `// [!code highlight]`: highlight
- `// [!code error]` / `// [!code warning]`: error / warning line

The comment marker can be `//`, `#`, `--`, `;`, `/* */`, or `<!-- -->`. The source of the code block below has added and removed annotations at the end of lines 3 and 4:

```yaml title="docs.yml"
languages:
  - lang: zh
    default: true # [!code ++]
  - lang: en
    default: true # [!code --]
```

## Max lines

```json title="manifest.json" maxLines=8
{
  "version": 1,
  "title": "ButterIX",
  "basepath": "",
  "homeSlug": "/guides/get-started/introduction",
  "locales": ["zh", "en"],
  "pages": [
    { "slug": "/guides/get-started/introduction", "title": "ButterIX 文档", "kind": "markdown", "locale": "zh" },
    { "slug": "/guides/get-started/quickstart", "title": "快速开始", "kind": "markdown", "locale": "zh" },
    { "slug": "/en/guides/get-started/quickstart", "title": "Quickstart", "kind": "markdown", "locale": "en" }
  ],
  "ai": { "enabled": true, "suggestions": [] }
}
```

## Color themes

`theme.code` in `docs.yml` sets the code colors of the whole site; `theme="…"` on a fence changes just that block:

````mdx
```ts theme="catppuccin"
export const ok = true;
```
````

```ts title="Catppuccin" theme="catppuccin"
// Every theme has a light and a dark side
export async function greet(name: string) {
  const res = await fetch(`/hi/${name}`, { retries: 3 });
  return res.ok ? res.text() : null;
}
```

```ts title="Rosé Pine" theme="rose-pine"
// Switch the mode in the header to see both
export async function greet(name: string) {
  const res = await fetch(`/hi/${name}`, { retries: 3 });
  return res.ok ? res.text() : null;
}
```

Available: `default`, `github`, `one`, `catppuccin`, `rose-pine`, `vitesse`, `everforest`, `gruvbox`, `solarized`, `night-owl`. Colors that are too faint in some themes (comments, mostly) are strengthened a little so they stay readable. In the editor, hover a code block and click the palette icon; the site's theme is under **Docs settings → Style**.

## Enlarge

The enlarge button on code blocks, code groups and API examples opens the code in a large floating window; press Esc or click outside it to put it back.

## Multi-language tab groups

Put several titled code blocks inside a `<CodeGroup>` (aliases `<CodeBlocks>` and `<CodeTabs>`):

````mdx
<CodeGroup>
```bash cURL
curl https://api.butterix.com/v1/whoami \
  -H "Authorization: Bearer $BITI_TOKEN"
```

```ts TypeScript
const res = await fetch("https://api.butterix.com/v1/whoami", {
  headers: { Authorization: `Bearer ${process.env.BITI_TOKEN}` },
});
```

```python Python
import os, requests

requests.get("https://api.butterix.com/v1/whoami",
             headers={"Authorization": f"Bearer {os.environ['BITI_TOKEN']}"})
```
</CodeGroup>
````

<CodeGroup>
```bash cURL
curl https://api.butterix.com/v1/whoami \
  -H "Authorization: Bearer $BITI_TOKEN"
```

```ts TypeScript
const res = await fetch("https://api.butterix.com/v1/whoami", {
  headers: { Authorization: `Bearer ${process.env.BITI_TOKEN}` },
});
```

```python Python
import os, requests

requests.get("https://api.butterix.com/v1/whoami",
             headers={"Authorization": f"Bearer {os.environ['BITI_TOKEN']}"})
```
</CodeGroup>

### Language sync

Once a reader picks a language in any code group, every code group containing that language on the page, every `<Tabs>` with `language`, and the API examples switch together. The choice is remembered (it still applies on the next visit). Add `?lang=python` to the URL to force a language.

The code group below is linked to the one above — try switching:

<CodeGroup>
```python Python
print("I switch together with the Python tab above")
```

```bash cURL
echo "I switch together with the cURL tab above"
```
</CodeGroup>

To sync along a different dimension (e.g. "package manager"), set a sync group with `for`:

````mdx
<CodeGroup>
```bash npm for="pm"
npm install -g bitidocs
```

```bash pnpm for="pm"
pnpm add -g bitidocs
```
</CodeGroup>
````

## The CodeBlock component

When you need props to control a code block, wrap the fenced code in a `<CodeBlock>`:

````mdx
<CodeBlock title="Link to docs" links={{ "createClient": "/api-reference" }} maxLines={0}>
```ts
const client = createClient();
```
</CodeBlock>
````

<CodeBlock title="Link to docs" links={{ "createClient": "/api-reference" }} maxLines={0}>
```ts
const client = createClient();
```
</CodeBlock>

`links` turns text in the code (or a `/regex/`) into links, which is handy for linking SDK method names to reference pages. See the [CodeBlock component](../components/code-block.mdx) for all props.

## Embedding files

`<Code src>` reads a file from the project (or a URL) at build time and highlights it, which keeps docs in sync with real code:

```mdx
<Code src="/versions/v0.yml" lines="1-3" title="versions/v0.yml (first 3 lines)" />
```

<Code src="/versions/v0.yml" lines="1-3" title="versions/v0.yml (first 3 lines)" />

<Warning>
  Write line-number props like `lines` and `highlight` as a string (`"1-3, 5"`) or an array of strings (`{["1-3", 5]}`). Don't write `{[1-3]}`: `1-3` is a subtraction expression, and props only allow literals.
</Warning>

## Mermaid

Code blocks with the language `mermaid` render as diagrams; see [Math and diagrams](./math-and-diagrams.mdx).
