SPB Git

Repository Public

mathtext.ts 8.0 KB 99 lines typescript

1/**2 * Formulas as text. Three jobs, all pure:3 *  - stripMathDelims: authors (and models) wrap LaTeX in $…$, $$…$$, \(…\) or \[…\] even where a field is already4 *    LaTeX; KaTeX refuses the delimiters, so they are removed before rendering.5 *  - latexToUnicode: a readable plain-text form of a formula, for places where KaTeX cannot draw (SVG labels,6 *    meta descriptions, sharing images) and as the fallback when KaTeX rejects a formula.7 *  - prettyMath / plainMath: running text that carries ASCII maths (x_t, A^h, σ²_{t−1}) gets real sub- and8 *    superscripts; plainMath also converts $…$ segments.9 */10const SUB: Record<string, string> = {11  "0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄", "5": "₅", "6": "₆", "7": "₇", "8": "₈", "9": "₉", "+": "₊", "-": "₋", "−": "₋", "=": "₌", "(": "₍", ")": "₎",12  a: "ₐ", e: "ₑ", h: "ₕ", i: "ᵢ", j: "ⱼ", k: "ₖ", l: "ₗ", m: "ₘ", n: "ₙ", o: "ₒ", p: "ₚ", r: "ᵣ", s: "ₛ", t: "ₜ", u: "ᵤ", v: "ᵥ", x: "ₓ", β: "ᵦ", γ: "ᵧ", ρ: "ᵨ", φ: "ᵩ", χ: "ᵪ",13};14const SUP: Record<string, string> = {15  "0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴", "5": "⁵", "6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹", "+": "⁺", "-": "⁻", "−": "⁻", "=": "⁼", "(": "⁽", ")": "⁾",16  a: "ᵃ", b: "ᵇ", c: "ᶜ", d: "ᵈ", e: "ᵉ", f: "ᶠ", g: "ᵍ", h: "ʰ", i: "ⁱ", j: "ʲ", k: "ᵏ", l: "ˡ", m: "ᵐ", n: "ⁿ", o: "ᵒ", p: "ᵖ", r: "ʳ", s: "ˢ", t: "ᵗ", u: "ᵘ", v: "ᵛ", w: "ʷ", x: "ˣ", y: "ʸ", z: "ᶻ",17  T: "ᵀ", "⊤": "ᵀ", "*": "*", "′": "′",18};19const script = (s: string, map: Record<string, string>): string | null => {20  let out = "";21  for (const ch of s) { if (ch === " ") continue; const m = map[ch]; if (m === undefined) return null; out += m; }22  return out;23};2425const BB: Record<string, string> = { R: "ℝ", E: "𝔼", N: "ℕ", Z: "ℤ", Q: "ℚ", C: "ℂ", P: "ℙ", D: "𝔻", V: "𝕍", "1": "𝟙" };26const CMD: Record<string, string> = {27  alpha: "α", beta: "β", gamma: "γ", delta: "δ", epsilon: "ε", varepsilon: "ε", zeta: "ζ", eta: "η", theta: "θ", vartheta: "ϑ", iota: "ι", kappa: "κ", lambda: "λ", mu: "μ", nu: "ν",28  xi: "ξ", pi: "π", rho: "ρ", sigma: "σ", tau: "τ", upsilon: "υ", phi: "φ", varphi: "φ", chi: "χ", psi: "ψ", omega: "ω",29  Gamma: "Γ", Delta: "Δ", Theta: "Θ", Lambda: "Λ", Xi: "Ξ", Pi: "Π", Sigma: "Σ", Phi: "Φ", Psi: "Ψ", Omega: "Ω",30  cdot: "·", times: "×", div: "÷", pm: "±", mp: "∓", approx: "≈", simeq: "≃", sim: "∼", equiv: "≡", neq: "≠", ne: "≠", le: "≤", leq: "≤", ge: "≥", geq: "≥", ll: "≪", gg: "≫",31  propto: "∝", infty: "∞", partial: "∂", nabla: "∇", sum: "Σ", prod: "Π", int: "∫", in: "∈", notin: "∉", subset: "⊂", subseteq: "⊆", cup: "∪", cap: "∩", emptyset: "∅",32  to: "→", rightarrow: "→", leftarrow: "←", Rightarrow: "⇒", Leftarrow: "⇐", leftrightarrow: "↔", mapsto: "↦", mid: "|", vert: "|", Vert: "‖", lVert: "‖", rVert: "‖", lvert: "|", rvert: "|",33  langle: "⟨", rangle: "⟩", lfloor: "⌊", rfloor: "⌋", lceil: "⌈", rceil: "⌉", dots: "…", ldots: "…", cdots: "⋯", top: "⊤", perp: "⊥", forall: "∀", exists: "∃", neg: "¬", land: "∧", lor: "∨",34  ell: "ℓ", hbar: "ℏ", circ: "∘", odot: "⊙", oplus: "⊕", otimes: "⊗", star: "⋆", ast: "*", prime: "′", angle: "∠", triangle: "△", setminus: "∖", degree: "°",35  quad: "  ", qquad: "   ", colon: ":", lbrace: "{", rbrace: "}", backslash: "\\",36};37const ACCENT: Record<string, string> = { bar: "̄", overline: "̄", hat: "̂", widehat: "̂", tilde: "̃", widetilde: "̃", dot: "̇", ddot: "̈", vec: "⃗" };3839/** LaTeX without its outer math delimiters. */40export function stripMathDelims(latex: string): string {41  let s = latex.trim();42  for (let n = 0; n < 2; n++) {43    if (s.length >= 4 && s.startsWith("$$") && s.endsWith("$$")) s = s.slice(2, -2).trim();44    else if (s.length >= 4 && s.startsWith("\\[") && s.endsWith("\\]")) s = s.slice(2, -2).trim();45    else if (s.length >= 4 && s.startsWith("\\(") && s.endsWith("\\)")) s = s.slice(2, -2).trim();46    else if (s.length >= 2 && s.startsWith("$") && s.endsWith("$") && !s.slice(1, -1).replace(/\\\$/g, "").includes("$")) s = s.slice(1, -1).trim();47    else break;48  }49  return s;50}5152const wrap = (s: string): string => (/^[\p{L}\p{N}.]+$/u.test(s) || /^\(.*\)$/.test(s) ? s : `(${s})`);5354/** Best-effort readable text for a formula: Greek letters, operators, real sub- and superscripts, a/b fractions. */55export function latexToUnicode(latex: string): string {56  let s = stripMathDelims(latex);57  s = s.replace(/\\(left|right|bigl|bigr|Bigl|Bigr|biggl|biggr|big|Big|bigg|Bigg|displaystyle|textstyle|limits|nolimits)(?![a-zA-Z])/g, "")58    .replace(/\\[,;:>]|\\ |~/g, " ").replace(/\\!/g, "").replace(/\\\\/g, " ; ").replace(/&/g, " ")59    .replace(/\\(begin|end)\{[a-z*]+\}/g, " ");60  // Known symbols first (so that \lVert\mathbf{u} does not become one unknown word), then groups, then what is left.61  s = s.replace(/\\\|/g, "‖").replace(/\\([A-Za-z]+)/g, (m, name: string) => (Object.hasOwn(CMD, name) ? (name === "sum" || name === "prod" || name === "int" ? ` ${CMD[name]}` : CMD[name]) : m));62  for (let pass = 0; pass < 12; pass++) {63    const before = s;64    s = s.replace(/\\mathbb\s*\{([^{}]*)\}/g, (_, x: string) => [...x].map((c) => BB[c] ?? c).join(""))65      .replace(/\\(bar|overline|hat|widehat|tilde|widetilde|dot|ddot|vec)\s*\{([^{}]*)\}/g, (_, a: string, x: string) => ([...x].length === 1 ? x + ACCENT[a] : x))66      .replace(/\\(bar|hat|tilde|dot|ddot|vec)\s*([^\s{\\])/gu, (_, a: string, x: string) => x + ACCENT[a])67      .replace(/\\(?:mathbf|mathrm|mathcal|mathit|mathsf|mathtt|mathscr|mathfrak|boldsymbol|bm|text|textbf|textit|textrm|operatorname\*?|underline|pmb)\s*\{([^{}]*)\}/g, "$1")68      .replace(/\\[dt]?frac\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g, (_, a: string, b: string) => `${wrap(a.trim())}/${wrap(b.trim())} `)69      .replace(/\\sqrt\s*\[([^\]]*)\]\s*\{([^{}]*)\}/g, (_, n: string, x: string) => `${script(n, SUP) ?? n}√${wrap(x.trim())}`)70      .replace(/\\sqrt\s*\{([^{}]*)\}/g, (_, x: string) => `√${wrap(x.trim())}`)71      .replace(/\\binom\s*\{([^{}]*)\}\s*\{([^{}]*)\}/g, "C($1, $2)");72    if (s === before) break;73  }74  s = s.replace(/\\([{}$%&#_])/g, "$1").replace(/\\([A-Za-z]+)\s?/g, (m, name: string) => name + (m.endsWith(" ") ? " " : ""));75  // Scripts: single characters first, then groups (a group that cannot be written stays readable: x_(<t), v_king).76  s = s.replace(/\^\s*([^\s{}^_(])/gu, (m, x: string) => SUP[x] ?? m).replace(/_\s*([^\s{}^_(])/gu, (m, x: string) => SUB[x] ?? m)77    .replace(/\^\s*\{([^{}]*)\}/g, (_, x: string) => script(x, SUP) ?? `^(${x})`).replace(/_\s*\{([^{}]*)\}/g, (_, x: string) => script(x, SUB) ?? `_${/^[\p{L}\p{N}]+$/u.test(x) ? x : `(${x})`}`);78  return s.replace(/[{}]/g, "").replace(/\s+/g, " ").replace(/\(\s+/g, "(").replace(/\s+([),.;:])/g, "$1").trim();79}8081const SUB_RE = /(?<![\p{L}\p{N}_\\])(\p{L}[²³′]?)_(\{[^{}$]{1,14}\}|[\p{L}\p{N}])(?![\p{L}\p{N}_])/gu;82const SUP_RE = /(?<=[\p{L}\p{N})\]₀-₟])\^(\{[^{}$]{1,14}\}|\p{N}{1,3}|\p{L})(?![\p{L}\p{N}^])/gu;83const inner = (x: string): string => (x.startsWith("{") ? x.slice(1, -1) : x);8485/** ASCII maths in running text (r_t, σ²_{t−1}, A^h) with real sub- and superscripts. Anything it cannot write is left as typed. */86export function prettyMath(text: string): string {87  if (!/[_^]/.test(text)) return text;88  return text89    .replace(SUB_RE, (m, base: string, x: string) => { const sub = script(inner(x), SUB); return sub === null ? m : base + sub; })90    .replace(SUP_RE, (m, x: string) => script(inner(x), SUP) ?? m);91}9293/** Plain text of a string that may hold $…$ formulas and ASCII maths: for SVG labels, descriptions, sharing images. */94export function plainMath(text: string): string {95  if (!/[$_^\\]/.test(text)) return text;96  const withMath = text.replace(/\$\$([^$]+)\$\$|\\\(([\s\S]+?)\\\)|(?<!\\)\$(?!\s)((?:\\.|[^$\\])+?)(?<!\s)\$/g, (_, a?: string, b?: string, c?: string) => latexToUnicode(a ?? b ?? c ?? ""));97  return prettyMath(withMath);98}99
Files main
Menu

Theme