Let's see what we can do with rehype-pretty-code

A tour of rehype-pretty-code features — syntax highlighting, line numbers, line and word highlighting, titles, captions, inline code and ANSI output — and how they're configured on this blog.

Bart Tworek3 min readrehype prettymdxshikinext.js

Every code block on this blog is rendered by rehype-pretty-code, a Rehype plugin powered by the shiki syntax highlighter. Because it runs when the site is built, the highlighted HTML is generated once and shipped as static markup. Visitors don't download a highlighting library, and the code never flickers from plain to coloured text as the page loads.

This post is a quick tour of what it can do, and doubles as a reference for the syntax I use in other posts.

How it's set up

This blog is built with Next.js and Velite, which compiles the MDX content at build time. Adding rehype-pretty-code is a single entry in the Velite config. Passing a light and a dark theme makes Shiki emit both sets of colours as CSS variables, so code blocks follow the site's light/dark mode toggle:

velite.config.ts
import rehypePrettyCode from "rehype-pretty-code";
 
export default defineConfig({
  mdx: {
    rehypePlugins: [
      [rehypePrettyCode, { theme: { light: "github-light", dark: "github-dark" } }]
    ]
  }
});

A few lines of CSS then select whichever variable matches the current theme:

[data-rehype-pretty-code-figure] pre span {
  color: var(--shiki-light);
}
 
.dark [data-rehype-pretty-code-figure] pre span {
  color: var(--shiki-dark);
}

Editor-grade highlighting

Shiki uses the same TextMate grammars as VS Code, so the highlighting is as accurate and fine-grained as what you see in your editor — and you can use any VS Code theme you like. It supports hundreds of languages out of the box: just name the language after the opening fence.

```csharp
var greeting = "Hello, world!";
```

Line numbers and line highlighting

Add showLineNumbers to the code fence to number the lines, and put line numbers in curly braces to highlight them. Ranges and lists are supported too — {1,3-5} highlights lines 1, 3, 4 and 5.

```js {4} showLineNumbers
...
```

Here, line 4 is highlighted to draw attention to the hook call:

import { useFloating } from "@floating-ui/react";
 
function MyComponent() {
  const { refs, floatingStyles } = useFloating();
 
  return (
    <>
      <div ref={refs.setReference} />
      <div ref={refs.setFloating} style={floatingStyles} />
    </>
  );
}

Word highlighting

To highlight specific words or characters rather than whole lines, wrap them in slashes like a regular expression — for example /floatingStyles/. Every occurrence gets highlighted, which makes it easy to follow a variable through a snippet:

import { useFloating } from "@floating-ui/react";
 
function MyComponent() {
  const { refs, floatingStyles } = useFloating();
 
  return (
    <>
      <div ref={refs.setReference} />
      <div ref={refs.setFloating} style={floatingStyles} />
    </>
  );
}

To highlight only some occurrences, add the instance numbers after the closing slash: /floatingStyles/2 highlights just the second one.

Titles and captions

A title is shown above the code block — ideal for showing which file a snippet belongs in — and a caption is shown below it:

```ts title="lib/utils.ts" caption="A tiny helper for joining class names"
...
```
lib/utils.ts
export function cn(...classes: (string | false | undefined)[]) {
  return classes.filter(Boolean).join(" ");
}
A tiny helper for joining class names

Inline code highlighting

Inline code can be highlighted too. Add {:lang} to the end of the inline code to tell Shiki which language it is — for example, writing `const answer = 42{:js}` renders as const answer = 42, while plain inline code like const answer = 42 is left as-is.

ANSI highlighting

Use the ansi language to render raw ANSI escape codes with their original colours. This is perfect for showing terminal or console output exactly as it appeared, rather than as a wall of escape characters.

  vite v5.0.0 dev server running at:
 
  > Local: http://localhost:3000/
  > Network: use `--host` to expose
 
  ready in 125ms.
 
8:38:02 PM [vite] hmr update /src/App.jsx

It works inline too: > Local: http://localhost:3000/


Kitchen sink

All of these options can be combined in a single code block — line numbers, highlighted lines, word highlighting, a title and a caption:

```ts showLineNumbers {6-8} title="retry.ts" /attempt/ caption="Retrying an async operation with exponential backoff"
...
```
retry.ts
export async function retry<T>(operation: () => Promise<T>, maxAttempts = 3): Promise<T> {
  for (let attempt = 1; ; attempt++) {
    try {
      return await operation();
    } catch (error) {
      if (attempt >= maxAttempts) throw error;
      const delay = 2 ** attempt * 100;
      await new Promise((resolve) => setTimeout(resolve, delay));
    }
  }
}
 
// Example usage:
const user = await retry(() => fetch("/api/user").then((res) => res.json()));
Retrying an async operation with exponential backoff

That covers everything I use day to day. The rehype-pretty-code documentation describes a few more advanced options, such as custom highlight groups and diff-style highlighting through Shiki transformers.