### Show Line Numbers Start At Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/showLineNumbersStartAtMultipleTheme.html This example shows how to configure line numbers to start at a specific value. Ensure the `data-line-numbers` attribute is present on the `code` element. ```html const a = 'a'; const b = 'b'; const c = 'c'; const a = 'a'; const b = 'b'; const c = 'c'; const a = 'a'; const b = 'b'; const c = 'c'; ``` -------------------------------- ### Install with bun Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use this command to install the transformers package with bun. ```sh bun add @rehype-pretty/transformers ``` -------------------------------- ### Install with yarn Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use this command to install the transformers package with yarn. ```sh yarn add @rehype-pretty/transformers ``` -------------------------------- ### Install rehype-pretty-code and shiki Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Install the necessary packages using npm, pnpm, bun, or yarn. ```sh # npm npm install rehype-pretty-code shiki # pnpm pnpm add rehype-pretty-code shiki # bun bun add rehype-pretty-code shiki # yarn yarn add rehype-pretty-code shiki ``` -------------------------------- ### Install with npm Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use this command to install the transformers package with npm. ```sh npm install @rehype-pretty/transformers ``` -------------------------------- ### Install with JSR Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use this command to install the transformers package with JSR. ```sh npx jsr add @rehype-pretty/transformers ``` -------------------------------- ### Install rehype-pretty-code and shiki Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Install the necessary packages for rehype-pretty-code and shiki using npm. This is the first step to integrating the syntax highlighter into your project. ```shell npm install rehype-pretty-code shiki ``` -------------------------------- ### Install with pnpm Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use this command to install the transformers package with pnpm. ```sh pnpm add @rehype-pretty/transformers ``` -------------------------------- ### Default Line Numbers Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/showLineNumbersStartAtMultipleTheme.md This example shows code with default line number behavior, starting at 1. ```javascript const a = 'a'; const b = 'b'; const c = 'c'; ``` -------------------------------- ### Install Rehype Pretty Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Install the `rehype-pretty-code` and `shiki` packages using npm, pnpm, bun, or yarn. This package is ESM-only and requires `shiki` version `^1.0.0`. ```sh npm install rehype-pretty-code shiki\n ``` ```sh pnpm add rehype-pretty-code shiki\n ``` ```sh bun add rehype-pretty-code shiki\n ``` ```sh yarn add rehype-pretty-code shiki\n ``` -------------------------------- ### Unsupported Language Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inlineMultipleTheme.md Illustrates how code blocks with unsupported language identifiers are handled. They are displayed as plain text. ```unsupportedlang
bar
{:unsupportedlang} ``` -------------------------------- ### Git Rebase Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/multiWordLanguage.md This snippet shows a typical git rebase sequence. Ensure your environment supports the 'git-rebase' language identifier. ```git-rebase pick e0662b2 Improve a11y of the logo image fixup 41aac9e fixup! e0662b2 pick d3942e9 Use SVG format for the logo fixup f5409b6 fixup! d3942e9 pick 5dae451 Link logo to the site root ``` -------------------------------- ### Show Line Numbers with Different Highlighted Lines Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightedLinesWithShowLineNumbersAt.html Illustrates using `showLineNumbers` with a specific starting line and a different set of lines to highlight. ```javascript const getStringLength = (str) => str.length; const add = (x, y) => x + y; const divide = (x, y) => x / y; const subtract = (x, y) => x - y; const multiply = (x, y) => x * y; ``` -------------------------------- ### Basic JavaScript Variables Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/showLineNumbers.html A simple example showing variable declarations in JavaScript. This code is not highlighted. ```javascript const a = 'a'; const b = 'b'; const c = 'c'; ``` -------------------------------- ### Highlighting HTML Attributes Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightCharsComplex.html Examples of highlighting specific parts of HTML tags and attributes. ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html ``` ```html <> ``` ```html <> ``` ```html <> ``` -------------------------------- ### Basic JavaScript Code Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/defaultLang.block=js.html A simple JavaScript code snippet demonstrating a boolean variable assignment. This is a basic example of how code is rendered. ```javascript const x = true; ``` -------------------------------- ### Highlighting JavaScript Variables Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightCharsComplex.html Examples of highlighting variable names in JavaScript, including partial matches and duplicates. ```javascript const carrotcar,carcarrot; const orangecarrotcar,orangecarrotcar; ``` ```javascript const carrotcar,carcarrot; const orangecarrotcar,orangecarrotcar; ``` ```javascript const carrotcar,carcarrot; const carrotcar,carcarrot; ``` ```javascript const carrot,carrot,carrot,carrot; ``` -------------------------------- ### Highlight Specific Lines with showLineNumbersAt (Variant) Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightedLinesWithShowLineNumbersAt.md Another example demonstrating line highlighting with showLineNumbersAt and showLineNumbers, showing variations in variable names. ```javascript const getStringLength = (str) => str.length; const add = (x, y) => x + y; const divide = (x, y) => x / y; const subtract = (x, y) => x - y; const multiply = (x, y) => x * y; ``` -------------------------------- ### Start Line Numbers at a Specific Number Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Customize the starting number for line numbering by appending `{number}` to `showLineNumbers`. ```mdx ```js showLineNumbers{number} ``` ``` -------------------------------- ### Code Diff Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/diff.html This snippet shows a typical code diff with lines added and removed. It is useful for visualizing changes in code. ```javascript import useSWR from 'swr' function Profile() { const { data, error } = useSWR('/api/user', fetcher) - if (error) return
failed to load
+ if (!data) return
loading...
return
hello {data.name}!
} ``` -------------------------------- ### Diff Transformer Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/transformers.html Demonstrates the use of boolean variables to indicate added, removed, or blank lines for diff highlighting. ```javascript const added = true; const removed = true; const blank = true; ``` -------------------------------- ### Highlight Lines by ID Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightLinesById.html Use this syntax to specify line ranges for highlighting, associating them with an ID. This is useful for referencing specific parts of the code. ```javascript const line1 = 1; const line2 = 2; const line3 = 3; const line4 = 4; const line5 = 5; const line6 = 6; ``` -------------------------------- ### Configure Copy Button with shiki Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Use the `transformerCopyButton` directly with `shiki`'s `codeToHtml` function. This example shows how to configure the button's visibility and feedback duration. ```ts import { codeToHtml } from 'shiki' const code = await codeToHtml('console.log("Hello World")', { lang: 'ts', theme: 'vitesse-light', transformers: [ transformerCopyButton({ visibility: 'always', feedbackDuration: 3_000, }), ] }) ``` -------------------------------- ### HTML Inline Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inline.md Example of an inline HTML element. ```html
bar
``` -------------------------------- ### Highlight Lines and Show Line Numbers Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightedLinesWithShowLineNumbersAt.html Use `showLineNumbers` with a number to specify the starting line for numbering, and provide a list of lines or ranges to highlight. ```javascript const getStringLength = (str) => str.length; const add = (a, b) => a + b; const divide = (a, b) => a / b; const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; ``` -------------------------------- ### HTML Structure for Dual Themes Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Example HTML structure showing the `data-theme` attribute populated with space-separated theme values, used for dual-theme rendering. ```html ``` -------------------------------- ### Set Default Language to JavaScript Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/defaultLang.inline=js.html Configure the default language for code blocks when not explicitly specified. This example sets the default to JavaScript. ```javascript { inline: 'js' } ``` ```javascript const x = true; ``` -------------------------------- ### Unsupported Language Inline Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inline.md Example of inline code with an unsupported language tag. ```plaintext
bar
{:unsupportedlang} ``` ```plaintext
bar
\{:unsupportedlang} ``` -------------------------------- ### Highlight 'path/to/carrot' in JavaScript Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightChars.md This example shows how to highlight a specific file path string within a JavaScript variable assignment. The highlighting is configured via a comment. ```js const path = 'path/to/carrot'; ``` -------------------------------- ### Configure Copy Button with rehype-pretty-code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/plugins/copy-button.mdx Integrate the `transformerCopyButton` into `rehype-pretty-code` by passing it to the `transformers` array. This example demonstrates setting `visibility` to 'always' and `feedbackDuration` to 3000 milliseconds. ```ts 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' import { transformerCopyButton } from '@rehype-pretty/transformers' const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { transformers: [ transformerCopyButton({ visibility: 'always', feedbackDuration: 3_000, }), ], }) .use(rehypeStringify) .process("`\ console.log('Hello, World!') `\ `) console.log(String(file)) ``` -------------------------------- ### JavaScript Code Diff Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/diff.md Shows a diff in a JavaScript file, indicating removed and added lines. This format is often used in version control systems. ```diff import useSWR from 'swr' function Profile() { const { data, error } = useSWR('/api/user', fetcher) - if (error) return
failed to load
+ if (!data) return
loading...
return
hello {data.name}!
} ``` -------------------------------- ### JavaScript Inline Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inline.md Example of an inline JavaScript function definition. ```javascript const getStringLength = (str) => str.length; ``` -------------------------------- ### Importing RSC into a Next.js Page Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Example of importing and using the `Code` React Server Component within a Next.js page (`src/app/rsc/page.tsx`). ```typescript import * as React from "react"; import { Code } from "./code.tsx"; export default async function Page() { return (
); } ``` -------------------------------- ### Initialize Empty Node String Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/filterMetaString.html Initializes a constant variable 'node' with an empty string. This is often a starting point for string manipulation or building dynamic content. ```javascript const node = ''; ``` -------------------------------- ### Vite Development Server Output Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/ansi.html Example of typical output from the Vite development server, including port information and HMR updates. This demonstrates how ANSI escape codes can be used for formatting terminal output. ```bash vite --port 3123 ``` ```text vite v2.8.6 dev server running at: > Local: http://localhost:3123/ > Network: use `--host` to expose ready in 125ms. 8:38:02 PM [vite] hmr update /src/App.jsx ``` -------------------------------- ### Line Numbers with Meta String Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Activate line numbers by including `showLineNumbers` in the meta string. Optionally, specify a starting number with `showLineNumbers{n}`. Styling is handled via CSS counters. ```ts ```ts showLineNumbers{5} function add(a: number, b: number) { return a + b; } ``` ``` ```css /* code receives data-line-numbers and data-line-numbers-max-digits="n" */ 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: #64748b; } code[data-line-numbers-max-digits="2"] > [data-line]::before { width: 1.25rem; } code[data-line-numbers-max-digits="3"] > [data-line]::before { width: 1.75rem; } ``` -------------------------------- ### Add Shiki Transformers for Code Manipulation Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Integrate Shiki transformers, such as 'transformerNotationDiff', to extend the functionality of code blocks. This requires installing the '@shikijs/transformers' package. ```javascript import { transformerNotationDiff } from '@shikijs/transformers'; const options = { transformers: [transformerNotationDiff()], }; ``` -------------------------------- ### Configure Next.js with MDX and Rehype Pretty Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Integrate rehype-pretty-code into your Next.js project by configuring the next.config.mjs file. This setup enables MDX processing with rehype plugins. ```javascript import fs from "node:fs"; import nextMDX from "@next/mdx"; import rehypePrettyCode from "rehype-pretty-code"; /** @type {import('rehype-pretty-code').Options} */ const options = { // See Options section below. }; const withMDX = nextMDX({ extension: /\.mdx?$/, options: { remarkPlugins: [], rehypePlugins: [[rehypePrettyCode, options]], }, }); /** @type {import('next').NextConfig} */ const nextConfig = { reactStrictMode: true }; export default withMDX(nextConfig); ``` -------------------------------- ### Highlight Specific Lines in JavaScript Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightedLines.html Use the `data-highlighted-line` attribute to specify which lines to highlight. This example highlights lines 1, 3, and 6 through 8. ```javascript const getStringLength = (str) => str.length; const add = (a, b) => a + b; const divide = (a, b) => a / b; const subtract = (a, b) => a - b; const multiply = (a, b) => a * b; ``` -------------------------------- ### Highlighting Duplicate Variable Declarations Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsById.md Shows highlighting of duplicate variable declarations. This example might be used to identify potential errors or code redundancies. ```js const carrotcar,carcarrot; const carrotcar,carcarrot; ``` -------------------------------- ### Bypass Inline Code Example Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/bypassInlineCode.html Use the `bypassInlineCode:true` option to prevent inline code from being highlighted. This is useful when inline code should be treated as plain text. ```javascript const x = true; ``` ```javascript const x = true;{:js,bypassInlineCode:true} ``` -------------------------------- ### Highlight Plain Text with VS Code Tokens Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Use `{: .token}` to highlight inline code based on tokens defined in your VS Code theme. Tokens starting with '.' differentiate them from languages. ```mdx The name of the function is `getStringLength{:.entity.name.function}`. ``` ```mdx The name of the function is `getStringLength{:.fn}`. ``` -------------------------------- ### Highlighting 'carrot' in JavaScript Functions Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightPartialNode.html These examples showcase how a code highlighting system can target and emphasize specific substrings like 'carrot' within comments and string literals in JavaScript code. ```javascript function carrot() { // comment that contains carrot and other words. } ``` ```javascript function carrot() { //carrot carrot contains carrot and other words, carrot } ``` ```javascript function carrot() { // carrot } ``` ```javascript function carrot() { 'carrot'; } ``` -------------------------------- ### Set Single Shiki Theme by Name or JSON Object Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Configure rehype-pretty-code to use a single Shiki theme. You can specify a built-in theme by its name or provide a raw VS Code theme JSON object. The example demonstrates loading a theme from a file. ```javascript import fs from "node:fs"; import rehypePrettyCode from "rehype-pretty-code"; // Built-in named theme const optionsNamed = { theme: "one-dark-pro", }; // Custom JSON theme loaded from disk const optionsCustom = { theme: JSON.parse(fs.readFileSync("./themes/moonlight-ii.json", "utf-8")), }; // Usage in a unified pipeline const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, optionsCustom) .use(rehypeStringify) .process("```ts\nconst greet = (name: string) => `Hello, ${name}`; ```"); console.log(String(file)); ``` -------------------------------- ### JavaScript Code Block with Line Numbers Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/showLineNumbersStartAt.html This JavaScript code snippet is displayed with line numbers. It serves as a basic example for demonstrating line number functionality. ```javascript const a = 'a'; const b = 'b'; const c = 'c'; const a = 'a'; const b = 'b'; const c = 'c'; const a = 'a'; const b = 'b'; const c = 'c'; ``` -------------------------------- ### CSS Data Attributes for Styling Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Rehype Pretty Code uses CSS data attributes for styling. This example shows how to style code blocks, highlighted lines, highlighted characters, line numbers, titles, captions, and dual-theme switching. ```css /* Prevent overflow and add padding to code blocks */ pre { overflow-x: auto; padding: 1rem 0; } /* Every line in a block code */ pre [data-line] { padding: 0 1rem; } /* Highlighted lines ({1,3-5} in meta) */ [data-highlighted-line] { background-color: rgba(99, 102, 241, 0.15); border-left: 3px solid rgb(99, 102, 241); padding-left: calc(1rem - 3px); } /* Highlighted chars / words (/pattern/ in meta) */ [data-highlighted-chars] { background-color: rgba(250, 204, 21, 0.2); border-radius: 3px; padding: 1px 3px; } /* Line numbers via CSS counters */ 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: #64748b; } /* Code block title */ [data-rehype-pretty-code-title] { padding: 0.5rem 1rem; border-bottom: 1px solid #334155; font-family: monospace; font-size: 0.85rem; } /* Code block caption */ [data-rehype-pretty-code-caption] { padding: 0.25rem 1rem; font-size: 0.75rem; color: #94a3b8; } /* Dual-theme (dark/light) switching */ code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-light); background-color: var(--shiki-light-bg); } @media (prefers-color-scheme: dark) { code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-dark); background-color: var(--shiki-dark-bg); } } ``` -------------------------------- ### Specify Theme by String Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Sets the Shiki theme for code highlighting using a pre-packaged theme name as a string. ```javascript const options = { theme: "one-dark-pro", }; ``` -------------------------------- ### Custom Highlighter Configuration Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Configure the highlighter completely using the `getHighlighter` option, useful for setting Shiki options like `langs`. ```js import { createHighlighter } from "shiki"; const options = { getHighlighter: (options) => createHighlighter({ ...options, langs: [ "plaintext", async () => JSON.parse(await readFile("my-grammar.json", "utf-8")), ], }), }; ``` -------------------------------- ### Configure Custom Highlighter with Shiki Options Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Use the `getHighlighter` option to completely configure the highlighter. This is useful for setting Shiki options like `langs`. ```javascript import { getHighlighter } from "shiki"; const options = { getHighlighter: (options) => getHighlighter({ ...options, langs: [ "plaintext", async () => JSON.parse(await readFile("my-grammar.json", "utf-8")), ], }), }; ``` -------------------------------- ### Highlighting JavaScript Options Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightCharsComplex.html Demonstrates highlighting within JavaScript object properties, including theme names and conditional logic. ```javascript const options = { theme: 'monokai', }; ``` ```javascript const options = { theme: 'monokai', }; ``` ```javascript const options = { theme: light && fluffy ? 'solarized-light' : 'monokai', }; ``` -------------------------------- ### SvelteKit Integration with rehype-pretty-code and Transformers Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Set up SvelteKit to use rehype-pretty-code with remark-parse, remark-rehype, and rehype-stringify. Includes copy button and foldable lines transformers. ```ts // src/lib/markdown.ts 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"; import { transformerCopyButton, transformerFoldableLines } from "@rehype-pretty/transformers"; import type { Compatible } from "vfile"; export const toHTML = (content: Compatible | undefined) => unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { theme: "rose-pine", transformers: [ transformerCopyButton({ visibility: "always", feedbackDuration: 2_500 }), transformerFoldableLines({ lines: [[1, 2]] }), ], }) .use(rehypeStringify) .process(content); ``` -------------------------------- ### Configure Unified for Markdown Processing Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx This JavaScript code demonstrates how to use the `unified` library with `remark-parse`, `remark-rehype`, `rehype-pretty-code`, and `rehype-stringify` to process Markdown content and apply syntax highlighting. ```js import { unified } from "unified";\nimport remarkParse from "remark-parse";\nimport remarkRehype from "remark-rehype";\nimport rehypeStringify from "rehype-stringify";\nimport rehypePrettyCode from "rehype-pretty-code";\n\nasync function main() {\n const file = await unified()\n .use(remarkParse)\n .use(remarkRehype)\n .use(rehypePrettyCode, {\n // See Options section below.\n })\n .use(rehypeStringify)\n .process("`const numbers = [1, 2, 3]{:js}`");\n\n console.log(String(file));\n}\n\nmain();\n ``` -------------------------------- ### Configure Multiple Themes for Dark and Light Mode Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Define an object with `dark` and `light` keys to specify themes for different color modes. This enables dual-theme support. ```js const options = { theme: { dark: "github-dark-dimmed", light: "github-light", }, }; ``` -------------------------------- ### Highlight Plain Text with Tokens Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Use `{.token}` to highlight inline code based on VS Code theme tokens. Tokens are prefixed with a `.`. ```md The name of the function is `getStringLength{:.entity.name.function}`. ``` ```js const options = { tokensMap: { fn: "entity.name.function", }, }; ``` ```md The name of the function is `getStringLength{:.fn}`. ``` -------------------------------- ### Configure Multiple Themes for Dark/Light Mode Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Enable dual-theme support by providing an object with arbitrary color-mode keys (e.g., 'dark', 'light'). The plugin generates CSS custom properties that can be toggled with a CSS media query. Ensure you include the necessary CSS for theme switching. ```javascript const options = { theme: { dark: "github-dark-dimmed", light: "github-light", }, }; // Required CSS to activate the dual-theme variables: // code[data-theme*=" "], code[data-theme*=" "] span { // color: var(--shiki-light); // background-color: var(--shiki-light-bg); // } // @media (prefers-color-scheme: dark) { // code[data-theme*=" "], code[data-theme*=" "] span { // color: var(--shiki-dark); // background-color: var(--shiki-dark-bg); // } // } // // Output HTML: //
const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, options) .use(rehypeStringify) .process("```js\nconsole.log('hello'); ```"); console.log(String(file)); ``` -------------------------------- ### Configure Multiple Themes for Dark and Light Mode Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Define dark and light themes using the `theme` option. The `` element will have a `data-theme` attribute listing the themes. ```js const options = { theme: { dark: "github-dark-dimmed", light: "github-light", }, }; ``` ```scss code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-light); background-color: var(--shiki-light-bg); } @media (prefers-color-scheme: dark) { code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-dark); background-color: var(--shiki-dark-bg); } } ``` ```html ``` -------------------------------- ### Configure Line Numbers with Query Parameter Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/showLineNumbers.md Configure line number display using a query parameter in the file path. ```js const showLineNumbers = true; ``` -------------------------------- ### Inline Code Highlighting with Language and Token Scopes Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Append `{:lang}` to inline code for full syntax highlighting or `{:.token}` to color it using a VS Code token scope. ```markdown Call `Array.prototype.join(){:js}` to produce `'1-2-3'{:js}` from `[1,2,3]{:js}`. The keyword `function{:.keyword}` introduces a named function `greet{:.entity.name.function}`. ``` -------------------------------- ### Replace Default Shiki Highlighter Factory Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Customize Shiki's behavior by providing a custom `getHighlighter` factory. This allows you to load additional language grammars or configure Shiki in non-default ways, such as loading custom TextMate grammars from disk. ```javascript import { createHighlighter } from "shiki"; import { readFile } from "node:fs/promises"; const options = { getHighlighter: (opts) => createHighlighter({ ...opts, langs: [ "plaintext", // Load a custom TextMate grammar from disk async () => JSON.parse(await readFile("./grammars/my-lang.json", "utf-8")), ], }), }; const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, options) .use(rehypeStringify) .process("```my-lang\nhello world\n```"); ``` -------------------------------- ### Specify Theme by JSON Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Applies a custom Shiki theme by providing the theme's JSON data, read from a file. ```javascript const options = { theme: JSON.parse(fs.readFileSync("./themes/moonlight-ii.json", "utf-8")), }; ``` -------------------------------- ### Inline Code with Support Class Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inline.md Shows inline code usage with a specific class attribute. ```plaintext getStringLength ``` -------------------------------- ### Filter Meta String in Rehype Pretty Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Use the 'filterMetaString' option to preprocess the meta string of code blocks, preventing conflicts with other meta string parsers. This example removes filename attributes. ```javascript const options = { filterMetaString: (string) => string.replace(/filename="[^"]*"/, ""), }; ``` -------------------------------- ### Highlight Added and Removed Lines Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/transformers.md Use `[!code ++]` and `[!code --]` to highlight added and removed lines respectively. ```javascript const added = true; // [!code ++] const removed = true; // [!code --] const blank = true; ``` -------------------------------- ### Map VS Code Tokens for Shorter Usage Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Define a map in options to shorten token names for highlighting plain text, improving readability in documentation. ```js const options = { tokensMap: { fn: "entity.name.function", }, }; ``` -------------------------------- ### Highlighting State Variables Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsById.md Demonstrates highlighting state variables using IDs. Useful for identifying and manipulating specific parts of your application's state. ```js const [age, setAge] = useState(42); const [name, setName] = useState('Taylor'); ``` -------------------------------- ### Core API Usage with Unified Pipeline Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Integrate rehypePrettyCode into a unified pipeline with remark-parse, remark-rehype, and rehype-stringify. Configure theme and other options. ```ts 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"; async function main() { const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { theme: "github-dark-dimmed", // default theme keepBackground: true, // keep Shiki's background color grid: true, // grid layout for full-width line highlights }) .use(rehypeStringify) .process("```js\nconst x = 42;\n```"); console.log(String(file)); // →
//
  //       
  //         const
  //       
  //     
//
} main(); ``` -------------------------------- ### Highlight Multiple Character Sets Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Demonstrates highlighting multiple distinct character sets within a single code block using slashes as delimiters. ```markdown ```js /carrot/ /apple/ ``` ``` -------------------------------- ### CSS for Dual Theme Styling Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx CSS rules to apply theme-specific colors and background colors based on the `data-theme` attribute, supporting both light and dark modes. ```scss code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-light); background-color: var(--shiki-light-bg); } @media (prefers-color-scheme: dark) { code[data-theme*=" "], code[data-theme*=" "] span { color: var(--shiki-dark); background-color: var(--shiki-dark-bg); } } ``` -------------------------------- ### Highlight Lines by ID in JavaScript Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightLinesById.md Demonstrates how to specify line ranges for highlighting using IDs like '#a' and '#b'. Use this when you need to visually distinguish specific sections of code based on custom identifiers. ```js const line1 = 1; const line2 = 2; const line3 = 3; const line4 = 4; const line5 = 5; const line6 = 6; ``` -------------------------------- ### Highlighting a Range of Lines with showLineNumbersAt Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightedLinesWithShowLineNumbersAt.md Demonstrates highlighting a contiguous range of lines using showLineNumbersAt and showLineNumbers. ```javascript // should not be highlighted // should be highlighted // should be highlighted // should be highlighted // should not be highlighted ``` -------------------------------- ### Title and Caption with Meta String Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Add a file title and/or an explanatory caption to a code block using `title="..."` and `caption="..."` in the meta string. These are rendered as `
` elements. ```ts ```ts title="src/utils/greet.ts" caption="Exported helper used in pages" export function greet(name: string) { return `Hello, ${name}!`; } ``` ``` ```css [data-rehype-pretty-code-title] { font-family: monospace; font-size: 0.8rem; padding: 0.25rem 1rem; background: #1e293b; border-bottom: 1px solid #334155; } [data-rehype-pretty-code-caption] { font-size: 0.75rem; color: #94a3b8; padding: 0.25rem 1rem; } ``` -------------------------------- ### Next.js (MDX) Integration with rehype-pretty-code Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Configure Next.js to use rehype-pretty-code for markdown processing. Ensure the theme JSON is correctly imported and passed to the options. ```js // next.config.mjs import nextMDX from "@next/mdx"; import rehypePrettyCode from "rehype-pretty-code"; import moonlightTheme from "./assets/moonlight-ii.json" with { type: "json" }; /** @type {import('rehype-pretty-code').Options} */ const options = { keepBackground: false, theme: moonlightTheme, }; const withMDX = nextMDX({ extension: /\.(md|mdx)$/, options: { remarkPlugins: [], rehypePlugins: [[rehypePrettyCode, options]], }, }); export default withMDX({ reactStrictMode: true, pageExtensions: ["md", "mdx", "tsx", "ts", "jsx", "js"], }); ``` -------------------------------- ### Define Aliases for VS Code Token Scopes Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt The `tokensMap` option allows you to create short aliases for verbose VS Code token scope paths. These aliases can then be used in inline code highlighting syntax for brevity. ```javascript const options = { tokensMap: { fn: "entity.name.function", kw: "keyword.control", str: "string.quoted", }, }; // In Markdown, instead of `getStringLength{:.entity.name.function}`, // you can now write: `getStringLength{:.fn}` ``` -------------------------------- ### Empty HTML Tags Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsComplex.md Empty HTML tags for highlighting. ```html <> ``` ```html <> ``` ```html <> ``` -------------------------------- ### Use Custom Theme JSON in Rehype Pretty Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Load and apply a custom Shiki theme by reading a JSON file and parsing its content. This allows for complete control over the code block's appearance. ```javascript const options = { theme: JSON.parse(fs.readFileSync("./themes/moonlight-ii.json", "utf-8")), }; ``` -------------------------------- ### Astro Integration with rehype-pretty-code and Copy Button Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Integrate rehype-pretty-code into Astro, disabling Astro's built-in highlighter and enabling the copy button transformer. Ensure the theme is correctly imported. ```ts // astro.config.ts import mdx from "@astrojs/mdx"; import { defineConfig } from "astro/config"; import { rehypePrettyCode } from "rehype-pretty-code"; import moonlightTheme from "./public/theme/moonlight-ii.json"; import { transformerCopyButton } from "@rehype-pretty/transformers"; export default defineConfig({ markdown: { syntaxHighlight: false, // disable Astro's built-in highlighter rehypePlugins: [ [ rehypePrettyCode, { theme: moonlightTheme, transformers: [ transformerCopyButton({ visibility: "hover", feedbackDuration: 2_500 }), ], }, ], ], }, integrations: [mdx()], }); ``` -------------------------------- ### Highlight Inline Code with Language Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Append `{:lang}` to inline code to apply language-specific highlighting, treating it like a regular code block. ```mdx This is an array `[1, 2, 3]{:js}` of numbers 1 through 3. ``` -------------------------------- ### Visitor Hooks for HTML Customization Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Callback functions that allow direct manipulation of the generated hAST elements for customizing HTML output. ```js const options = { onVisitLine(element) { console.log("Visited line"); }, onVisitHighlightedLine(element) { console.log("Visited highlighted line"); }, onVisitHighlightedChars(element) { console.log("Visited highlighted chars"); }, onVisitTitle(element) { console.log("Visited title"); }, onVisitCaption(element) { console.log("Visited caption"); }, }; ``` -------------------------------- ### JavaScript Options Theme Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsComplex.md JavaScript object with a theme option. ```javascript const options = { theme: 'monokai', }; ``` ```javascript const options = { theme: 'monokai', }; ``` -------------------------------- ### Specify Theme in Rehype Pretty Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx Set the 'theme' option to a Shiki theme name string or a custom theme object. The default theme is 'github-dark-dimmed'. ```javascript const options = { theme: "one-dark-pro", }; ``` -------------------------------- ### React useState Hook Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/results/highlightCharsById.html Illustrates the basic usage of the useState hook in React to manage component state for numerical and string values. ```javascript const [age, setAge] = useState(42); const [name, setName] = useState('Taylor'); ``` -------------------------------- ### CSS for Theming Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/manyLines.md This CSS defines color variables for light and dark modes, applying them to various HTML elements. It's useful for creating adaptable user interfaces. ```css html { --page-color: white; --ink-color: black; } @media (prefers-color-scheme: dark) { html { --page-color: black; --ink-color: white; } } body { background-color: var(--page-color); color: var(--ink-color); } input { background-color: var(--page-color); color: var(--ink-color); border-color: var(--ink-color); } button { background-color: var(--ink-color); color: var(--page-color); } ``` -------------------------------- ### Vite Dev Server Output with ANSI Formatting Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/ansi.md This snippet shows the typical output from a Vite development server, utilizing ANSI escape codes for colored and styled text. It includes information about the server's local and network addresses, and HMR updates. ```ansi vite v2.8.6 dev server running at: > Local: http://localhost:3123/ > Network: use `--host` to expose ready in 125ms. 8:38:02 PM [vite] hmr update /src/App.jsx ``` -------------------------------- ### Highlight Characters with Slashes Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Highlights specific character sequences within a code block using forward slashes as delimiters in the meta string. ```markdown ```js /carrot/ ``` ``` -------------------------------- ### ANSI Highlighted Terminal Output Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx This snippet demonstrates how to render terminal output with ANSI color codes, preserving the original formatting and colors. ```ansi  vite v5.0.0 dev server running at:\n\n > Local: http://localhost:3000/\n > Network: use `--host` to expose\n\n ready in 125ms.\n\n8:38:02 PM [vite] hmr update /src/App.jsx\n ``` -------------------------------- ### Escaped HTML Inline Code Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/inline.md Demonstrates escaping curly braces in inline HTML code. ```html
bar
\{:html} ``` ```html
bar
\\{:html} ``` ```html
bar
\\\{:html} ``` -------------------------------- ### Next.js MDX Configuration Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Configure `rehype-pretty-code` within a Next.js `next.config.mjs` file for MDX processing. Ensure the `mdxRs` option is disabled if Rehype plugins do not work. ```js import nextMDX from "@next/mdx";\nimport rehypePrettyCode from "rehype-pretty-code";\n\n/** @type {import('rehype-pretty-code').Options} */\nconst options = {\n // See Options section below.\n};\n\nconst withMDX = nextMDX({\n extension: /\.mdx?$/,\n options: {\n remarkPlugins: [],\n rehypePlugins: [[rehypePrettyCode, options]],\n },\n});\n\n/** @type {import('next').NextConfig} */\nconst nextConfig = { reactStrictMode: true };\n\nexport default withMDX(nextConfig);\n ``` -------------------------------- ### Character / Word Highlighting with Meta String Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Highlight specific characters or words using `/pattern/` or `"pattern"` delimiters in the meta string. An optional numeric range can restrict occurrences. ```md ```js /useState/ /useEffect/ import { useState, useEffect } from "react"; function App() { const [count, setCount] = useState(0); useEffect(() => { document.title = count; }, [count]); } ``` ``` ```css /* All highlighted chars spans */ [data-highlighted-chars] { background-color: rgba(250, 204, 21, 0.2); border-radius: 2px; } ``` -------------------------------- ### Integrate Shiki Transformers Source: https://context7.com/rehype-pretty/rehype-pretty-code/llms.txt Augment the hAST tree for code blocks by providing an array of Shiki transformers. The `@shikijs/transformers` package offers pre-built transformers for features like diffs and focus highlighting. ```javascript import { transformerNotationDiff, transformerNotationFocus } from "@shikijs/transformers"; const options = { transformers: [ transformerNotationDiff(), // enables // [!code ++] / [!code --] transformerNotationFocus(), // enables // [!code focus] ], }; ``` -------------------------------- ### React Server Component for Code Highlighting Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/examples/next/src/app/index.mdx This component, designed for React Server Components, takes raw code as a string and returns it as highlighted HTML. It uses `unified` with `remark-parse`, `remark-rehype`, `rehype-pretty-code`, and `rehype-stringify`. ```typescript 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 (
); } async function highlightCode(code: string) { const file = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, { keepBackground: false, }) .use(rehypeStringify) .process(code); return String(file); } ``` -------------------------------- ### TypeScript Options Interface Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/docs/src/content/docs/index.mdx Defines the configuration options for the rehype-pretty-code plugin, including theme, language defaults, and transformer settings. ```typescript interface Options { grid?: boolean; theme?: Theme | Record; keepBackground?: boolean; bypassInlineCode?: boolean; defaultLang?: string | { block?: string; inline?: string }; tokensMap?: Record; transformers?: ShikiTransformer[]; filterMetaString?(str: string): string; getHighlighter?(options: BundledHighlighterOptions): Promise; onVisitLine?(element: LineElement): void; onVisitHighlightedLine?(element: LineElement): void; onVisitHighlightedChars?(element: CharsElement, id: string | undefined): void; onVisitTitle?(element: Element): void; onVisitCaption?(element: Element): void; } ``` -------------------------------- ### Highlighting HTML Elements Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsById.md Shows how to highlight an HTML element with a specific ID. This is useful for targeting and styling or manipulating DOM elements. ```js
``` -------------------------------- ### Highlighting a Variable by ID Source: https://github.com/rehype-pretty/rehype-pretty-code/blob/master/packages/core/test/fixtures/highlightCharsById.md Illustrates highlighting a variable named 'age' using a generic ID. This can be used for dynamic code analysis or transformation. ```js const age = 'age'; ```