/* ----------------------------------------------------------------------------- | Copyright (c) Jupyter Development Team. | Distributed under the terms of the Modified BSD License. |----------------------------------------------------------------------------*/ /* eslint-disable @typescript-eslint/no-explicit-any */ /** * @packageDocumentation * @module markedparser-extension */ import { PromiseDelegate } from '@lumino/coreutils'; import type { JupyterFrontEnd, JupyterFrontEndPlugin } from '@jupyterlab/application'; import { LruCache } from '@jupyterlab/coreutils'; import { IEditorLanguageRegistry } from '@jupyterlab/codemirror'; import { IMarkdownParser, removeMath } from '@jupyterlab/rendermime'; import type { IMarkdownHeadingToken } from '@jupyterlab/rendermime'; import { IMermaidMarkdown } from '@jupyterlab/mermaid'; import type { marked, MarkedExtension, MarkedOptions, Renderer, Token, Tokens } from 'marked'; // highlight cache key separator const FENCE = '```~~~'; const HEADING_TAG_REGEX = /^]*>/i; /** * An interface for fenced code block renderers. */ export interface IFencedBlockRenderer { languages: string[]; rank: number; walk: (text: string) => Promise; render: (text: string) => string | null; } /** * Options */ export interface IRenderOptions { /** handlers for fenced code blocks */ blocks?: IFencedBlockRenderer[]; } /** * Create a markdown parser * * @param languages Editor languages * @returns Markdown parser */ export function createMarkdownParser( languages: IEditorLanguageRegistry, options?: IRenderOptions ) { return { render: (content: string): Promise => { return Private.render(content, languages, options); }, getHeadingTokens: (content: string): Promise => { return Private.getHeadingTokens(content, options); } }; } /** * The markdown parser plugin. */ const plugin: JupyterFrontEndPlugin = { id: '@jupyterlab/markedparser-extension:plugin', description: 'Provides the Markdown parser.', autoStart: true, provides: IMarkdownParser, requires: [IEditorLanguageRegistry], optional: [IMermaidMarkdown], activate: ( app: JupyterFrontEnd, languages: IEditorLanguageRegistry, mermaidMarkdown: IMermaidMarkdown | null ) => { return createMarkdownParser(languages, { blocks: mermaidMarkdown ? [mermaidMarkdown] : [] }); } }; /** * Export the plugin as default. */ export default plugin; /** * A namespace for private marked functions */ namespace Private { let _initializing: PromiseDelegate | null = null; let _marked: typeof marked | null = null; let _blocks: IFencedBlockRenderer[] = []; let _languages: IEditorLanguageRegistry | null = null; let _markedOptions: MarkedOptions = {}; let _highlights = new LruCache(); export async function render( content: string, languages: IEditorLanguageRegistry, options?: IRenderOptions ): Promise { _languages = languages; if (!_marked) { _marked = await initializeMarked(options); } return _marked(content, _markedOptions); } /** * Load marked lazily and exactly once. */ export async function initializeMarked( options?: IRenderOptions ): Promise { if (_marked) { return _marked; } if (_initializing) { return await _initializing.promise; } // order blocks by `rank` _blocks = options?.blocks || []; _blocks = _blocks.sort( (a, b) => (a.rank ?? Infinity) - (b.rank ?? Infinity) ); _initializing = new PromiseDelegate(); // load marked lazily, and exactly once const [{ marked, Renderer }, plugins] = await Promise.all([ import('marked'), loadMarkedPlugins() ]); // use load marked plugins for (const plugin of plugins) { marked.use(plugin); } // finish marked configuration _markedOptions = { // use the explicit async paradigm for `walkTokens` async: true, // enable all built-in GitHub-flavored Markdown opinions gfm: true, // asynchronously prepare for any special tokens, like highlighting and mermaid walkTokens, // use custom renderer renderer: makeRenderer(Renderer) }; // complete initialization _marked = marked; _initializing.resolve(_marked); return _marked; } /** * Load and use marked plugins. * * As of writing, both of these features would work without plugins, but emit * deprecation warnings. */ async function loadMarkedPlugins(): Promise { // use loaded marked plugins return Promise.all([ (async () => (await import('marked-gfm-heading-id')).gfmHeadingId())(), (async () => (await import('marked-mangle')).mangle())() ]); } /** * Build a custom marked renderer. */ function makeRenderer(Renderer_: typeof Renderer): Renderer { const renderer = new Renderer_(); const originalCode = renderer.code; renderer.code = token => { const { text, lang } = token; // handle block renderers for (const block of _blocks) { if (lang && block.languages.includes(lang)) { const rendered = block.render(text); if (rendered != null) { return rendered; } } } // handle known highlighting const key = `${lang}${FENCE}${text}${FENCE}`; const highlight = _highlights.get(key); if (highlight != null) { return highlight; } // fall back to calling with the renderer as `this` return originalCode.call(renderer, token); }; return renderer; } /** * Apply and cache syntax highlighting for code blocks. */ async function highlight(token: Tokens.Code): Promise { const { lang, text } = token; if (!lang || !_languages) { // no language(s), no highlight return; } const key = `${lang}${FENCE}${text}${FENCE}`; if (_highlights.get(key)) { // already cached, don't make another DOM element return; } const el = document.createElement('div'); try { await _languages.highlight(text, _languages.findBest(lang), el); const html = `
${el.innerHTML}
`; _highlights.set(key, html); } catch (err) { console.error(`Failed to highlight ${lang} code`, err); } finally { el.remove(); } } /** * After parsing, lazily load and render or highlight code blocks */ async function walkTokens(token: Token): Promise { switch (token.type) { case 'code': if (token.lang) { for (const block of _blocks) { if (block.languages.includes(token.lang)) { await block.walk(token.text); return; } } } await highlight(token as Tokens.Code); } } /** * Extract heading metadata from markdown source. */ export async function getHeadingTokens( content: string, options?: IRenderOptions ): Promise { if (!_marked) { _marked = await initializeMarked(options); } const headings = new Array(); // Hide math from the lexer, as `renderMarkdown` does, but not single `$` // math that spans lines: those `$` are often dollar amounts, and the // editor shows any heading on those lines. const { text, math } = removeMath(content); const tokens = _marked.lexer(restoreMath(text, math, spansLines)); // Extract heading tokens and compute line numbers // Include three token types that may contain headings: // - heading: Standard markdown headings (# Title) // - html: Standalone HTML heading blocks (

Title

) // - paragraph: Only paragraphs with nested HTML tokens (inline html tags) that might contain embedded headings (

Title

) let currentLine = 0; for (const token of tokens) { const raw = restoreMath(token.raw, math); if ( token.type === 'heading' || (token.type === 'html' && containsHeadingTag(token.raw)) || (token.type === 'paragraph' && containsInlineHeading(token)) ) { headings.push({ raw, line: currentLine }); } currentLine += raw.split('\n').length - 1; } return headings; } function containsHeadingTag(raw: any) { return HEADING_TAG_REGEX.test(raw); } function containsInlineHeading(token: Tokens.Generic): boolean { if (!token.tokens) return false; return token.tokens.some( (t: Tokens.Generic) => t.type === 'html' && containsHeadingTag(t.raw) ); } /** * Whether math in single `$` spans more than one line. */ function spansLines(math: string): boolean { return /^\$[^$]/.test(math) && math.includes('\n'); } /** * Put back the math source hidden by `removeMath` that `filter` accepts, * undoing the HTML escaping it applies, so that the result matches the * Markdown source. */ function restoreMath( text: string, math: string[], filter: (source: string) => boolean = () => true ): string { const placeholder = /@@(\d+)@@/g; let restored = ''; let end = 0; let match: RegExpExecArray | null; while ((match = placeholder.exec(text)) !== null) { const source: string | undefined = math[Number(match[1])]; if (source === undefined) { // Text such as `@@1` right before a placeholder forms a `@@n@@` that // has no math: look for the placeholder from the next character. placeholder.lastIndex = match.index + 1; } else if (filter(source)) { restored += text.slice(end, match.index) + source .replace(/</g, '<') .replace(/>/g, '>') .replace(/&/g, '&'); end = placeholder.lastIndex; } } return restored + text.slice(end); } }