> ## Documentation Index
> Fetch the complete documentation index at: https://adminroletesting-justin-client-exports.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# 格式化代码

> 在文档中格式化代码，支持语法高亮、行号、差异对比、复制按钮和 MDX 中的交互式代码组功能。

<div id="adding-code-samples">
  ## 添加代码示例
</div>

你可以添加行内代码片段或代码块。代码块支持用于语法高亮、标题、行高亮、icon 等的元选项，以及更多功能。

<div id="inline-code">
  ### 行内代码
</div>

要将某个 `word` 或 `phrase` 标记为代码，请用反引号 (\`) 将其包裹。

```mdx theme={null}
要将`单词`或`短语`标记为代码,请用反引号(`)将其包围。
```

<div id="code-blocks">
  ### 代码块
</div>

使用[围栏代码块](https://www.markdownguide.org/extended-syntax/#fenced-code-blocks)，将代码置于三个反引号内。代码块可复制；如果启用了 AI 助手，用户可以让助手解释代码。

为语法高亮和启用元选项指定编程语言。在语言标识后添加任意元选项，如 title 或 icon。

<CodeGroup>
  ```java HelloWorld.java example icon=java lines theme={null}
  class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello, World!");
      }
  }
  ```

  ````mdx Format theme={null}
  ```java HelloWorld.java example lines icon="java"
  class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello, World!");
      }
  }
  ```
  ````
</CodeGroup>

<div id="code-block-options">
  ## 代码块选项
</div>

在代码块中添加元选项来自定义其展示效果。

<Note>
  在添加任何其他元选项之前，必须先为代码块指定编程语言。
</Note>

<div id="option-syntax">
  ### 选项语法
</div>

* **字符串和布尔选项**：可以使用 `""`、`''`，或不加引号包裹。
* **表达式选项**：可以使用 `{}`、`""`，或 `''` 包裹。

<div id="syntax-highlighting">
  ### 语法高亮
</div>

在代码块的起始反引号后指定编程语言即可启用语法高亮。

我们使用 [Shiki](https://shiki.style/) 实现语法高亮，支持所有可用语言。完整语言列表请参见 Shiki 文档中的[语言](https://shiki.style/languages)。

在 `docs.json` 中通过 `styling.codeblocks` 全局自定义代码块主题。可设置 `system` 或 `dark` 等简单主题，或为明暗模式配置自定义的 [Shiki 主题](https://shiki.style/themes)。配置项参见 [Settings](/zh/organize/settings-appearance#styling)。

<CodeGroup>
  ```java Syntax highlighting example theme={null}
  class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello, World!");
      }
  }
  ```

  ````mdx Format theme={null}
  ```java Syntax highlighting example
  class HelloWorld {
      public static void main(String[] args) {
          System.out.println("Hello, World!");
      }
  }
  ```
  ````
</CodeGroup>

<Accordion title="自定义语法高亮主题">
  如需自定义主题，请在 `docs.json` 中将主题设为 `"css-variables"`，并使用以 `--mint-` 为前缀的 CSS 变量覆盖语法高亮颜色。

  可用变量如下：

  **基础颜色**

  * `--mint-color-text`: 默认文本颜色
  * `--mint-color-background`: 背景颜色

  **Token 颜色**

  * `--mint-token-constant`: 常量和字面量
  * `--mint-token-string`: 字符串值
  * `--mint-token-comment`: 注释
  * `--mint-token-keyword`: 关键字
  * `--mint-token-parameter`: 函数参数
  * `--mint-token-function`: 函数名
  * `--mint-token-string-expression`: 字符串表达式
  * `--mint-token-punctuation`: 标点符号
  * `--mint-token-link`: 链接

  **ANSI 颜色**

  * `--mint-ansi-black`, `--mint-ansi-black-dim`
  * `--mint-ansi-red`, `--mint-ansi-red-dim`
  * `--mint-ansi-green`, `--mint-ansi-green-dim`
  * `--mint-ansi-yellow`, `--mint-ansi-yellow-dim`
  * `--mint-ansi-blue`, `--mint-ansi-blue-dim`
  * `--mint-ansi-magenta`, `--mint-ansi-magenta-dim`
  * `--mint-ansi-cyan`, `--mint-ansi-cyan-dim`
  * `--mint-ansi-white`, `--mint-ansi-white-dim`
  * `--mint-ansi-bright-black`, `--mint-ansi-bright-black-dim`
  * `--mint-ansi-bright-red`, `--mint-ansi-bright-red-dim`
  * `--mint-ansi-bright-green`, `--mint-ansi-bright-green-dim`
  * `--mint-ansi-bright-yellow`, `--mint-ansi-bright-yellow-dim`
  * `--mint-ansi-bright-blue`, `--mint-ansi-bright-blue-dim`
  * `--mint-ansi-bright-magenta`, `--mint-ansi-bright-magenta-dim`
  * `--mint-ansi-bright-cyan`, `--mint-ansi-bright-cyan-dim`
  * `--mint-ansi-bright-white`, `--mint-ansi-bright-white-dim`

  **自定义语法高亮**

  通过提供自定义 TextMate 语法文件，为 Shiki 默认集合中未包含的语言添加语法高亮支持。创建一个遵循 [TextMate 语法格式](https://macromates.com/manual/en/language_grammars) 的 JSON 文件，然后在 `docs.json` 中引用它。你可以在数组中加入更多路径以添加多种自定义语言。

  ```json docs.json theme={null}
  {
    "styling": {
      "codeblocks": {
        "languages": {
          "custom": ["/languages/my-custom-language.json"]
        }
      }
    }
  }
  ```
</Accordion>

<div id="twoslash">
  ### Twoslash
</div>

在 JavaScript 和 TypeScript 代码块中，使用 `twoslash` 可启用交互式类型信息。用户可以像在 IDE 中一样，将鼠标悬停在变量、函数和参数上以查看类型和错误。

<CodeGroup>
  ```ts twoslash Twoslash example theme={null}
  type Pet = "cat" | "dog" | "hamster";

  function adoptPet(name: string, type: Pet) {
    return `${name} the ${type} is now adopted!`;
  }

  // Hover to see the inferred types
  const message = adoptPet("Mintie", "cat");
  ```

  ````mdx Format theme={null}
  ```ts twoslash Twoslash example
  type Pet = "cat" | "dog" | "hamster";

  function adoptPet(name: string, type: Pet) {
    return `${name} the ${type} is now adopted!`;
  }

  // Hover to see the inferred types
  const message = adoptPet("Mintie", "cat");
  ```
  ````
</CodeGroup>

<div id="title">
  ### 标题
</div>

为你的代码示例添加一个标题。将标题放在语言标识符之后。标题可以包含多个单词和文件路径。

你可以通过两种方式设置标题：

* **内联**：将标题直接放在语言标识符之后。
* **`title` 属性**：使用 `title="Your title"` 来设置需要特殊字符或显式引号的标题。

<CodeGroup>
  ```javascript Example title theme={null}
  const hello = "world";
  ```

  ```javascript title="utils/hello.js" theme={null}
  const hello = "world";
  ```

  ````mdx Inline format theme={null}
  ```javascript Example title
  const hello = "world";
  ```
  ````

  ````mdx title property format theme={null}
  ```javascript title="utils/hello.js"
  const hello = "world";
  ```
  ````
</CodeGroup>

<div id="icon">
  ### 图标
</div>

使用 `icon` 属性为代码块添加图标。参见 [图标](/zh/components/icons) 以查看所有可用选项。

<CodeGroup>
  ```javascript Icon example icon=square-js theme={null}
  const hello = "world";
  ```

  ````mdx Format theme={null}
  ```javascript Icon example icon="square-js"
  const hello = "world";
  ```
  ````
</CodeGroup>

<div id="line-highlighting">
  ### 行高亮
</div>

在代码块中，使用 `highlight` 并指定要高亮的行号或行范围来高亮特定行。

<CodeGroup>
  ```javascript 行高亮示例 {1,2,5} theme={null}
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```

  ````mdx 格式 theme={null}
  ```javascript 行高亮示例 highlight={1-2,5}
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```
  ````
</CodeGroup>

<div id="line-focusing">
  ### 行聚焦
</div>

在代码块中使用 `focus` 搭配行号或行范围来突出显示特定行。

<CodeGroup>
  ```javascript Line focusing example focus=2,4,5 theme={null}
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```

  ````mdx Format theme={null}
  ```javascript Line focusing example focus={2,4-5}
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```
  ````
</CodeGroup>

<div id="show-line-numbers">
  ### 显示行号
</div>

使用 `lines` 在代码块左侧显示行号。

<CodeGroup>
  ```javascript Show line numbers example lines theme={null}
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```

  ````mdx Format theme={null}
  ```javascript Show line numbers example lines
  const greeting = "Hello, World!";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```
  ````
</CodeGroup>

<div id="expandable">
  ### 可展开
</div>

使用 `expandable` 让用户展开或折叠较长的代码块。

<CodeGroup>
  ```python Expandable example expandable theme={null}
  from datetime import datetime, timedelta
  from typing import Dict, List, Optional
  from dataclasses import dataclass

  @dataclass
  class Book:
  title: str
  author: str
  isbn: str
  checked_out: bool = False
  due_date: Optional[datetime] = None

  class Library:
      def __init__(self):
          self.books: Dict[str, Book] = {}
          self.checkouts: Dict[str, List[str]] = {} # patron -> list of ISBNs

      def add_book(self, book: Book) -> None:
          if book.isbn in self.books:
              raise ValueError(f"Book with ISBN {book.isbn} already exists")
          self.books[book.isbn] = book

      def checkout_book(self, isbn: str, patron: str, days: int = 14) -> None:
          if patron not in self.checkouts:
              self.checkouts[patron] = []

          book = self.books.get(isbn)
          if not book:
              raise ValueError("Book not found")

          if book.checked_out:
              raise ValueError("Book is already checked out")

          if len(self.checkouts[patron]) >= 3:
              raise ValueError("Patron has reached checkout limit")

          book.checked_out = True
          book.due_date = datetime.now() + timedelta(days=days)
          self.checkouts[patron].append(isbn)

      def return_book(self, isbn: str) -> float:
          book = self.books.get(isbn)
          if not book or not book.checked_out:
              raise ValueError("Book not found or not checked out")

          late_fee = 0.0
          if datetime.now() > book.due_date:
              days_late = (datetime.now() - book.due_date).days
              late_fee = days_late * 0.50

          book.checked_out = False
          book.due_date = None

          # Remove from patron's checkouts
          for patron, books in self.checkouts.items():
              if isbn in books:
                  books.remove(isbn)
                  break

          return late_fee

      def search(self, query: str) -> List[Book]:
          query = query.lower()
          return [
              book for book in self.books.values()
              if query in book.title.lower() or query in book.author.lower()
          ]

  def main():
      library = Library()

      # Add some books
      books = [
          Book("The Hobbit", "J.R.R. Tolkien", "978-0-261-10295-4"),
          Book("1984", "George Orwell", "978-0-452-28423-4"),
      ]

      for book in books:
          library.add_book(book)

      # Checkout and return example
      library.checkout_book("978-0-261-10295-4", "patron123")
      late_fee = library.return_book("978-0-261-10295-4")
      print(f"Late fee: ${late_fee:.2f}")

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

  ````text Format theme={null}
  ```python Expandable example expandable
  from datetime import datetime, timedelta
  from typing import Dict, List, Optional
  from dataclasses import dataclass

  # ...

  if __name__ == "__main__":
      main()
  ```
  ````
</CodeGroup>

<div id="wrap">
  ### 换行
</div>

使用 `wrap` 为长行启用换行。这样可避免水平滚动，并使长行更易读。

<CodeGroup>
  ```javascript Wrap example wrap theme={null}
  const greeting =
    "Hello, World! I am a long line of text that will wrap to the next line.";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```

  ````mdx Format theme={null}
  ```javascript Wrap example wrap
  const greeting =
    "Hello, World! I am a long line of text that will wrap to the next line.";
  function sayHello() {
    console.log(greeting);
  }
  sayHello();
  ```
  ````
</CodeGroup>

<div id="diff">
  ### 差异
</div>

在代码块中直观显示新增或删除的行。新增行会以绿色高亮显示，删除行会以红色高亮显示。

在行尾的注释中添加 `[!code ++]` 或 `[!code --]`，即可将该行标记为新增或删除。请使用对应语言的注释语法：

| Language                                       | Added                 | Removed               |
| ---------------------------------------------- | --------------------- | --------------------- |
| JavaScript, TypeScript, Java, C, C++, Go, Rust | `// [!code ++]`       | `// [!code --]`       |
| Python, Ruby, Bash, YAML                       | `# [!code ++]`        | `# [!code --]`        |
| HTML, XML                                      | `<!-- [!code ++] -->` | `<!-- [!code --] -->` |
| CSS                                            | `/* [!code ++] */`    | `/* [!code --] */`    |
| SQL, Lua                                       | `-- [!code ++]`       | `-- [!code --]`       |

对于连续的多行，请添加冒号和行数：

* `// [!code ++:3]`：将当前行及其后两行标记为新增。
* `# [!code --:5]`：将当前行及其后四行标记为删除。

<CodeGroup>
  ```js JavaScript diff lines theme={null}
  const greeting = "Hello, World!"; // [!code ++]
  function sayHello() {
    console.log("Hello, World!"); // [!code --]
    console.log(greeting); // [!code ++]
  }
  sayHello();
  ```

  ```python Python diff lines theme={null}
  def greet():
      print("Hello, World!")  # [!code --]
      print("Hello, Mintlify!")  # [!code ++]

  greet()
  ```

  ````text JavaScript format theme={null}
  ```js JavaScript diff lines
  const greeting = "Hello, World!"; // [!code ++]
  function sayHello() {
    console.log("Hello, World!"); // [!code --]
    console.log(greeting); // [!code ++]
  }
  sayHello();
  ```
  ````

  ````text Python format theme={null}
  ```python Python diff lines
  def greet():
      print("Hello, World!")  # [!code --]
      print("Hello, Mintlify!")  # [!code ++]

  greet()
  ```
  ````
</CodeGroup>

<div id="codeblock-component">
  ## CodeBlock 组件
</div>

在自定义 React 组件中使用 `<CodeBlock>`，以编程方式渲染与 Markdown 代码块相同样式和功能的代码块。

<div id="props">
  ### 属性
</div>

<ResponseField name="language" type="string">
  用于语法高亮的编程语言。
</ResponseField>

<ResponseField name="filename" type="string">
  显示在代码块标题中的文件名。
</ResponseField>

<ResponseField name="icon" type="string">
  显示在代码块标题中的 icon。可用选项参见 [图标](/zh/components/icons)。
</ResponseField>

<ResponseField name="lines" type="boolean">
  是否显示行号。
</ResponseField>

<ResponseField name="wrap" type="boolean">
  是否对代码块进行换行显示。
</ResponseField>

<ResponseField name="expandable" type="boolean">
  是否可展开代码块。
</ResponseField>

<ResponseField name="highlight" type="string">
  需要高亮的行。提供数字的字符串化数组。示例：`"[1,3,4,5]"`。
</ResponseField>

<ResponseField name="focus" type="string">
  需要聚焦的行。提供数字的字符串化数组。示例：`"[1,3,4,5]"`。
</ResponseField>

<div id="example">
  ### 示例
</div>

```jsx theme={null}
export const CustomCodeBlock = ({
  filename,
  icon,
  language,
  highlight,
  children,
}) => {
  return (
    <CodeBlock
      filename={filename}
      icon={icon}
      language={language}
      lines
      highlight={highlight}
    >
      {children}
    </CodeBlock>
  );
};
```
