pngwn / MDsveX

A markdown preprocessor for Svelte.
https://mdsvex.pngwn.io
MIT License
2.27k stars 96 forks source link

Highlight inline code such as \`console.log("hello");{:js}\` #543

Open jeremt opened 9 months ago

jeremt commented 9 months ago

It would be nice to be able to apply highlighting to inline blocks. To do so, I tried two approaches, which only works for <pre> blocks:

image
  1. Using rehype-pretty-code plugin :
import adapter from '@sveltejs/adapter-auto';
import {mdsvex} from 'mdsvex';
import {vitePreprocess} from '@sveltejs/kit/vite';
import rehypePrettyCode from 'rehype-pretty-code';

/** @type {import('mdsvex').MdsvexOptions} */
const mdsvexOptions = {
    extensions: ['.mdx'],
    highlight: false,

    remarkPlugins: [],
    rehypePlugins: [
        [
            rehypePrettyCode,
            {
                keepBackground: false,
                theme: {
                    dark: 'dark-plus',
                    light: 'light-plus',
                },
            },
        ],
    ],
};

/** @type {import('@sveltejs/kit').Config} */
const config = {
    extensions: ['.svelte', '.mdx'],
    preprocess: [vitePreprocess(), mdsvex(mdsvexOptions)],

    kit: {
        adapter: adapter(),
    },
};

export default config;
  1. Using highlight option :
import shiki from 'shiki';
import adapter from '@sveltejs/adapter-auto';
import {mdsvex, escapeSvelte} from 'mdsvex';
import {vitePreprocess} from '@sveltejs/kit/vite';

/** @type {import('mdsvex').MdsvexOptions} */
const mdsvexOptions = {
    extensions: ['.mdx'],
    highlight: {
        highlighter: async (code, lang) => {
            console.log(code, lang);
            const highlighter = await shiki.getHighlighter({themes: ['dark-plus', 'light-plus']});
            const darkHtml = escapeSvelte(highlighter.codeToHtml(code, {lang}));
            const lightHtml = escapeSvelte(highlighter.codeToHtml(code, {lang, theme: 'light-plus'}));
            return `{@html \`${darkHtml}${lightHtml}\` }`;
        },
    },
};

/** @type {import('@sveltejs/kit').Config} */
const config = {
    extensions: ['.svelte', '.mdx'],
    preprocess: [vitePreprocess(), mdsvex(mdsvexOptions)],

    kit: {
        adapter: adapter(),
    },
};

export default config;

Is it impossible to do using MDsvex or am I missing something? 🤔

PS: it works nicely using parsers like unified or contentlayer with next:

unified()
    .use(remarkParse)
    .use(remarkRehype)
    .use(rehypePrettyCode, {
        keepBackground: false,
        theme: {
            dark: 'dark-plus',
            light: 'light-plus',
        },
    })
    .use(rehypeStringify);
lubiah commented 4 months ago

@jeremt I was able to do this with mdsvex and I used the same syntax as you did. It's possible