|
| 1 | +import type MarkdownIt from 'markdown-it' |
| 2 | +import { bundledLanguages, getHighlighter } from 'shikiji' |
| 3 | +import type { BuiltinLanguage, BuiltinTheme, CodeOptionsThemes, CodeToHastOptions, Highlighter, LanguageInput } from 'shikiji' |
| 4 | +import { parseHighlightLines } from '../../shared/line-highlight' |
| 5 | + |
| 6 | +export type MarkdownItShikijiOptions = MarkdownItShikijiSetupOptions & { |
| 7 | + /** |
| 8 | + * Language names to include. |
| 9 | + * |
| 10 | + * @default Object.keys(bundledLanguages) |
| 11 | + */ |
| 12 | + langs?: Array<LanguageInput | BuiltinLanguage> |
| 13 | +} |
| 14 | + |
| 15 | +export type MarkdownItShikijiSetupOptions = CodeOptionsThemes<BuiltinTheme> & { |
| 16 | + /** |
| 17 | + * Add `highlighted` class to lines defined in after codeblock |
| 18 | + * |
| 19 | + * @default true |
| 20 | + */ |
| 21 | + highlightLines?: boolean | string |
| 22 | +} |
| 23 | + |
| 24 | +function setup(markdownit: MarkdownIt, highlighter: Highlighter, options: MarkdownItShikijiSetupOptions) { |
| 25 | + const { |
| 26 | + highlightLines = true, |
| 27 | + } = options |
| 28 | + |
| 29 | + markdownit.options.highlight = (code, lang = 'text', attrs) => { |
| 30 | + const codeOptions: CodeToHastOptions = { |
| 31 | + ...options, |
| 32 | + lang, |
| 33 | + } |
| 34 | + |
| 35 | + codeOptions.transforms ||= {} |
| 36 | + |
| 37 | + if (highlightLines) { |
| 38 | + const lines = parseHighlightLines(attrs) |
| 39 | + if (lines) { |
| 40 | + const className = highlightLines === true |
| 41 | + ? 'highlighted' |
| 42 | + : highlightLines |
| 43 | + |
| 44 | + codeOptions.transforms.line = (node, line) => { |
| 45 | + if (lines.includes(line)) |
| 46 | + node.properties.class += ` ${className}` |
| 47 | + return node |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + codeOptions.transforms.code = (node) => { |
| 53 | + node.properties.class = `language-${lang}` |
| 54 | + } |
| 55 | + |
| 56 | + return highlighter.codeToHtml( |
| 57 | + code, |
| 58 | + codeOptions, |
| 59 | + ) |
| 60 | + } |
| 61 | +} |
| 62 | + |
| 63 | +export default async function markdownItShikiji(options: MarkdownItShikijiOptions) { |
| 64 | + const themeNames = ('themes' in options ? Object.values(options.themes) : [options.theme]).filter(Boolean) as BuiltinTheme[] |
| 65 | + const highlighter = await getHighlighter({ |
| 66 | + themes: themeNames, |
| 67 | + langs: options.langs || Object.keys(bundledLanguages) as BuiltinLanguage[], |
| 68 | + }) |
| 69 | + |
| 70 | + return function (markdownit: MarkdownIt) { |
| 71 | + setup(markdownit, highlighter, options) |
| 72 | + } |
| 73 | +} |
0 commit comments