# Format code (/create/code)

<!-- agent-signals: reading_time_min: 10 · est_tokens: 5615 · updated: 2026-07-30 -->
Related: [Changelogs](/create/changelogs.md), [Files](/create/files.md), [Images and embeds](/create/image-embeds.md), [Lists and tables](/create/list-table.md), [Personalized content](/create/personalization.md), [Redirects](/create/redirects.md)

## Add code samples [#add-code-samples]

You can add inline code snippets or code blocks. Code blocks support meta options for syntax highlighting, titles, line highlighting, icons, and more.

### Inline code [#inline-code]

To denote a `word` or `phrase` as code, enclose it in backticks (\`).

```mdx
To denote a `word` or `phrase` as code, enclose it in backticks (`).
```

### Code blocks [#code-blocks]

Use [fenced code blocks](https://www.markdownguide.org/extended-syntax/#fenced-code-blocks) by enclosing code in three backticks. Code blocks are copyable, and if you have the assistant enabled, users can ask the assistant to explain the code.

Specify the programming language for syntax highlighting and to enable meta options. Add any meta options, like a title or icon, after the language.

<CodeGroup>
  <CodeBlockTabs defaultValue="HelloWorld.java example" groupId="format+helloworld-java-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="HelloWorld.java example">
        HelloWorld.java example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

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

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

## Code block options [#code-block-options]

Add meta options to your code blocks to customize their appearance.

<Note>
  You must specify a programming language for a code block before adding any other meta options.
</Note>

### Option syntax [#option-syntax]

* **String and boolean options**: Wrap with `""`, `''`, or no quotes.
* **Expression options**: Wrap with `{}`, `""`, or `''`.

### Syntax highlighting [#syntax-highlighting]

Enable syntax highlighting by specifying the programming language after the opening backticks of a code block.

Mintlify uses [Shiki](https://shiki.style/) for syntax highlighting and supports all available languages. See the full list of [languages](https://shiki.style/languages) in Shiki's documentation.

Customize code block themes globally using `styling.codeblocks` in your `docs.json` file. Set simple themes like `system` or `dark`, or configure custom [Shiki themes](https://shiki.style/themes) for light and dark modes. See [Settings](/organize/settings-appearance#styling) for configuration options.

<CodeGroup>
  <CodeBlockTabs defaultValue="Syntax highlighting example" groupId="format+syntax-highlighting-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Syntax highlighting example">
        Syntax highlighting example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

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

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

<Accordion title="Custom syntax highlighting theme">
  For custom themes, set your theme in `docs.json` to `"css-variables"` and override syntax highlighting colors using CSS variables with the `--mint-` prefix.

  The following variables are available:

  **Basic colors**

  * `--mint-color-text`: Default text color
  * `--mint-color-background`: Background color

  **Token colors**

  * `--mint-token-constant`: Constants and literals
  * `--mint-token-string`: String values
  * `--mint-token-comment`: Comments
  * `--mint-token-keyword`: Keywords
  * `--mint-token-parameter`: Function parameters
  * `--mint-token-function`: Function names
  * `--mint-token-string-expression`: String expressions
  * `--mint-token-punctuation`: Punctuation marks
  * `--mint-token-link`: Links

  **ANSI colors**

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

  **Custom syntax highlighting**

  Add syntax highlighting for languages not included in Shiki's default set by providing custom TextMate grammar files. Create a JSON file following the [TextMate grammar format](https://macromates.com/manual/en/language_grammars), then reference it in your `docs.json`. You can add multiple custom languages by including additional paths in the array.

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

### Twoslash [#twoslash]

In JavaScript and TypeScript code blocks, use `twoslash` to enable interactive type information. Users can hover over variables, functions, and parameters to see types and errors like in an IDE.

<CodeGroup>
  <CodeBlockTabs defaultValue="twoslash Twoslash example" groupId="format+twoslash-twoslash-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="twoslash Twoslash example">
        twoslash Twoslash example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="twoslash Twoslash example">
      ```ts  
      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");
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Format">
      ````mdx  
      ```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");
      ```
      ````
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### Title [#title]

Add a title to label your code example. Place the title after the language identifier. Titles can contain multiple words and file paths.

You can set the title two ways:

* **Inline**: Place the title directly after the language identifier.
* **`title` property**: Use `title="Your title"` for titles that need special characters or explicit quoting.

<CodeGroup>
  <CodeBlockTabs defaultValue="Example title" groupId="example-title+inline-format+title-property-format+utils-hello-js">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Example title">
        Example title
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="utils/hello.js">
        utils/hello.js
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Inline format">
        Inline format
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="title property format">
        title property format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="Example title">
      ```javascript  
      const hello = "world";
      ```
    </CodeBlockTab>

    <CodeBlockTab value="utils/hello.js">
      ```javascript  
      const hello = "world";
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Inline format">
      ````mdx  
      ```javascript Example title
      const hello = "world";
      ```
      ````
    </CodeBlockTab>

    <CodeBlockTab value="title property format">
      ````mdx  
      ```javascript title="utils/hello.js"
      const hello = "world";
      ```
      ````
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### Icon [#icon]

Add an icon to your code block using the `icon` property. See [Icons](/components/icons) for all available options.

<CodeGroup>
  <CodeBlockTabs defaultValue="Icon example" groupId="format+icon-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Icon example">
        Icon example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="Icon example">
      ```javascript icon=square-js  
      const hello = "world";
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Format">
      ````mdx  
      ```javascript Icon example icon="square-js"
      const hello = "world";
      ```
      ````
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### Line highlighting [#line-highlighting]

Highlight specific lines in your code blocks using `highlight` with the line numbers or ranges you want to highlight.

<CodeGroup>
  <CodeBlockTabs defaultValue="Line highlighting example" groupId="format+line-highlighting-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Line highlighting example">
        Line highlighting example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="Line highlighting example">
      ```javascript {1,2,5}  
      const greeting = "Hello, World!";
      function sayHello() {
        console.log(greeting);
      }
      sayHello();
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Format">
      ````mdx  
      ```javascript Line highlighting example highlight={1-2,5}
      const greeting = "Hello, World!";
      function sayHello() {
        console.log(greeting);
      }
      sayHello();
      ```
      ````
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### Line focusing [#line-focusing]

Focus on specific lines in your code blocks using `focus` with line numbers or ranges.

<CodeGroup>
  <CodeBlockTabs defaultValue="Line focusing example" groupId="format+line-focusing-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Line focusing example">
        Line focusing example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

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

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

### Show line numbers [#show-line-numbers]

Display line numbers on the left side of your code block using `lines`.

<CodeGroup>
  <CodeBlockTabs defaultValue="Show line numbers example" groupId="format+show-line-numbers-example">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="Show line numbers example">
        Show line numbers example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

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

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

### Expandable [#expandable]

Allow users to expand and collapse long code blocks using `expandable`.

<CodeGroup>
  <CodeBlockTabs defaultValue="example" groupId="example+format">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="example">
        example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="example">
      ```python Expandable expandable  
      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()
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Format">
      ````text  
      ```python Expandable example expandable
      from datetime import datetime, timedelta
      from typing import Dict, List, Optional
      from dataclasses import dataclass

      # ...

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

### Wrap [#wrap]

Enable text wrapping for long lines using `wrap`. This prevents horizontal scrolling and makes long lines easier to read.

<CodeGroup>
  <CodeBlockTabs defaultValue="example" groupId="example+format">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="example">
        example
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Format">
        Format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

    <CodeBlockTab value="example">
      ```javascript Wrap 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();
      ```
    </CodeBlockTab>

    <CodeBlockTab value="Format">
      ````mdx  
      ```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();
      ```
      ````
    </CodeBlockTab>
  </CodeBlockTabs>
</CodeGroup>

### Diff [#diff]

Show a visual diff of added or removed lines in your code blocks. Added lines are highlighted in green and removed lines are highlighted in red.

Add `[!code ++]` or `[!code --]` inside a comment at the end of a line to mark it as added or removed. Use your language's comment syntax:

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

For multiple consecutive lines, add a colon and the number of lines:

* `// [!code ++:3]`: Mark the current line plus the next two lines as added.
* `# [!code --:5]`: Mark the current line plus the next four lines as removed.

<CodeGroup>
  <CodeBlockTabs defaultValue="JavaScript diff" groupId="javascript-diff+javascript-format+python-diff+python-format">
    <CodeBlockTabsList>
      <CodeBlockTabsTrigger value="JavaScript diff">
        JavaScript diff
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Python diff">
        Python diff
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="JavaScript format">
        JavaScript format
      </CodeBlockTabsTrigger>

      <CodeBlockTabsTrigger value="Python format">
        Python format
      </CodeBlockTabsTrigger>
    </CodeBlockTabsList>

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

    <CodeBlockTab value="Python diff">
      ```python lines  
      def greet():
          print("Hello, World!")  # [!code --]
          print("Hello, Mintlify!")  # [!code ++]

      greet()
      ```
    </CodeBlockTab>

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

    <CodeBlockTab value="Python format">
      ````text  
      ```python Python diff lines
      def greet():
          print("Hello, World!")  # [!code --]
          print("Hello, Mintlify!")  # [!code ++]

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

## CodeBlock component [#codeblock-component]

Use the `<CodeBlock>` component in custom React components to programmatically render code blocks with the same styling and features as markdown code blocks.

### Props [#props]

<ResponseField name="language" type="string">
  The programming language for syntax highlighting.
</ResponseField>

<ResponseField name="filename" type="string">
  The filename to display in the code block header.
</ResponseField>

<ResponseField name="icon" type="string">
  The icon to display in the code block header. See [Icons](/components/icons)
  for available options.
</ResponseField>

<ResponseField name="lines" type="boolean">
  Whether to show line numbers.
</ResponseField>

<ResponseField name="wrap" type="boolean">
  Whether to wrap the code block.
</ResponseField>

<ResponseField name="expandable" type="boolean">
  Whether to expand the code block.
</ResponseField>

<ResponseField name="highlight" type="string">
  The lines to highlight. Provide a stringified array of numbers. Example:
  `"[1,3,4,5]"`.
</ResponseField>

<ResponseField name="focus" type="string">
  The lines to focus on. Provide a stringified array of numbers. Example:
  `"[1,3,4,5]"`.
</ResponseField>

### Example [#example]

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