Code blocks

Components•5 min read|
|

DocsLit provides enhanced code blocks with syntax highlighting, filenames, copy buttons, tabbed groups, and editable variables.

Basic code block

Style a code block's parts with ::part(): root, header and copy-button. A code group has root, tab-bar, tab-content and copy-button. See Custom CSS.

Use standard fenced code blocks with a language identifier:

```javascript const config = { name: "My Docs" }; ``` const config = { name: "My Docs" };

Every code block includes a copy button automatically.

Syntax highlighting

DocsLit uses Shiki for build-time syntax highlighting. Code blocks are highlighted at parse time, so there is no client-side rendering cost. Shiki supports dual themes -- your code blocks automatically match the page's light or dark mode.

Code theme toggle

Every code block and code group includes a kebab menu that lets readers switch all code blocks between light and dark mode. This setting is independent of the page theme and is saved to the browser for future visits.

You can also force a specific theme on any individual code block:

<wc-code-block language="javascript" theme="dark"> const alwaysDark = true; </wc-code-block>

Fence options

Everything after the language in the opening fence is read as options. The same options exist as attributes on the wc-code-block element, so you can write whichever form you like.

Fence Attribute Effect
title="app.js", filename="app.js", or bare words after the language filename Header title
icon=code icon Icon in the header (a wc-icon name)
{1,3-5} or highlight={1,3-5} highlight="1,3-5" Highlight lines
focus=2,4-5 focus="2,4-5" Dim every other line
lines or linenumbers="true" linenumbers="true" Line numbers
startLine={10} start-line="10" First line number
wrap or wordWrap wrap Wrap long lines
expandable expandable Collapse long blocks behind "Show more" (10 lines)
maxLines=5 max-lines="5" Collapse after N lines
annotate annotate Turn (1) comment markers into numbered notes (see Code annotations)
nocopy nocopy Hide the copy button
for="npm" for="npm" Sync token inside a code group

Mintlify and Fern spellings are accepted as they are, so content moved from those platforms keeps working.

Title and icon

```js title="utils/hello.js" icon=code const hello = "world"; ``` const hello = "world";

A fence with only a language still shows a small header with the language name and the copy button. A fence with no language and no title gets a copy button that appears on hover.

Line highlighting

Use braces or highlight=. Ranges and lists mix freely.

```js {1,3-4} const a = 1; const b = 2; const c = 3; const d = 4; const e = 5; ``` const a = 1; const b = 2; const c = 3; const d = 4; const e = 5;

Focus

focus dims the other lines. Hovering or focusing the block brings them back, and touch devices keep the dimming.

```js focus=2,3 const a = 1; const b = 2; const c = 3; const d = 4; ``` const a = 1; const b = 2; const c = 3; const d = 4;

Diff, highlight and focus comments

Add a comment at the end of a line to mark it. This is the Shiki notation, so the same markers work in code copied from Mintlify or Fern docs. The marker comment is removed from the display and from the copy button.

Marker Effect
[!code ++] Added line (green, + in the gutter)
[!code --] Removed line (red, minus in the gutter)
[!code highlight] Highlighted line
[!code focus] Focused line
[!code error], [!code warning] Error or warning line
[!code ++:3] This line and the next two

Use the comment syntax of the language (//, #, --, /* */, <!-- -->). A marker on a line of its own is removed and applies to the lines after it.

const greeting = "Hello, World!"; // [!code ++] function sayHello() { console.log("Hello, World!"); // [!code --] console.log(greeting); // [!code ++] } const greeting = "Hello, World!"; function sayHello() { console.log("Hello, World!"); console.log(greeting); }

Languages without comments (text, markdown, json) are never scanned, so you can show the notation itself in a text block as above. The diff language is rendered as a diff too, and keeps its + and - signs when copied:

@@ -1,3 +1,3 @@ const a = 1; -const b = 2; +const b = 3;

Line numbers

```ts lines startLine={8} export function add(a: number, b: number) { return a + b; } ``` export function add(a: number, b: number) { return a + b; }

Numbers are drawn by CSS, so they are never selected or copied.

Wrapping and collapsing

Long lines scroll horizontally by default; add wrap to wrap them. Long blocks can collapse behind a "Show more" button (a real button with aria-expanded):

```js wrap lines maxLines=3 const message = "A very long line of text that wraps onto the next line instead of scrolling sideways."; const a = 1; const b = 2; const c = 3; const d = 4; ``` const message = "A very long line of text that wraps onto the next line instead of scrolling sideways."; const a = 1; const b = 2; const c = 3; const d = 4;

expandable alone collapses after 10 lines. Blocks shorter than the limit are never collapsed.

Hide the copy button

User --> CDN --> Origin

What copying does

The copy button copies the code as written: no line numbers, no gutter signs, no [!code ...] markers, and {{VARIABLES}} replaced by their current values. In a diff block the + and - signs are part of the code and are kept.

Importing code

Options combine with code import. Fence options other than the import keys (file, lines, region) are passed through:

```js file="examples/server.js" region="routes" title="routes" {2} ```

Generated Markdown and llms.txt

The .md pages and llms.txt contain the code without presentation markers: [!code highlight], focus, error and warning comments are removed, and a block that uses [!code ++] / [!code --] is written as a diff block with + and - prefixes.

Twoslash

twoslash (interactive type hovers) is not supported. The flag is accepted and ignored, so the block renders as normal highlighted code.

Code block with filename

Add a filename attribute to show a file header:

<wc-code-block language="json" filename="docslit.json"> { "name": "My Docs", "sidebar": [] } </wc-code-block> { "name": "My Docs", "sidebar": [] }

Hand-written blocks are highlighted at build time just like fences, and support every option as an attribute:

def greet(name): print(f"Hello, {name}!") The syntax highlighting language. Examples: javascript, python, bash, json, html, css. Shown as a label in the header. A filename or title displayed in the header bar above the code. An icon name shown before the filename. true or false. Set to true to show line numbers. The number of the first line when line numbers are shown. Default 1. Lines to highlight, for example 1,3-5. Lines to focus; the others are dimmed. Wrap long lines instead of scrolling. Collapse blocks longer than 10 lines behind a "Show more" button. Collapse after this many lines (implies expandable). Hide the copy button. Sync token inside a code group. See Code groups. dark or light. Pins the block to a color scheme. Marks content that is already highlighted HTML. DocsLit sets this at build time; you rarely write it by hand.

Code annotations

Code annotations attach numbered notes to specific lines. Add the annotate flag to the fence, end a comment on the line with a marker, and write the notes as an ordered list directly after the block.

  • (1), (2), ... at the end of a comment marks the line. The marker is replaced by a numbered badge and the comment stays visible.
  • (1)! hides the comment characters too, so only the badge remains.
  • The ordered list right after the block holds the notes. Item N is the note for marker (N). Notes can contain inline Markdown such as code, links and emphasis.
```python annotate import requests def fetch(url): # Retry transient failures (1) for attempt in range(3): response = requests.get(url, timeout=10) # (2)! if response.ok: return response.json() raise RuntimeError("giving up") # (3) ``` 1. Only network errors and `5xx` responses are worth retrying. 2. Always set a timeout, or a stalled server can hang the call forever. 3. Callers should catch `RuntimeError` and report the URL. import requests def fetch(url): # Retry transient failures for attempt in range(3): response = requests.get(url, timeout=10) if response.ok: return response.json() raise RuntimeError("giving up") #
  1. Only network errors and 5xx responses are worth retrying.
  2. Always set a timeout, or a stalled server can hang the call forever.
  3. Callers should catch RuntimeError and report the URL.

How it behaves

  • Clicking a badge opens its note in a popover next to the line. Clicking it again, clicking elsewhere or pressing Escape closes it, and focus returns to the badge. Opening one note closes any other open note.
  • Badges are real buttons, so they can be reached with Tab and opened with Enter or Space.
  • Markers are removed from the copy button, so copied code is clean.
  • Without JavaScript the badges are static and the ordered list stays visible under the code, so the notes are never lost.
  • Markers work with the other fence options, for example annotate lines {2}.

Build warnings

docslit validate and docslit build report these problems. None of them stops the build.

Code Cause
code-annotation-no-list The block has annotate but no ordered list directly after it. Markers stay as plain text.
code-annotation-no-marker The block has annotate but no (N) marker in a comment. The list stays below the code.
code-annotation-missing-item A marker (N) has no matching list item.

Code groups

Group related code examples in tabs. The simplest form puts fences straight inside wc-code-group; each fence's title (or its language) becomes the tab label:

<wc-code-group> ```javascript helloWorld.js console.log("Hello World"); ``` ```python hello_world.py print('Hello World!') ``` ```java HelloWorld.java lines class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } } ``` </wc-code-group> console.log("Hello World"); print('Hello World!') class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"); } }

Each fence keeps its own options (lines, {2}, nocopy, ...). You can also give the tab a label with wc-code-tab. Its content can be a fence, or plain text with a language attribute, which is highlighted at build time:

<wc-code-group> <wc-code-tab label="npm" language="bash">npm install docslit</wc-code-tab> <wc-code-tab label="pnpm" language="bash">pnpm add docslit</wc-code-tab> <wc-code-tab label="yarn" language="bash">yarn add docslit</wc-code-tab> </wc-code-group> npm install docslit pnpm add docslit yarn add docslit

Add dropdown to replace the tab bar with a native select, handy for long language lists:

<wc-code-group dropdown> ```javascript helloWorld.js console.log("Hello World"); ``` ```python hello_world.py print('Hello World!') ``` </wc-code-group> console.log("Hello World"); print('Hello World!')

Synced groups

Code groups on the same page sync by default. When a reader picks Python in one group, every group that has a Python tab switches too, and the choice is remembered across pages. A tab matches by its for token, its label, or its language (js and javascript are the same language). Opening a page with ?language=python preselects Python.

Use for when the tabs are not about a language, for example package managers. Tabs with the same for value switch together:

<wc-code-group> ```bash title="Install using npm" for="npm" npm install plantstore ``` ```bash title="Install using pnpm" for="pnpm" pnpm add plantstore ``` </wc-code-group>

Set sync="my-key" to keep a set of groups (and wc-tabs with the same key) separate from the rest, or sync="off" to opt out.

Tab bars follow the WAI-ARIA tabs pattern: Left and Right arrows, Home and End move between tabs.

Show a language dropdown instead of tabs. Sync key. Defaults to code; off disables syncing. Hide the copy button for the whole group. Tab label. Highlighting language for plain-text content; also used for language sync. Icon shown in the tab. Sync token (read from the tab or from a fence inside it).

Editable variables

Use wc-var to create interactive variables that update across all code blocks on the page. Readers click the variable, type their value, and every {{VAR_NAME}} placeholder updates instantly.

Set your API key:

Set your base URL:

curl -H "Authorization: Bearer {{API_KEY}}" {{BASE_URL}}/v1/docs const client = new DocsClient({ apiKey: "{{API_KEY}}", baseUrl: "{{BASE_URL}}" });

Click the variable values above and type your own — watch both code blocks update in real time.

The variable name. Use UPPER_SNAKE_CASE by convention. Reference it in code blocks with {{NAME}}. The default value shown before the reader edits it. Compile-time form only: <wc-var name="X" value="Y" /> declares a page-level variable. See Variables and precedence. Prevent the reader from editing the value. Editable variables make setup instructions personal. Instead of asking readers to "replace YOUR_API_KEY", give them a field to type it once and see it everywhere.

Copy button on code groups

Code groups include a copy button that copies the active tab's code.

Supported languages

DocsLit uses Shiki for syntax highlighting, which supports all common programming languages including JavaScript, TypeScript, Python, Go, Rust, Java, C, C++, Ruby, PHP, Shell/Bash, SQL, HTML, CSS, JSON, YAML, TOML, Markdown, and more.

Variables and highlighting

Code blocks that contain {{VAR}} placeholders are fully highlighted. The placeholders become editable spans that update as readers change the variable, and copying uses the current values. In the rare case where a placeholder cannot be kept in one piece by the highlighter, the block falls back to plain text so substitution keeps working.