diff --git a/docs/app/components/Playground.vue b/docs/app/components/Playground.vue index b1fc6145..e5d0d0c7 100644 --- a/docs/app/components/Playground.vue +++ b/docs/app/components/Playground.vue @@ -7,7 +7,7 @@ import binding from '@comark/vue/plugins/binding' import emoji from '@comark/vue/plugins/emoji' import mermaid from '@comark/vue/plugins/mermaid' import jsonRender from '@comark/vue/plugins/json-render' -import footnotes from '@comark/vue/plugins/footnotes' +import footnotes, { Footnote } from '@comark/vue/plugins/footnotes' import punctuation from '@comark/vue/plugins/punctuation' import breaks from '@comark/vue/plugins/breaks' import titleDescription from '@comark/vue/plugins/title-description' @@ -391,7 +391,9 @@ function resetComark(): void { const formattedOutput = ref('') watchEffect(async () => { - formattedOutput.value = document.value ? await renderMarkdown(document.value as any) : '' + formattedOutput.value = document.value + ? await renderMarkdown(document.value as any, { components: { footnotes: Footnote } }) + : '' }) const formattedOutputModel = computed({ diff --git a/docs/content/4.plugins/1.built-in/footnotes.md b/docs/content/4.plugins/1.built-in/footnotes.md index 3ecf388b..045c36b1 100644 --- a/docs/content/4.plugins/1.built-in/footnotes.md +++ b/docs/content/4.plugins/1.built-in/footnotes.md @@ -117,7 +117,7 @@ Define footnotes with `[^label]: content` on its own line: [^qm]: See the photoelectric effect paper, also from 1905. ``` -Definitions can appear anywhere in the document. The plugin removes them from their original position and appends them to the footnotes section at the end. +Definitions can appear anywhere in the document outside code blocks, starting at the beginning of a line. The plugin removes them from their original position and appends them to the footnotes section at the end. ### Complete example diff --git a/packages/comark/src/plugins/footnotes.ts b/packages/comark/src/plugins/footnotes.ts index 3043aa5f..e9e8c03b 100644 --- a/packages/comark/src/plugins/footnotes.ts +++ b/packages/comark/src/plugins/footnotes.ts @@ -1,3 +1,4 @@ +import type { MarkdownExit } from 'markdown-exit/core' import type { Node, ElementNode, ElementNodeAttributes, ConditionalNodeHandler } from 'comark' import { defineComarkPlugin } from 'comark' import { visit } from 'comark/utils' @@ -28,7 +29,37 @@ export interface FootnotesConfig { } // [^label]: content -const FOOTNOTE_DEF_RE = /^\[\^([^\s\]]+)\]:[ \t]?(.*)$/gm +const FOOTNOTE_DEF_RE = /^\[\^([^\s\]]+)\]:[ \t]?(.*)$/ + +/** + * Tokenizes single-line `[^label]: content` definitions as a block rule, so the parser + * never reads them inside code, raw HTML, or other literal blocks. + */ +function markdownItFootnoteDefs(md: MarkdownExit): void { + md.block.ruler.before( + // Before `table` and `reference`, which would read `[^1]: a | b` as a table header or `[^1]: https://…` as a link definition. + 'table', + 'footnote_def', + (state, startLine, _endLine, silent) => { + const start = state.bMarks[startLine]! + state.tShift[startLine]! + // Only at the start of a source line, so definitions in blockquotes, list items, or indented lines stay text. + if (start > 0 && state.src.charCodeAt(start - 1) !== 0x0a /* \n */) return false + if (state.src.charCodeAt(start) !== 0x5b /* [ */ || state.src.charCodeAt(start + 1) !== 0x5e /* ^ */) { + return false + } + const def = FOOTNOTE_DEF_RE.exec(state.src.slice(start, state.eMarks[startLine])) + if (!def) return false + if (silent) return true + + const token = state.push('footnote_def', '', 0) + token.meta = { label: def[1], content: def[2]!.trim() } + token.map = [startLine, startLine + 1] + state.line = startLine + 1 + return true + }, + { alt: ['paragraph', 'reference', 'blockquote'] } + ) +} /** * Labels are author-controlled, so they must not leak raw characters into the @@ -89,13 +120,16 @@ export default defineComarkPlugin((config: FootnotesConfig = {}) => { return { name: 'footnotes', - pre(state) { + markdownItPlugins: [markdownItFootnoteDefs], + markdownItPost(state) { const definitions = new Map() - - state.markdown = state.markdown.replace(FOOTNOTE_DEF_RE, (_match, defLabel: string, content: string) => { - definitions.set(defLabel, content.trim()) - return '' - }) + if (state.tokens.some((token) => token.type === 'footnote_def')) { + state.tokens = state.tokens.filter((token) => { + if (token.type !== 'footnote_def') return true + definitions.set(token.meta.label, token.meta.content) + return false + }) + } // Store on state to avoid mixing definitions across parallel parses state.footnote = definitions @@ -130,26 +164,7 @@ export default defineComarkPlugin((config: FootnotesConfig = {}) => { ] }) - let nodes = state.tree.nodes - - // Remove empty paragraphs left after definition removal - nodes = nodes.filter((node) => { - if (!Array.isArray(node) || node[0] !== 'p') return true - for (let i = 2; i < node.length; i++) { - const child = node[i] - if (typeof child === 'string') { - if ((child as string).trim().length > 0) return true - } else if (Array.isArray(child) && child[0] != null) { - return true - } - } - return false - }) - - if (refIndexMap.size === 0) { - state.tree.nodes = nodes - return - } + if (refIndexMap.size === 0) return const footnoteItems: Node[] = [] @@ -175,9 +190,8 @@ export default defineComarkPlugin((config: FootnotesConfig = {}) => { } sectionChildren.push(['ol', { class: 'footnotes-list' }, ...footnoteItems]) - nodes.push(['section', { class: 'footnotes' }, ...sectionChildren]) - - state.tree.nodes = nodes + // Copy so a cached streaming tree never gains the section. + state.tree.nodes = [...state.tree.nodes, ['section', { class: 'footnotes' }, ...sectionChildren]] }, } }) @@ -204,13 +218,22 @@ export default defineComarkPlugin((config: FootnotesConfig = {}) => { * ``` */ export const Footnote: ConditionalNodeHandler = { + // Only the shapes `post()` emits, so other nodes with these classes render as usual. match: (node) => { - return node[1].class === 'footnotes' || node[1].class === 'footnote-ref' + if (node[1].class === 'footnotes') { + return ( + node[0] === 'section' && node.some((n) => Array.isArray(n) && n[0] === 'ol' && n[1]?.class === 'footnotes-list') + ) + } + if (node[1].class === 'footnote-ref') { + const link = node[2] + return node[0] === 'sup' && Array.isArray(link) && link[0] === 'a' && String(link[1]?.id).startsWith('fnref-') + } + return false }, handler: (node) => { if (node[1].class === 'footnotes') { const ol = node.find((n) => Array.isArray(n) && n[0] === 'ol') as ElementNode - if (!ol) return '' let result = '' for (let i = 2; i < ol.length; i++) { const key = String(((ol[i] as ElementNode)[1] as ElementNodeAttributes)?.id)?.replace('fn-', '') diff --git a/packages/comark/test/footnotes.test.ts b/packages/comark/test/footnotes.test.ts index b68b0daf..e1e2d998 100644 --- a/packages/comark/test/footnotes.test.ts +++ b/packages/comark/test/footnotes.test.ts @@ -222,9 +222,75 @@ describe('footnotes plugin', () => { expect(secondRef).toBeTruthy() expect(secondRef[2]).toBe('[2]') }) + + it('should keep definition-like lines inside fenced code', async () => { + const md = `Text[^1] + +\`\`\`\`md +[^1]: Backtick example +\`\`\` +[^1]: After a shorter fence +\`\`\`\` + +~~~ +[^2]: Tilde example +~~~ + +[^1]: Real note` + + const tree = await parseMarkdown(md, { plugins: [footnotes()] }) + const codes = tree.nodes.filter((n) => Array.isArray(n) && n[0] === 'pre').map((n: any) => n[2][2]) + expect(codes).toEqual(['[^1]: Backtick example\n```\n[^1]: After a shorter fence', '[^2]: Tilde example']) + + const section = tree.nodes.find((n) => Array.isArray(n) && n[0] === 'section') as any[] + const ol = section.find((n: any, i: number) => i >= 2 && Array.isArray(n) && n[0] === 'ol') + expect(ol.slice(2)).toEqual([ + ['li', { id: 'fn-1' }, 'Real note', ' ', ['a', { href: '#fnref-1', class: 'footnote-backref' }, '↩']], + ]) + }) + + it.each([ + ['CRLF line endings', 'Text[^1]\r\n\r\n[^1]: Real note\r\n'], + ['a closer followed by NBSP', 'Text[^1]\n\n~~~\n~~~\u00a0\n[^1]: Example\n~~~\n\n[^1]: Real note'], + ['backticks in a fence info string', 'Text[^1]\n\n```inline```\n\n[^1]: Real note'], + ['lone CR line endings', 'Text[^1]\r\r[^1]: Real note\r'], + ['a fence closed inside a list item', 'Text[^1]\n- ~~~\n code\n ~~~\n[^1]: Real note'], + ['a fence marker inside raw HTML', 'Text[^1]\n\n
\n~~~\n
\n\n[^1]: Real note'], + ['a blockquote right before it', 'Text[^1]\n> quote\n[^1]: Real note'], + ])('should find the definition with %s', async (_name, md) => { + const tree = await parseMarkdown(md, { plugins: [footnotes()] }) + const section = tree.nodes.find((n) => Array.isArray(n) && n[0] === 'section') as any[] + expect(section?.at(-1)?.[2]?.[2]).toBe('Real note') + }) + + it('should find a definition followed by a table delimiter row', async () => { + const tree = await parseMarkdown('Text[^1]\n\n[^1]: Left | right\n--- | ---', { plugins: [footnotes()] }) + const section = tree.nodes.find((n) => Array.isArray(n) && n[0] === 'section') as any[] + expect(section?.at(-1)?.[2]?.[2]).toBe('Left | right') + }) + + it.each([ + ['indented', 'Text[^1]\n\n [^1]: Not a note'], + ['in a blockquote', 'Text[^1]\n\n> [^1]: Not a note'], + ['in a list item', 'Text[^1]\n\n- [^1]: Not a note'], + ])('should keep a definition %s as text', async (_name, md) => { + const tree = await parseMarkdown(md, { plugins: [footnotes()] }) + expect(tree.nodes.some((n) => Array.isArray(n) && n[0] === 'section')).toBe(false) + expect(JSON.stringify(tree.nodes)).toContain(': Not a note') + }) }) describe('footnotes stringify', () => { + it.each([ + 'A ordinary text B', + 'A [ordinary text]{.footnote-ref} B', + '::section{.footnotes}\nhi\n::', + '::section{.footnotes}\n1. item\n::', + ])('should leave non-footnote nodes with footnote classes unchanged: %s', async (md) => { + const doc = await parseMarkdown(md) + expect(await renderMarkdown(doc, { components: { footnotes: Footnote } })).toBe(await renderMarkdown(doc)) + }) + it('should render footnotes back to markdown syntax', async () => { const md = `Hello world[^1]