rehype-pretty-code
repository·master·Indexed 23 days ago
https://github.com/rehype-pretty/rehype-pretty-codeA rehype plugin that provides high-quality, syntax-highlighted code block rendering for MD and MDX documentation. It integrates with Shiki and unified to support features such as line and character highlighting via meta strings, inline code highlighting, custom titles, captions, and CSS-based line numbers. The ecosystem includes @rehype-pretty/transformers for adding functionality like a customizable copy button.
What's inside rehype-pretty-code
- Rehype Pretty Code is a tool designed to create beautiful, syntax-highlighted code blocks for Markdown (MD) and MDX documentation. It works as a rehype plugin to transform code elements during the processing of your content.
Add titles and captions to code blocks
masterYou can add metadata to code blocks using the
titleandcaptionkeys in the meta string.- Title:
```js title="filename.js" - Caption:
```js caption="A description"
- Title:
Highlight lines and characters using meta strings
masterYou can control highlighting directly in Markdown code block fences using meta strings:
Highlight Lines
Use
{}to specify a numeric range.```js {1-3,4}highlights lines 1 through 3, and line 4.- Styling: Highlighted lines receive a
data-highlighted-lineattribute. - Group by ID: Use
#after the range to assign an ID:```js {1,2}#a {3,4}#b. - Styling: Lines receive
data-highlighted-line-id="<id>".
Highlight Characters
Use
/or"as delimiters.```js /carrot/highlights the word 'carrot'.```js /carrot/3-5highlights the 3rd through 5th instances of 'carrot'.- Styling: Highlighted characters receive a
data-highlighted-charsattribute. - Group by ID: Use
#after the delimiter:```js /age/#v. - Styling: Characters receive
data-chars-id="<id>".
Highlight inline code and plain text
masterUse special syntax to highlight code within text:
Inline Code Highlighting
Append
{:lang}to the end of inline code to apply language highlighting.- Example:
`[1, 2, 3]{:js}`
Highlight Plain Text (Tokens)
Append
{: .token.name}to highlight text based on specific VS Code theme tokens.- Example:
`getStringLength{:.entity.name.function}` - Tokens Map: You can use
tokensMapin the plugin options to create aliases (e.g.,fn: "entity.name.function"), allowing you to use`getStringLength{:.fn}`.
- Example:
Highlight characters in code blocks
masterHighlight specific words or character sequences using
/or"delimiters in the meta string.Basic character highlighting
```js /carrot/ ```Multiple segments and ranges
You can highlight multiple segments or specify a range of occurrences (e.g.,
3-5for the 3rd to 5th instance).```js /carrot/3-5 /apple/ ```Group highlighted characters by ID
Use
#after the delimiter to assign an ID.```js /age/#v /name/#v const [age, setName] = useState(50); ```Styling: The characters receive a
data-chars-id="<id>"attribute.Styling Note
Highlighted characters receive a
data-highlighted-charsattribute.Implement Multiple Themes (Dark and Light Mode)
masterTo support dual themes, pass an object to the
themeoption where keys represent the color mode (e.g.,dark,light).When multiple themes are provided, the
<code>and<pre>elements will have adata-themeattribute containing a space-separated list of the theme names (e.g.,data-theme="github-dark-dimmed github-light").You can then use CSS to switch colors based on the
prefers-color-schememedia query or by targeting thedata-themeattribute.const options = { theme: { dark: "github-dark-dimmed", light: "github-light", }, };Implement line numbers with CSS
masterThe library is unstyled, but it provides attributes to help you implement line numbers via CSS counters.
- Use the
showLineNumbersmeta string to enable them:```js showLineNumbers. - To start at a specific number:
```js showLineNumbers{5}. - The
<code>element will receivedata-line-numbersanddata-line-numbers-max-digits="n"attributes.
Example CSS Implementation:
code[data-line-numbers] { counter-reset: line; } code[data-line-numbers] > [data-line]::before { counter-increment: line; content: counter(line); display: inline-block; width: 0.75rem; margin-right: 2rem; text-align: right; color: gray; }code[data-line-numbers] { counter-reset: line; } code[data-line-numbers] > [data-line]::before { counter-increment: line; content: counter(line); display: inline-block; width: 0.75rem; margin-right: 2rem; text-align: right; color: gray; } code[data-line-numbers-max-digits="2"] > [data-line]::before { width: 1.25rem; }- Use the
Use rehype-pretty-code in React Server Components
masterYou can use
rehype-pretty-codewithin React Server Components (RSC) by processing the code string through aunifiedpipeline.Implementation Steps:
- Create an async function that uses
unified,remark-parse,remark-rehype,rehype-pretty-code, andrehype-stringifyto process the code. - Return the processed string.
- Use
dangerouslySetInnerHTMLto render the result in your component.
Example Component:
import * as React from "react"; import { unified } from "unified"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import rehypeStringify from "rehype-stringify"; import rehypePrettyCode from "rehype-pretty-code"; export async function Code({ code }: { code: string }) { const highlightedCode = await highlightCode(code); return ( <section dangerouslySetInnerHTML={{ __html: highlightedCode, }} /> ); } async function highlightCode(code: string) { const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { keepBackground: false, }) .use(rehypeStringify) .process(code); return String(file); }- Create an async function that uses
View integration examples for various frameworks
masterRehype Pretty Code provides specific integration examples for several popular web frameworks and environments. You can explore these examples to see how to set up the plugin in your specific stack:
- SvelteKit: Integration for Svelte-based projects.
- Astro: Integration for Astro-based projects.
- CDN: A simple
index.htmlexample using CDN-based integration. - Next.js: Integration for Next.js projects.
Use rehype-pretty-code in React Server Components (RSC)
masterYou can use
rehype-pretty-codewithin React Server Components by processing the code string through aunifiedpipeline.- Create an async function that uses
unified,remark-parse,remark-rehype,rehype-pretty-code, andrehype-stringifyto process the code. - Wrap the resulting HTML in a component using
dangerouslySetInnerHTML. - Import and use this component within your RSC pages.
import * as React from "react"; import { unified } from "unified"; import remarkParse from "remark-parse"; import remarkRehype from "remark-rehype"; import rehypeStringify from "rehype-stringify"; import rehypePrettyCode from "rehype-pretty-code"; export async function Code({ code }: { code: string }) { const highlightedCode = await highlightCode(code); return ( <section dangerouslySetInnerHTML={{ __html: highlightedCode, }} /> ); } async function highlightCode(code: string) { const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { keepBackground: false, }) .use(rehypeStringify) .process(code); return String(file); }import * as React from "react"; import { Code } from "./code.tsx"; export default async function Page() { return ( <main> <Code code="`const numbers = [1, 2, 3]{:js}`" /> </main> ); }- Create an async function that uses
Install rehype-pretty-code and shiki
masterInstall the package and its required dependency
shikiusing your preferred package manager. Note that this package is ESM-only and requiresshikiversion^1.0.0.npm install rehype-pretty-code shiki # or pnpm add rehype-pretty-code shiki # or bun add rehype-pretty-code shiki # or yarn add rehype-pretty-code shikiInstall @rehype-pretty/transformers
masterTo use the Copy Button transformer, install the
@rehype-pretty/transformerspackage using your preferred package manager.npm install @rehype-pretty/transformers