diff --git a/web/features/notes/model/markdown.ts b/web/features/notes/model/markdown.ts index c1079e311..2d3a307e9 100644 --- a/web/features/notes/model/markdown.ts +++ b/web/features/notes/model/markdown.ts @@ -65,23 +65,43 @@ export function parseNoteMarkdown( prose.push(line) } flush() + const splitInlineMath = (items: unknown[]): unknown[] => + items.flatMap(raw => { + const item = raw as { type: string; text?: string; styles?: Record } + if (item.type !== 'text' || item.styles?.code || !item.text) return [raw] + const out: unknown[] = [] + let cursor = 0 + for (const match of item.text.matchAll(/(? cursor) + out.push({ ...item, text: item.text.slice(cursor, match.index) }) + out.push({ type: 'inlineMath', props: { formula: match[1] } }) + cursor = match.index! + match[0].length + } + if (cursor < item.text.length) out.push({ ...item, text: item.text.slice(cursor) }) + return out + }) + const inlineMath = (blocks: NoteBlock[]) => blocks.forEach(block => { - if (block.type !== 'codeBlock' && Array.isArray(block.content)) { - block.content = block.content.flatMap(raw => { - const item = raw as { type: string; text?: string; styles?: Record } - if (item.type !== 'text' || item.styles?.code || !item.text) return [raw] - const out: unknown[] = [] - let cursor = 0 - for (const match of item.text.matchAll(/(? cursor) - out.push({ ...item, text: item.text.slice(cursor, match.index) }) - out.push({ type: 'inlineMath', props: { formula: match[1] } }) - cursor = match.index! + match[0].length + if (block.type !== 'codeBlock') { + if (Array.isArray(block.content)) { + block.content = splitInlineMath(block.content) + } else if (block.content && typeof block.content === 'object') { + // BlockNote table cells carry their own inline-content arrays. The + // top-level walk never reached them, so formulas inside a table + // stayed literal `$...$` text and rendered as raw LaTeX. + const table = block.content as { + type?: string + rows?: Array<{ cells?: Array<{ content?: unknown }> }> } - if (cursor < item.text.length) out.push({ ...item, text: item.text.slice(cursor) }) - return out - }) + if (table.type === 'tableContent' && Array.isArray(table.rows)) { + for (const row of table.rows) { + for (const cell of row.cells ?? []) { + if (Array.isArray(cell.content)) cell.content = splitInlineMath(cell.content) + } + } + } + } } if (block.children) inlineMath(block.children) }) diff --git a/web/lib/latex-normalize.ts b/web/lib/latex-normalize.ts index b77b11156..bff0d0049 100644 --- a/web/lib/latex-normalize.ts +++ b/web/lib/latex-normalize.ts @@ -41,6 +41,7 @@ const MATH_WORDS = new Set([ "sec", "csc", "log", + "ln", "exp", "lim", "max", @@ -53,7 +54,53 @@ const MATH_WORDS = new Set([ "lcm", "mod", "arg", + "argmax", + "argmin", ]); +// Statistics and linear-algebra names. `Var(X)` and `Cov(X, Y)` are ordinary +// prose to the Latin-word heuristic unless these are known, which used to make +// `escapeStrayDollars` turn `$Var(N)$` back into literal source. Most are also +// English words or keywords ("$52k mean, $48k median", `var x = 1`), so they +// only count when written as a call. +const FUNCTION_NAMES = new Set([ + "var", + "cov", + "corr", + "std", + "sd", + "mean", + "median", + "mode", + "prob", + "pdf", + "cdf", + "pmf", + "mgf", + "rank", + "tr", + "trace", + "span", + "ker", + "deg", +]); + +/** Is every Latin word of at least `minLength` letters in `value` maths? */ +function wordsAreMath( + value: string, + minLength: number, + allow: (word: string) => boolean = () => false, +): boolean { + for (const match of value.matchAll(/[A-Za-z]+/g)) { + const word = match[0]; + if (word.length < minLength) continue; + const name = word.toLowerCase(); + if (MATH_WORDS.has(name) || allow(word)) continue; + const called = /^\s*\(/.test(value.slice(match.index + word.length)); + if (FUNCTION_NAMES.has(name) && called) continue; + return false; + } + return true; +} // --------------------------------------------------------------------------- // masking @@ -208,8 +255,7 @@ function plausibleMathBody(body: string, tight: boolean): boolean { // Latin prose gives itself away with words. `x + y`, `f(x)` and `E = mc` are // all formulas; "5 and the value of " is not. - const words = value.match(/[A-Za-z]{3,}/g) ?? []; - return words.every((word) => MATH_WORDS.has(word.toLowerCase())); + return wordsAreMath(value, 3); } /** @@ -234,11 +280,10 @@ function looksLikePlainMathExpression(value: string): boolean { // Multi-letter runs are variables juxtaposed for multiplication (`AB`, `BCD`) // or named functions — never lowercase words like `npm run dev`. - const words = value.match(/[A-Za-z]{2,}/g) ?? []; - return words.every( - (word) => - MATH_WORDS.has(word.toLowerCase()) || - (word.length <= 4 && word === word.toUpperCase()), + return wordsAreMath( + value, + 2, + (word) => word.length <= 4 && word === word.toUpperCase(), ); } diff --git a/web/tests/latex-normalize.test.ts b/web/tests/latex-normalize.test.ts index efe71cc91..f8fe21213 100644 --- a/web/tests/latex-normalize.test.ts +++ b/web/tests/latex-normalize.test.ts @@ -126,6 +126,13 @@ test("a code span holding code stays code", () => { } }); +test("a statistics name only reads as maths when it is called", () => { + // `var` is a keyword in a page that also has real maths, not Var(X). + const code = "设 $x$ 为变量,代码写成 `var x = 1`。"; + assert.equal(normalizeMathMarkup(code), code); + assert.equal(normalizeMathMarkup("方差 $Var (N)$ 与 $Cov(X, Y)$。"), "方差 $Var (N)$ 与 $Cov(X, Y)$。"); +}); + // --------------------------------------------------------------------------- // backslashes that are not maths // --------------------------------------------------------------------------- @@ -215,6 +222,11 @@ test("currency is escaped so remark-math cannot swallow it", () => { normalizeMathMarkup("It costs $5 and the value of $x$ is 2."), "It costs \\$5 and the value of $x$ is 2.", ); + // Statistics names are English words too: between two prices they are prose. + assert.equal( + normalizeMathMarkup("Salaries: $52k mean, $48k median."), + "Salaries: \\$52k mean, $48k median.", + ); }); test("real formulas survive the same pass", () => { @@ -223,6 +235,9 @@ test("real formulas survive the same pass", () => { "设 $x$ 为变量,$y$ 为常量。", "$\\text{速度} = \\frac{s}{t}$", "已知 $速度 = 路程/时间$ 求解。", + "求 $N$ 的方差 $Var(N)$。", + "> 方差 $Var(N)$ 已知。", + "统计量 $Cov(X,Y)$ 与 $Corr(X,Y)$。", "$$\n\\overline{A+B}=\\bar{A}\\bar{B}\n$$", ]) { assert.equal(normalizeMathMarkup(input), input); @@ -261,6 +276,9 @@ test("routing agrees with what normalisation produces", () => { assert.equal(hasMarkdownMath(input), true, input); assert.notEqual(normalizeMathMarkup(input), input, input); } + // Already-delimited statistics notation must route to KaTeX and survive + // normalisation byte-for-byte. + assert.equal(hasMarkdownMath("求 $N$ 的方差 $Var(N)$。"), true); const shouldNot = [ "价格是 $5 和 $10。", diff --git a/web/tests/notes-model.spec.ts b/web/tests/notes-model.spec.ts index 188425db8..3fa8c2ad2 100644 --- a/web/tests/notes-model.spec.ts +++ b/web/tests/notes-model.spec.ts @@ -24,6 +24,38 @@ describe('notebook migration and generated content', () => { it('keeps unfinished math input as ordinary text', () => { expect(parseNoteMarkdown('$$\nunclosed', parse)[0].type).toBe('paragraph') }) + it('converts inline math inside table cells', () => { + const tableParse = (): NoteBlock[] => [ + { + id: 'table', + type: 'table', + props: {}, + content: { + type: 'tableContent', + rows: [ + { + cells: [ + { + type: 'tableCell', + content: [ + { type: 'text', text: '$P(A\\mid B)=\\dfrac{P(AB)}{P(B)}$', styles: {} }, + ], + }, + ], + }, + ], + }, + }, + ] + const blocks = parseNoteMarkdown('table', tableParse) + const table = blocks[0].content as { + rows: Array<{ cells: Array<{ content: Array<{ type: string; props?: { formula?: string } }> }> }> + } + const cell = table.rows[0].cells[0].content + expect(cell).toHaveLength(1) + expect(cell[0].type).toBe('inlineMath') + expect(cell[0].props?.formula).toBe('P(A\\mid B)=\\dfrac{P(AB)}{P(B)}') + }) it('persists question payloads without the chat quiz provider', () => { const result = resultLearningBlock({ summary: { results: [{ qa_pair: { question: 'Frequency?', correct_answer: 'Hz' } }] },