UNPKG

@svelte-dev/pretty-code

Version:

Beautiful Svelte code blocks for Markdown or MDsveX.

32 lines (31 loc) 1.25 kB
/* eslint-disable @typescript-eslint/ban-ts-comment */ import { unified } from 'unified'; import rehypePrettyCode from 'rehype-pretty-code'; import remarkParse from 'remark-parse'; import remarkRehype from 'remark-rehype'; import rehypeStringify from 'rehype-stringify'; /** * Escape curlies, backtick, \t, \r, \n to avoid breaking output of {@html `here`} in .svelte * * [reference](https://github.com/pngwn/MDsveX/blob/6c60fe68c335fce559db9690fbf5e69ef539d37d/packages/mdsvex/src/transformers/index.ts#L571) * @param {string} str * @returns {string} */ const escape_svelty = (str) => str // @ts-expect-error .replace(/[{}`]/g, (c) => ({ '{': '{', '}': '}', '`': '`' })[c]) .replace(/\\([trn])/g, '\$1'); const makeSource = (code, lang, meta) => `\`\`\`${lang} ${meta}\n${code}\n\`\`\``; export function createHighlighter(options) { return async function highligher(raw, inputLang, metastring) { const html = await unified() .use(remarkParse) .use(remarkRehype) .use(rehypePrettyCode, options) .use(rehypeStringify) .process( // makeSource(raw, inputLang, metastring || '')); return escape_svelty(String(html)); }; }