Skip to content

Open-source, local-first AI agent for real work.

1.7 KB
Raw Blame
import remarkGfm from "remark-gfm";
import remarkParse from "remark-parse";
import { unified } from "unified";
import { describe, expect, it } from "vitest";
import { richRemarkPlugins } from "./rich-syntax";

interface Node {
	type: string;
	value?: string;
	children?: Node[];
}

function mathValues(markdown: string): string[] {
	const processor = unified().use(remarkParse).use(remarkGfm);
	for (const plugin of richRemarkPlugins) processor.use(plugin);
	const values: string[] = [];
	const visit = (node: Node) => {
		if (node.type === "inlineMath" && node.value !== undefined) values.push(node.value);
		node.children?.forEach(visit);
	};
	visit(processor.runSync(processor.parse(markdown)) as Node);
	return values;
}

describe("\\( \\) and \\[ \\] math aliases", () => {
	it("keeps single-line formulas and TeX line breaks", () => {
		expect(mathValues("面积 \\(a^2\\) 平方")).toEqual(["a^2"]);
		expect(mathValues("\\[a \\\\ b\\]")).toEqual(["a \\\\ b"]);
		expect(mathValues("\\(\\)")).toEqual([""]);
	});

	it("parses formulas that span lines instead of crashing or hanging", () => {
		expect(mathValues("\\(a\nb\\)")).toEqual(["a\nb"]);
		expect(mathValues("\\[a\n\\]")).toEqual(["a\n"]);
		// openvetta/open-vetta#107: table-like lines inside a display formula threw
		// "Cannot access index N in a splice buffer of size N" and blanked the session.
		expect(mathValues("\\[| a | b |\n|:--|--:|\n\\]")).toEqual(["| a | b |\n|:--|--:|\n"]);
		expect(() => mathValues("\\[ x\n| a | b |\n|---|---|\n\\]")).not.toThrow();
		expect(() => mathValues("文字 \\(a\n| a | b |\n|---|---|\n| 1 | 2 |\n\\)")).not.toThrow();
	});

	it("leaves unclosed delimiters as text", () => {
		expect(mathValues("\\(a\nb")).toEqual([]);
	});
});