@mdsx/rehype-custom-highlighter
A plugin for MDSX that allows you to use any syntax highlighter you want.
The @mdsx/rehype-custom-highlighter
plugin allows you to use any syntax highlighter you want with MDSX. This plugin processes fenced code blocks and lets you apply custom highlighting logic.
Type Definition
function rehypeCustomHighlight(options?: HighlightOptions): Transformer<Root, Root>;
type HighlightOptions = {
highlight?: (args: HighlightCallbackArgs) => MaybePromise<string | undefined>;
};
type HighlightCallbackArgs = {
/** The language identifier from the fenced code block (e.g., "svelte", "ts") */
lang: string | null | undefined;
/** The actual code content within the block */
value: string | undefined;
/** The metastring following the language declaration (e.g., `title="example.md" showLineNumbers`) */
meta: string | null | undefined;
};
Properties
highlight
Type: (args: HighlightCallbackArgs) => MaybePromise<string | undefined>
(optional)
A callback function that receives code block data and returns highlighted HTML. This function is called for each fenced code block in your markdown.
import { defineConfig } from 'mdsx';
import { rehypeCustomHighlight } from '@mdsx/rehype-custom-highlighter';
export const mdsxConfig = defineConfig({
extensions: ['.md'],
rehypePlugins: [
[
rehypeCustomHighlight,
{
highlight: async ({ lang, value, meta }) => {
// your custom highlighting logic here
return highlightedCode;
},
},
],
],
});
HighlightCallbackArgs
Type: HighlightCallbackArgs
The arguments passed to your highlight function:
lang
: The language identifier from the fenced code block (e.g., "svelte", "ts")value
: The actual code content within the blockmeta
: The metastring following the language declaration (e.g.,title="example.md" showLineNumbers
)
Note
The highlight
function can be synchronous or asynchronous. If it returns undefined
, the original code block will be left unchanged.
How It Works
The plugin does the following:
- Visits all
pre
elements in the AST - Extracts the
code
element within eachpre
block - Calls your
highlight
function with the code block data - Replaces the original code element with your highlighted HTML
- Escapes the HTML for safe use in Svelte components
The plugin only processes fenced code blocks (```
) and skips inline code or other elements.
Warning
The plugin expects your highlight
function to return valid HTML that will be safely escaped for use in Svelte components. Make sure your highlighter outputs properly formatted HTML.