---
title: 代码块
subtitle: 构建时用 Shiki 预先高亮（浅色 / 深色双主题），浏览器端零开销。支持标题、行高亮、聚焦、diff、最大行数、多语言标签组和语言同步。
description: 代码围栏的 meta 语法（title、行高亮、focus、startLine、maxLines、wordWrap、showLineNumbers、for、collapsible、diff）、行尾标注、CodeGroup、CodeBlock 与 Code 组件。
---

## 基本用法

````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())
```

每个代码块右上角都有复制按钮。`bash` / `shell` 代码块用 `$` 提示符代替行号（续行显示 `>`），复制时提示符不会被复制。

## meta 语法速查

语言后面的部分称为 **meta**，可以组合使用：

| 写法 | 效果 |
|---|---|
| ` ```js 示例标题 ` | 语言后的裸文字作为标题 |
| ` ```js title="client.ts" ` | 标题（也可以写 `filename=`） |
| ` ```js {2-4, 6} ` | 高亮第 2–4 行和第 6 行（也可以写 `highlight={2-4}` 或 `lines=`） |
| ` ```js focus={2-4} ` | 聚焦这些行，其余行变暗（悬停代码块时恢复） |
| ` ```js startLine={6} ` | 行号从 6 开始 |
| ` ```py maxLines=10 ` | 超过 10 行时限高，在框内滚动；默认 20，`maxLines=0` 不限制 |
| ` ```py maxLines=10 collapsible ` | 用「显示更多」折叠代替滚动 |
| ` ```txt wordWrap ` | 自动换行 |
| ` ```bash showLineNumbers={false} ` | 隐藏行号与提示符；`showLineNumbers` 强制显示 |
| ` ```py for="install" ` | 自定义同步分组，代替按语言同步 |
| ` ```js diff ` | 把 `+` / `-` 开头的行显示为新增 / 删除 |
| ` ```diff ` | diff 语言 |

## 标题与行高亮

````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,
});
```

## 聚焦与起始行

```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 });
}
```

## 行尾标注

在行尾加注释形式的标注，构建时会被移除并转换为样式：

- `// [!code ++]` / `// [!code --]`：新增 / 删除行
- `// [!code focus]`：聚焦
- `// [!code highlight]`：高亮
- `// [!code error]` / `// [!code warning]`：错误 / 警告行

注释符号可以是 `//`、`#`、`--`、`;`、`/* */` 或 `<!-- -->`。下面这个代码块的源码在第 3、4 行行尾写了新增和删除标注：

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

## 最大行数

```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": [] }
}
```

## 配色

`docs.yml` 的 `theme.code` 设定全站的代码配色，围栏里写 `theme="…"` 只改这一块：

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

```ts title="Catppuccin" theme="catppuccin"
// 每种配色都有亮色和暗色两套
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"
// 切换页头的深浅模式看看
export async function greet(name: string) {
  const res = await fetch(`/hi/${name}`, { retries: 3 });
  return res.ok ? res.text() : null;
}
```

可选：`default`、`github`、`one`、`catppuccin`、`rose-pine`、`vitesse`、`everforest`、`gruvbox`、`solarized`、`night-owl`。个别配色里过淡的颜色（多是注释）会略微加深，保证读得清。在编辑器里，悬停代码块后点调色板图标选择；全站配色在「文档设置 → 样式」。

## 放大

代码块、代码组和接口示例右上角的放大按钮，会把代码放进一个浮在页面上的大窗口；按 Esc 或点窗口外面收回原处。

## 多语言标签组

把多个带标题的代码块放进 `<CodeGroup>`（别名 `<CodeBlocks>`、`<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` 的 `<Tabs>` 以及 API 示例会一起切换，选择会被记住（下次访问依然生效）。URL 中加 `?lang=python` 可以强制指定。

下面这个代码组和上面的代码组是联动的，试着切换一下：

<CodeGroup>
```python Python
print("我会和上面的 Python 标签一起切换")
```

```bash cURL
echo "我会和上面的 cURL 标签一起切换"
```
</CodeGroup>

需要按其他维度同步（例如「包管理器」）时，用 `for` 指定同步分组：

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

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

## CodeBlock 组件

需要用属性控制代码块时，可以把围栏代码包在 `<CodeBlock>` 中：

````mdx
<CodeBlock title="链接到文档" links={{ "createClient": "/api-reference" }} maxLines={0}>
```ts
const client = createClient();
```
</CodeBlock>
````

<CodeBlock title="链接到文档" links={{ "createClient": "/api-reference" }} maxLines={0}>
```ts
const client = createClient();
```
</CodeBlock>

`links` 把代码中的文字（或 `/正则/`）变成链接，适合把 SDK 方法名链接到参考页。全部属性见[CodeBlock 组件](../components/code-block.mdx)。

## 嵌入文件

`<Code src>` 在构建时读取项目里的文件（或一个 URL）并高亮，适合让文档与真实代码保持同步：

```mdx
<Code src="/versions/v0.yml" lines="1-3" title="versions/v0.yml（前 3 行）" />
```

<Code src="/versions/v0.yml" lines="1-3" title="versions/v0.yml（前 3 行）" />

<Warning>
  `lines`、`highlight` 等行号属性请写成字符串（`"1-3, 5"`）或字符串数组（`{["1-3", 5]}`）。不要写成 `{[1-3]}`：`1-3` 是一个减法表达式，而属性只允许字面量。
</Warning>

## Mermaid

语言写成 `mermaid` 的代码块会渲染为图表，见[公式与图表](./math-and-diagrams.mdx)。
