Skip to main content

@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.

mdsx.config.js
		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 block
  • meta: The metastring following the language declaration (e.g., title="example.md" showLineNumbers)

How It Works

The plugin does the following:

  1. Visits all pre elements in the AST
  2. Extracts the code element within each pre block
  3. Calls your highlight function with the code block data
  4. Replaces the original code element with your highlighted HTML
  5. Escapes the HTML for safe use in Svelte components

The plugin only processes fenced code blocks (```) and skips inline code or other elements.