import { BaseParagraphPlugin, ContentSlice, DebugPlugin, definePlugin, type DefinitionOf, editorCommands, type Element, ElementApi, type ElementOf, inputRuleVeto, type Location, NodeApi, type NodeEntry, type NodeKey, type NodeSelection, PathApi, PointApi, type BlockInsertOptions, type BlockUpsertOptions, PLUGINS, property, type Range, RangeApi, schema, SelectionApi, txLocate, locateAt, } from '../../../core'; import { canPlaceBlocksAtPath, isDocumentView } from '../../../facade'; import { failInvariant } from '../../../internal/failInvariant'; import { applyBlockInsertion } from '../../../internal/plugin/blockInsertion'; import { applyBlockReleases, canReplaceContainers, readBlockReleases, } from '../../../internal/plugin/blockRelease'; import { readVSCodeLanguage } from '../../../internal/utils/vscodeClipboard'; import { MATHML_FIRST_CHILD_DRAWN } from '../../../lib/plugins/html/htmlAst'; const CODE_LANGUAGE_CLASS_RE = /(?:^|\s)language-([^\s]+)/; const NON_WHITESPACE = /\S/; const NON_WHITESPACE_OR_END = /\S|$/; const TRAILING_NEWLINES = /\n+$/; export type HighlightNode = { children?: HighlightNode[]; properties?: Record; type: string; value?: string; }; export type HighlightResult = { children: HighlightNode[]; type: string; }; export type CodeHighlightLowlight = { highlight( language: string, value: string, options?: Readonly<{ prefix?: string | null }> | null ): HighlightResult; listLanguages(): string[]; registered(aliasOrName: string): boolean; }; type CodeBlockDecoration = Readonly<{ attributes: Readonly<{ className: string; 'data-code-block-syntax': '' }>; key: string; range: Range; }>; type CodeHighlightWarning = | { error: unknown; kind: 'highlight'; language: string } | { kind: 'missing-language'; language: string }; type CodeHighlightCache = { attributes: ReadonlyMap; decorations: readonly CodeBlockDecoration[]; language: string | null; leafLengths: readonly number[]; lowlight: CodeHighlightLowlight; text: string; }; const getLineStartOffset = (text: string, offset: number) => offset === 0 ? 0 : text.lastIndexOf('\n', offset - 1) + 1; const getLineEndOffset = (text: string, offset: number) => { const nextBreak = text.indexOf('\n', offset); return nextBreak === -1 ? text.length : nextBreak; }; const getIndentDepth = (text: string, offset: number) => { const lineStart = getLineStartOffset(text, offset); const lineEnd = getLineEndOffset(text, offset); return text.slice(lineStart, lineEnd).search(NON_WHITESPACE_OR_END); }; const countTrailingNewlines = (text: string) => text.match(TRAILING_NEWLINES)?.[0].length ?? 0; const readCodeDomText = (node: Node): string => { if (node.nodeName === 'SELECT') return ''; const parent = node.parentElement; if ( parent && MATHML_FIRST_CHILD_DRAWN.has(parent.localName) && parent.closest('math') && (node as ChildNode & NonDocumentTypeChildNode).previousElementSibling ) { return ''; } if (node.nodeName === 'BR') return '\n'; if (node.nodeType === node.TEXT_NODE) return node.textContent ?? ''; return Array.from(node.childNodes).map(readCodeDomText).join(''); }; const restoreTrailingNewlines = (text: string, element: HTMLElement) => { const encoded = element.getAttribute( 'data-editor-html-code-trailing-newlines' ); if (!encoded || !/^\d+$/.test(encoded)) return text; const expected = Number(encoded); const current = countTrailingNewlines(text); if (!Number.isSafeInteger(expected) || expected > text.length + 1) { return text; } return current < expected ? text + '\n'.repeat(expected - current) : text; }; const getEquationTexCarriers = (element: HTMLElement) => Array.from( element.querySelectorAll( '[data-editor-html-equation], [data-editor-html-equation-latex]' ) ); const getSelectedLineStarts = (text: string, start: number, end: number) => { const starts = [getLineStartOffset(text, start)]; let nextBreak = text.indexOf('\n', starts[0]); while (nextBreak !== -1 && nextBreak + 1 < end) { starts.push(nextBreak + 1); nextBreak = text.indexOf('\n', nextBreak + 1); } return starts; }; const offsetToLinePoint = (text: string, offset: number) => { const before = text.slice(0, offset); const line = before.split('\n').length - 1; const lineStart = before.lastIndexOf('\n') + 1; return { line, offset: offset - lineStart }; }; const pointToCodeOffset = ( codeBlock: Element, point: { offset: number; path: readonly number[] } ) => { const leafIndex = point.path.at(-1) ?? 0; let offset = 0; for ( let index = 0; index < leafIndex && index < codeBlock.children.length; index += 1 ) { offset += NodeApi.string(codeBlock.children[index]).length; } return offset + point.offset; }; const codeOffsetToPoint = ( codeBlock: Element, blockPath: readonly number[], targetOffset: number ) => { let remaining = targetOffset; for (let index = 0; index < codeBlock.children.length; index += 1) { const { length } = NodeApi.string(codeBlock.children[index]); if (remaining <= length || index === codeBlock.children.length - 1) { return { offset: Math.max(0, Math.min(remaining, length)), path: [...blockPath, index], }; } remaining -= length; } return { offset: 0, path: [...blockPath, 0] }; }; const getLeafLengths = (block: Element) => block.children.map((child) => NodeApi.string(child).length); const sameLeafLengths = (a: readonly number[], b: readonly number[]) => a.length === b.length && a.every((length, index) => length === b[index]); export const BaseCodeBlockPlugin = definePlugin(PLUGINS.codeBlock, { schema: { element: { content: schema.content.text({ default: 'text', min: 1 }), contentMarks: false, ownsExit: true, properties: { language: property.string(), meta: property.string() }, slice: { plainText: true, preserveContext: true }, }, }, component: 'pre', formats: ({ defineFormats, schema: { type } }) => defineFormats({ docx: { decode: ({ decodeInlines, node }) => { const children = decodeInlines(node.children); return { children: children.length > 0 ? children : [{ text: '' }], type, }; }, encode: ({ encodeInlines, node }) => ({ children: encodeInlines(), ...(node.language ? { codeLanguage: node.language } : {}), isCodeBlock: true, kind: 'paragraph', preserveWhitespace: true, }), node: 'codeBlock', }, html: { decode: ({ element, preserve, report }) => { if (element.querySelector('math')) { report({ action: 'replaced', kind: 'element', message: 'Plate HTML decode kept only the drawn text of in a code block.', }); const carriers = getEquationTexCarriers(element); if ( carriers.every( (carrier) => carrier.localName === 'math' || carrier.querySelector('math') ) ) { for (const carrier of carriers) { preserve( carrier, 'data-editor-html-equation', 'data-editor-html-equation-latex' ); } } } const languageClass = element .querySelector(':scope > code') ?.className.match(CODE_LANGUAGE_CLASS_RE)?.[1]; const language = element.getAttribute('data-editor-html-language') || element.dataset.language || languageClass || undefined; const meta = element.getAttribute('data-editor-html-meta') ?? undefined; const text = restoreTrailingNewlines( readCodeDomText(element), element ); preserve( 'data-editor-html-code-trailing-newlines', 'data-editor-html-language', 'data-editor-html-meta' ); return { children: [{ text }], ...(language ? { language } : {}), ...(meta !== undefined ? { meta } : {}), }; }, encode: ({ content, node, preserve }) => { const trailingNewlines = countTrailingNewlines(NodeApi.string(node)); preserve('language', 'meta'); return { attributes: { ...(trailingNewlines > 0 ? { 'data-editor-html-code-trailing-newlines': trailingNewlines, } : {}), 'data-editor-html-language': node.language, 'data-editor-html-meta': node.meta, }, children: [{ children: content, tag: 'code' }], tag: 'pre', }; }, match: [ { tag: 'pre' }, { style: { fontFamily: 'Consolas' }, tag: 'p' }, ], priority: 10, }, markdown: { node: 'code', decode: ({ node }) => ({ ...(node.lang ? { language: node.lang } : {}), ...(node.meta ? { meta: node.meta } : {}), children: [{ text: node.value || '' }], type, }), encode: ({ node, preserve }) => { preserve('language'); // A fence writes its meta only after a language. if (node.language) preserve('meta'); return { lang: node.language, meta: node.meta, type: 'code', value: NodeApi.string(node), }; }, }, }), shortcuts: { selectAll: { keys: 'mod+a' }, tab: { keys: 'tab' }, untab: { keys: 'shift+tab' }, }, }) .extend(({ editor, plugin, schema: { type } }) => { type CodeBlock = ElementOf; type CodeBlockInsertInput = Pick; return { update: ({ tx }) => { const paragraphType = editor.plugin(BaseParagraphPlugin).schema.type; const codeBlockTextPath = (path: readonly number[]) => [...path, 0]; const createParagraphs = (code: string) => code.split('\n').map((text) => ({ children: [{ text }], type: paragraphType, })); const pointInBlock = ( blockPath: readonly number[], point: { path: readonly number[] } ) => PathApi.isAncestor(blockPath, point.path); const mapPointToParagraph = ( codeBlock: Element, blockPath: readonly number[], code: string, point: { offset: number; path: readonly number[]; root?: string } ) => { const mapped = offsetToLinePoint( code, pointToCodeOffset(codeBlock, point) ); const blockIndex = blockPath.at(-1); if (blockIndex === undefined) return point; return { offset: mapped.offset, path: [...blockPath.slice(0, -1), blockIndex + mapped.line, 0], ...(point.root ? { root: point.root } : {}), }; }; const unwrap = ({ at, }: { at?: Location | NodeSelection; } = {}) => { if (at === undefined && !tx.selection()) return false; let unwrapped = false; const codeBlockEntries = Array.from( tx.nodes.entries({ at, type: plugin, }) ).reverse(); for (const [codeBlock, codeBlockPath] of codeBlockEntries) { const code = NodeApi.string(codeBlock); const selection = tx.selection(); const mappedSelection = selection && pointInBlock(codeBlockPath, selection.anchor) && pointInBlock(codeBlockPath, selection.focus) ? { anchor: mapPointToParagraph( codeBlock, codeBlockPath, code, selection.anchor ), focus: mapPointToParagraph( codeBlock, codeBlockPath, code, selection.focus ), } : undefined; if ( !tx.nodes.replace(createParagraphs(code), { at: codeBlockPath }) ) { continue; } unwrapped = true; if (mappedSelection) tx.selection.set(mappedSelection); } return unwrapped; }; const codeRuns = (blocks: ReadonlyArray>) => { const runs: Array>> = []; for (const entry of blocks) { const run = runs.at(-1); const last = run?.at(-1); if ( run && last && PathApi.equals(PathApi.next(last[1]), entry[1]) ) { run.push(entry); } else { runs.push([entry]); } } const codes = runs.map((run) => ({ children: [ { text: run.map(([block]) => NodeApi.string(block)).join('\n') }, ], type, })); if ( runs.length === 0 || !runs.every((run, index) => canPlaceBlocksAtPath(tx.schema, run[0][1], [codes[index]], { removing: run.map(([, path]) => path.at(-1) ?? 0), root: tx.view.root(), }) ) ) { return false; } const keys: NodeKey[] = []; for (const [index, run] of [...runs.entries()].toReversed()) { const [, at] = run[0]; if (!tx.nodes.replace(codes[index], { at })) { failInvariant('A checked code block conversion refused.'); } const key = tx.key(at); if (key) keys.push(key); for (const [, path] of run.slice(1).toReversed()) { tx.nodes.remove({ at: path }); } } const [first, ...rest] = keys.flatMap((key) => { const entry = tx.nodes.get(key); return entry ? [entry[1]] : []; }); if (first) { tx.selection.set( SelectionApi.nodes([first, ...rest], { mode: 'block', root: tx.view.root(), }) ); } return true; }; const insertCodeBlock = ( input: CodeBlockInsertInput = {}, options: BlockInsertOptions = {} ) => (tx.selection() !== null || options.at !== undefined || options.after !== undefined || options.before !== undefined) && tx.blocks.insert(tx.schema.create(type, input), { ...options, select: options.select ?? true, }) !== undefined; const applyCodeBlockInsertion = ( mode: 'insert' | 'upsert', input: CodeBlockInsertInput = {}, options: BlockInsertOptions | BlockUpsertOptions = {} ) => applyBlockInsertion({ editor, insert: (insertOptions) => insertCodeBlock(input, insertOptions), matches: (block) => block.type === type && block.listType === undefined, mode, onReuse: (block, key) => { if ( input.language !== undefined && block.language !== input.language ) { tx.nodes.set({ language: input.language }, { at: key }); } }, options, tx, }); const tab = (reverse = false) => { const selection = tx.selection(); if (!selection) return false; const codeBlock = tx.nodes.above({ at: selection.anchor, type: plugin, }); if (!codeBlock || !pointInBlock(codeBlock[1], selection.focus)) { return false; } const text = NodeApi.string(codeBlock[0]); const value = ' '; if (!tx.selection.isExpanded()) { const anchorOffset = pointToCodeOffset( codeBlock[0], selection.anchor ); const lineStart = getLineStartOffset(text, anchorOffset); const beforeCursor = text.slice(lineStart, anchorOffset); const offset = NON_WHITESPACE.test(beforeCursor) ? anchorOffset : lineStart; if (reverse) { const removable = text .slice(lineStart, lineStart + value.length) .match(/^[ \t]{1,2}/)?.[0].length; if (!removable) return true; tx.text.delete({ at: { anchor: codeOffsetToPoint( codeBlock[0], codeBlock[1], lineStart ), focus: codeOffsetToPoint( codeBlock[0], codeBlock[1], lineStart + removable ), }, }); } else { tx.text.insert(value, { at: offset === anchorOffset ? selection.anchor : codeOffsetToPoint(codeBlock[0], codeBlock[1], offset), }); } return true; } const [start, end] = RangeApi.edges(selection); const lineStarts = getSelectedLineStarts( text, pointToCodeOffset(codeBlock[0], start), pointToCodeOffset(codeBlock[0], end) ).reverse(); for (const lineStart of lineStarts) { const currentEntry = tx.nodes.get(codeBlock[1]); const currentBlock = currentEntry && ElementApi.isElement(currentEntry[0]) ? currentEntry[0] : codeBlock[0]; if (reverse) { const removable = text .slice(lineStart, lineStart + value.length) .match(/^[ \t]{1,2}/)?.[0].length; if (!removable) continue; tx.text.delete({ at: { anchor: codeOffsetToPoint( currentBlock, codeBlock[1], lineStart ), focus: codeOffsetToPoint( currentBlock, codeBlock[1], lineStart + removable ), }, }); } else { tx.text.insert(value, { at: codeOffsetToPoint(currentBlock, codeBlock[1], lineStart), }); } } return true; }; return { insert: txLocate( locateAt(1, 'at', 'after', 'before'), ( input: CodeBlockInsertInput = {}, options: BlockInsertOptions = {} ) => applyCodeBlockInsertion('insert', input, options) ), selectAll: () => { const codeBlock = tx.nodes.above({ type: plugin, }); if (!codeBlock) return false; const selection = tx.selection(); const blockRange = tx.ranges.get(codeBlock[1]); if ( selection && blockRange && RangeApi.equals(selection, blockRange) ) { return false; } tx.selection.set(codeBlock[1]); return true; }, tab: txLocate( false, ({ reverse = false }: { reverse?: boolean } = {}) => tab(reverse) ), toggle: (): boolean => { const initial = tx.selection(); if (!initial) return false; const selected = tx.nodes.blocks({ mode: 'lowest' }); const releases = readBlockReleases( editor, tx, selected, () => true ); const [release] = releases; if (release) { const [start, end] = RangeApi.edges(initial); const startBlock = tx.nodes.block({ at: start }); const endBlock = tx.nodes.block({ at: end }); // The released block converts alone; the rest of its container // never joins the code. if ( releases.length > 1 || !startBlock || !endBlock || tx.key(startBlock[1]) !== release.key || tx.key(endBlock[1]) !== release.key ) { return false; } } if (tx.nodes.some({ type: plugin })) return unwrap(); if (!release && tx.selection.nodes().length > 0) { return codeRuns(selected); } if (release) { const code = { children: [{ text: NodeApi.string(release.block) }], type, }; const fit = release.fit.map((child) => child === release.block ? code : child ); if (!canReplaceContainers(tx, new Map([[release, fit]]))) { return false; } applyBlockReleases(tx, releases); } const selection = tx.selection(); if (!selection) return false; const [start, end] = RangeApi.edges(selection); const startBlock = tx.nodes.block({ at: start }); const endBlock = tx.nodes.block({ at: end }); if (!startBlock || !endBlock) return false; const startParent = startBlock[1].slice(0, -1); const endParent = endBlock[1].slice(0, -1); const startIndex = startBlock[1].at(-1); const endIndex = endBlock[1].at(-1); if ( startIndex === undefined || endIndex === undefined || !PathApi.equals(startParent, endParent) ) { return tx.blocks.set({ type }, { at: startBlock[1] }); } const blocks: Array> = []; for (let index = startIndex; index <= endIndex; index++) { const block = tx.nodes.get([...startParent, index], { match: ElementApi.isElement, }); if (block) blocks.push(block); } if (blocks.length === 0) return false; const values = blocks.map(([block]) => NodeApi.string(block)); const mapSelectionPoint = (point: typeof selection.anchor) => { let offset = 0; for (let index = 0; index < blocks.length; index++) { const [, blockPath] = blocks[index]; if (pointInBlock(blockPath, point)) { const blockStart = tx.points.start(blockPath); const range = blockStart && tx.ranges.get(blockStart, point); offset += range ? tx.text.string(range).length : 0; return { offset, path: codeBlockTextPath(blocks[0][1]), ...(point.root ? { root: point.root } : {}), }; } offset += values[index].length + 1; } return point; }; const mappedSelection = { anchor: mapSelectionPoint(selection.anchor), focus: mapSelectionPoint(selection.focus), }; // The replacement goes first: a refused one leaves the other // blocks in place. if ( !tx.nodes.replace( { children: [{ text: values.join('\n') }], type }, { at: blocks[0][1] } ) ) { return false; } for (const [, blockPath] of blocks.slice(1).reverse()) { tx.nodes.remove({ at: blockPath }); } tx.selection.set(mappedSelection); return true; }, untab: () => tab(true), upsert: txLocate( locateAt(1, 'after', 'before'), ( input: CodeBlockInsertInput = {}, options: BlockUpsertOptions = {} ) => applyCodeBlockInsertion('upsert', input, options) ), }; }, }; }) .extend((context) => ({ contributions: [inputRuleVeto.of({ element: context.schema.type })], dataTransferFormats: [ { accept: ({ state }) => { const selection = state.selection(); return ( !selection || !state.nodes.block({ at: selection, type: context.schema.type, }) ); }, decode: ({ data, snapshot }) => { const language = readVSCodeLanguage(snapshot); if (language === null || language === 'markdown') return null; return ContentSlice.closed([ { children: [{ text: data }], language, type: context.schema.type, }, ]); }, mimeType: 'text/plain', priority: 200, }, ], commands: ({ handle }) => [ handle(editorCommands.delete, ({ input, state }) => { const selection = state.selection(); if (!selection || state.selection.isExpanded()) { return false; } if (input.direction === 'forward') { if (input.unit && input.unit !== 'character') return false; const currentBlock = state.nodes.block({ at: selection.anchor }); if (!currentBlock || NodeApi.string(currentBlock[0]).length === 0) { return false; } const blockEnd = state.points.end(currentBlock[1]); if (!blockEnd || !PointApi.equals(selection.anchor, blockEnd)) { return false; } const nextPath = PathApi.next(currentBlock[1]); const nextEntry = state.nodes.get(nextPath); if ( !nextEntry || !ElementApi.isElement(nextEntry[0]) || nextEntry[0].type !== context.schema.type ) { return false; } const nextCodeBlock = nextEntry[0]; const newlineIndex = NodeApi.string(nextCodeBlock).indexOf('\n'); if (newlineIndex === -1) return false; if (newlineIndex === 0) { return state.transaction((tx) => { tx.text.delete({ at: { anchor: codeOffsetToPoint(nextCodeBlock, nextPath, 0), focus: codeOffsetToPoint(nextCodeBlock, nextPath, 1), }, }); }); } return state.transaction((tx) => { tx.nodes.split({ always: true, at: codeOffsetToPoint(nextCodeBlock, nextPath, newlineIndex), match: (_node, path) => PathApi.equals(path, nextPath), }); const secondEntry = tx.nodes.get(PathApi.next(nextPath)); if (secondEntry && ElementApi.isElement(secondEntry[0])) { tx.text.delete({ at: { anchor: codeOffsetToPoint(secondEntry[0], secondEntry[1], 0), focus: codeOffsetToPoint(secondEntry[0], secondEntry[1], 1), }, }); } tx.nodes.merge({ at: nextPath }); }); } if (input.direction !== 'backward') return false; const codeBlock = state.nodes.above({ type: context.plugin }); if ( !codeBlock || codeBlock[0].type !== context.schema.type || pointToCodeOffset(codeBlock[0], selection.anchor) !== 0 ) { return false; } if (NodeApi.string(codeBlock[0]).length > 0) { return state.transaction(() => {}); } return state.transaction((tx) => { tx.nodes.set( { type: context.editor.plugin(BaseParagraphPlugin).schema.type, }, { at: codeBlock[1] } ); }); }), handle(editorCommands.insertBreak, ({ state }) => { const selection = state.selection(); const codeBlock = selection ? state.nodes.above({ at: selection, type: context.plugin, }) : undefined; if ( !selection || !codeBlock || codeBlock[0].type !== context.schema.type || !PathApi.isAncestor(codeBlock[1], selection.focus.path) ) { return false; } const code = NodeApi.string(codeBlock[0]); const [start, end] = RangeApi.edges(selection); const startOffset = pointToCodeOffset(codeBlock[0], start); const endOffset = pointToCodeOffset(codeBlock[0], end); const indentDepth = getIndentDepth(code, startOffset); const suffixIndent = code.slice(endOffset).match(/^[ \t]*/)?.[0].length ?? 0; const indent = ' '.repeat(Math.max(0, indentDepth - suffixIndent)); return state.transaction((tx) => { tx.text.insert(`\n${indent}`, { at: selection }); }); }), ], })); export type CodeBlockElement = ElementOf; export type CodeHighlightPluginState = { defaultLanguage: string | null; lowlight: CodeHighlightLowlight | null; }; export const BaseCodeHighlightPlugin = definePlugin(PLUGINS.codeSyntax, { dependencies: [BaseCodeBlockPlugin], initialState: (): CodeHighlightPluginState => ({ defaultLanguage: null, lowlight: null, }), }).extend(({ editor, store }) => { const blockDecorations = new Map(); // Documents rendered one after another share unchanged blocks, so their // highlighting is found by block identity without a key lookup. let decorationsByBlock = new WeakMap(); // Every node's decoration read checks the code block type, and resolving a // portal costs more than the rest of that check; the portal stays live. const resolveCodeBlock = () => editor.plugin(BaseCodeBlockPlugin); let codeBlock: ReturnType | undefined; let nextSyntaxKey = 0; let observers = 0; const parseNodes = ( nodes: HighlightNode[], className: string[] = [], result: Array<{ classes: string[]; text: string }> = [] ) => { for (const node of nodes) { if (node.type === 'element') { const nodeClassName = node.properties?.className; const classes = [ ...className, ...(Array.isArray(nodeClassName) ? nodeClassName.map(String) : typeof nodeClassName === 'string' ? [nodeClassName] : []), ]; parseNodes(node.children ?? [], classes, result); } else if (node.type === 'text' && typeof node.value === 'string') { result.push({ classes: className, text: node.value }); } } return result; }; return { decorate: { observe: ({ refresh }) => { observers += 1; const unsubscribe = store.subscribe(() => { blockDecorations.clear(); decorationsByBlock = new WeakMap(); refresh({ nodeKeys: 'all' }); }); return () => { unsubscribe(); observers -= 1; if (observers === 0) { blockDecorations.clear(); decorationsByBlock = new WeakMap(); } }; }, // Reads the code block itself: its decorations cover its text, and a // change to that text invalidates the block too. read: ({ editor: view, entry: [block, blockPath], }): readonly CodeBlockDecoration[] => { if (!ElementApi.isElement(block)) return []; codeBlock ??= resolveCodeBlock(); if (block.type !== codeBlock.schema.type) return []; const { defaultLanguage, lowlight } = store.get(); if (!lowlight) return []; const language = (typeof block.language === 'string' ? block.language : undefined) || defaultLanguage; const atBlockPath = (cached: CodeHighlightCache) => { const cachedPath = cached.decorations[0]?.range.anchor.path; if (cachedPath && !PathApi.isParent(blockPath, cachedPath)) { const leafPaths = new Map(); const resolveLeafPath = (leafIndex: number) => { let path = leafPaths.get(leafIndex); if (!path) { path = Object.freeze([...blockPath, leafIndex]); leafPaths.set(leafIndex, path); } return path; }; cached.decorations = Object.freeze( cached.decorations.map((decoration) => Object.freeze({ ...decoration, range: Object.freeze({ anchor: Object.freeze({ ...decoration.range.anchor, path: resolveLeafPath( decoration.range.anchor.path.at(-1) ?? 0 ), }), focus: Object.freeze({ ...decoration.range.focus, path: resolveLeafPath( decoration.range.focus.path.at(-1) ?? 0 ), }), }), }) ) ); } return cached.decorations; }; const sameBlock = decorationsByBlock.get(block); if ( sameBlock?.language === language && sameBlock.lowlight === lowlight ) { return atBlockPath(sameBlock); } const text = NodeApi.string(block); const leafLengths = getLeafLengths(block); // A key follows a block across the live editor's edits. Nodes of a // document view get new keys, and resolving one indexes the whole // document, so there only identity finds a block's highlighting. const blockKey = isDocumentView(view) ? '' : (view.key(blockPath) ?? ''); const previous = blockKey ? blockDecorations.get(blockKey) : undefined; if ( previous?.language === language && previous.text === text && previous.lowlight === lowlight && sameLeafLengths(previous.leafLengths, leafLengths) ) { decorationsByBlock.set(block, previous); return atBlockPath(previous); } let highlighted: HighlightResult; let warning: CodeHighlightWarning | undefined; try { if (!language || language === 'plaintext') { highlighted = { children: [], type: 'root' }; } else highlighted = lowlight.highlight(language, text); } catch (error) { const languageName = language ?? 'unknown'; warning = language && lowlight.registered(language) ? { error, kind: 'highlight', language: languageName } : { kind: 'missing-language', language: languageName }; highlighted = { children: [], type: 'root' }; } const decorations: CodeBlockDecoration[] = []; const attributesByClass = new Map< string, CodeBlockDecoration['attributes'] >(); const singleLeaf = leafLengths.length <= 1; const textPath = Object.freeze([...blockPath, 0]); const leafPaths = singleLeaf ? [textPath] : leafLengths.map((_, index) => Object.freeze([...blockPath, index])); const previousTokens = singleLeaf && (previous?.leafLengths.length ?? 0) <= 1 ? (previous?.decorations ?? []) : []; let retainedPrefix = 0; let matchingPrefix = singleLeaf; let start = 0; let leafIndex = 0; let leafStart = 0; for (const token of parseNodes(highlighted.children)) { const end = start + token.text.length; if (end > start && token.classes.length > 0) { const className = token.classes.join(' '); let attributes = attributesByClass.get(className); if (!attributes) { attributes = previous?.attributes.get(className) ?? Object.freeze({ className, 'data-code-block-syntax': '' }); attributesByClass.set(className, attributes); } if (singleLeaf) { const before = previousTokens[decorations.length]; if ( matchingPrefix && before && before.attributes === attributes && before.range.anchor.offset === start && before.range.focus.offset === end && PathApi.equals(before.range.anchor.path, textPath) ) { decorations.push(before); retainedPrefix += 1; } else { matchingPrefix = false; decorations.push({ attributes, key: '', range: { anchor: { offset: start, path: textPath }, focus: { offset: end, path: textPath }, }, }); } } else { while ( leafIndex < leafLengths.length - 1 && leafStart + leafLengths[leafIndex] <= start ) { leafStart += leafLengths[leafIndex]; leafIndex += 1; } let cursor = start; let spanLeaf = leafIndex; let spanLeafStart = leafStart; while (cursor < end && spanLeaf < leafLengths.length) { const spanLeafEnd = spanLeafStart + leafLengths[spanLeaf]; const sliceEnd = Math.min(end, spanLeafEnd); if (sliceEnd > cursor) { const path = leafPaths[spanLeaf]; decorations.push({ attributes, key: '', range: { anchor: { offset: cursor - spanLeafStart, path }, focus: { offset: sliceEnd - spanLeafStart, path }, }, }); } cursor = sliceEnd; if (cursor >= spanLeafEnd) { spanLeafStart = spanLeafEnd; spanLeaf += 1; } } } } start = end; } const delta = text.length - (previous?.text.length ?? 0); let beforeEnd = previousTokens.length; let afterEnd = decorations.length; if (singleLeaf) { while (beforeEnd > retainedPrefix && afterEnd > retainedPrefix) { const before = previousTokens[beforeEnd - 1]; const after = decorations[afterEnd - 1]; if ( before.attributes !== after.attributes || before.range.anchor.offset + delta !== after.range.anchor.offset || before.range.focus.offset + delta !== after.range.focus.offset ) { break; } decorations[afterEnd - 1] = delta === 0 && PathApi.equals(before.range.anchor.path, textPath) ? before : { ...after, key: before.key }; beforeEnd -= 1; afterEnd -= 1; } } for (let index = retainedPrefix; index < afterEnd; index++) { decorations[index] = { ...decorations[index], key: `${blockKey}:${nextSyntaxKey}`, }; nextSyntaxKey += 1; } for (let index = retainedPrefix; index < decorations.length; index++) { const decoration = decorations[index]; if (Object.isFrozen(decoration)) continue; Object.freeze(decoration.range.anchor); Object.freeze(decoration.range.focus); Object.freeze(decoration.range); Object.freeze(decoration); } Object.freeze(decorations); const cache = { attributes: attributesByClass, decorations, language, leafLengths, lowlight, text, }; if (blockKey) blockDecorations.set(blockKey, cache); decorationsByBlock.set(block, cache); if (warning?.kind === 'highlight') { editor .plugin(DebugPlugin) .api.warn( `Could not highlight with Highlight.js for language "${warning.language}". Falling back to plaintext`, 'CODE_HIGHLIGHT', warning.error ); } else if (warning) { editor .plugin(DebugPlugin) .api.warn( `Language "${warning.language}" is not registered. Falling back to plaintext` ); } return decorations; }, }, on: { commit({ commit }) { if (blockDecorations.size === 0) return; const structure = commit.changed.hasAny('structure') || commit.changed.hasAny('replace'); if (!structure && !commit.changed.hasAny('properties')) return; const codeBlockType = editor.plugin(BaseCodeBlockPlugin).schema.type; const keys = new Set([ ...commit.changed.nodeKeysAll('node'), ...(structure ? commit.changed.nodeKeysAll('presence') : []), ]); for (const key of keys) { if (!blockDecorations.has(key)) continue; const entry = editor.read.nodes.get(key); if (!entry || !ElementApi.isElementType(entry[0], codeBlockType)) { blockDecorations.delete(key); } } }, }, }; }); export type CodeBlockDefinition = DefinitionOf; export type CodeHighlightDefinition = DefinitionOf< typeof BaseCodeHighlightPlugin >;