Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

markdownMath.ts

94 lines3.5 KB

1/// <reference types="mdast-util-to-hast" />
2import type { Root } from "mdast";
3import remarkMath from "remark-math";
4import remarkParse from "remark-parse";
5import remarkGfm from "remark-gfm";
6import { unified } from "unified";
7​
8const mathParser = unified()
9 .use(remarkParse)
10 .use(remarkGfm)
11 .use(remarkMath, { singleDollarTextMath: true })
12 .freeze();
13​
14export function parseMarkdownWithMath(source: string) {
15 return mathParser.parse(source);
17​
18/** Closed, parser-owned formulas with authored source for editors. */
19export function markdownMathRanges(source: string, tree?: Root) {
20 const ranges: Array<{
21 start: number;
22 end: number;
23 source: string;
24 tex: string;
25 display: boolean;
26 inTable: boolean;
27 }> = [];
28 if (!mayContainMath(source)) return ranges;
29 const sourceOffset = source.startsWith("\uFEFF") ? 1 : 0;
30 const visit = (node: Root | Root["children"][number], inTable = false) => {
31 const table = inTable || node.type === "tableCell";
32 if (
33 node.type === "math" ||
34 node.type === "inlineMath" ||
35 (node.type === "code" && node.lang === "math")
36 ) {
37 const position = node.position;
38 const parserStart = position?.start.offset;
39 const parserEnd = position?.end.offset;
40 if (!position || parserStart === undefined || parserEnd === undefined) return;
41 const start = parserStart + sourceOffset;
42 const end = parserEnd + sourceOffset;
43 const authored = source.slice(start, end);
44 if (node.type === "code") {
45 const open = /^[ \t]*(`{3,}|~{3,})/.exec(authored)?.[1];
46 const close = /[\r\n][ \t>]*(`{3,}|~{3,})[ \t\r]*$/.exec(authored)?.[1];
47 if (!open || !close || open[0] !== close[0] || close.length < open.length) return;
48 // An unclosed fence keeps a would-be closer (e.g. indented 4+ spaces) in its value.
49 const valueLines = node.value ? node.value.split(/\r\n|\r|\n/).length : 0;
50 const spanLines = position.end.line - position.start.line + 1;
51 if (spanLines < valueLines + 2) return;
52 }
53 const display = node.type !== "inlineMath" || /^(?:\$\$|\\\[)/.test(authored);
54 ranges.push({ start, end, source: authored, tex: node.value, display, inTable: table });
55 } else if ("children" in node) node.children.forEach((child) => visit(child, table));
56 };
57 visit(tree ?? parseMarkdownWithMath(source));
58 return ranges;
60​
61/** Messages without these characters skip math parsing entirely. */
62function mayContainMath(text: string): boolean {
63 return (
64 mayContainDollarMath(text) ||
65 text.includes("\\(") ||
66 text.includes("\\[") ||
67 /(?:`{3,}|~{3,})[ \t]*math\b/.test(text)
68 );
70​
71/**
72 * A `$` formula needs a closing `$` (or the second `$` of `$$`) after another `$` on its line and
73 * not right after a space (micromark reads a tab as virtual spaces, which still close). So `$skill`
74 * chips and prices skip the parser.
75 */
76function mayContainDollarMath(text: string): boolean {
77 let opened = false;
78 for (let index = 0; index < text.length; index += 1) {
79 const char = text[index];
80 if (char === "\n" || char === "\r") {
81 opened = false;
82 } else if (char === "$") {
83 if (opened && text[index - 1] !== " ") return true;
84 opened = true;
85 }
86 }
87 return false;
89​
90export function mathKind(className: string | undefined): "inline" | "display" | null {
91 if (!className?.includes("language-math")) return null;
92 if (className.includes("math-display")) return "display";
93 return className.includes("math-inline") ? "inline" : null;