Skip to content

Commit 4791532

Browse files
committed
fix(docx): preserve XML escaping in math equations
1 parent d65e92f commit 4791532

2 files changed

Lines changed: 55 additions & 2 deletions

File tree

‎packages/math-block/src/docx-exporter/docxExporter.test.ts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ import {
1616
TextWriter,
1717
ZipReader,
1818
} from "@zip.js/zip.js";
19-
import { Packer } from "docx";
19+
import { Document, Packer, Paragraph } from "docx";
2020
import { describe, expect, it } from "vite-plus/test";
2121
import xmlFormat from "xml-formatter";
2222

@@ -42,6 +42,57 @@ const prettify = (sourceXml: string) => {
4242
};
4343

4444
describe("docx exporter mappings", () => {
45+
it.each([
46+
["x < 0", "x&lt;0"],
47+
[String.raw`\text{a\&b}`, "a&amp;b"],
48+
[String.raw`\text{<tag>\&amp;}`, "&lt;tag&gt;&amp;amp;"],
49+
])(
50+
"should preserve XML escaping in block and inline math: %s",
51+
async (source, escaped) => {
52+
const exporter = new DOCXExporter(
53+
BlockNoteSchema.create(),
54+
docxDefaultSchemaMappings,
55+
);
56+
const doc = new Document({
57+
sections: [
58+
{
59+
children: [
60+
mathBlockMapping(
61+
{
62+
id: "math",
63+
type: "mathBlock",
64+
props: {},
65+
content: [{ type: "text", text: source, styles: {} }],
66+
},
67+
exporter,
68+
),
69+
new Paragraph({
70+
children: [
71+
inlineMathMapping(
72+
{ type: "math", content: source },
73+
exporter,
74+
),
75+
],
76+
}),
77+
],
78+
},
79+
],
80+
});
81+
const zip = new ZipReader(new BlobReader(await Packer.toBlob(doc)));
82+
try {
83+
const xml = await getZIPEntryContent(
84+
await zip.getEntries(),
85+
"word/document.xml",
86+
);
87+
expect(xml.match(/<m:oMath[ >]/g)).toHaveLength(2);
88+
expect(xml.split(escaped)).toHaveLength(3);
89+
expect(() => xmlFormat(xml)).not.toThrow();
90+
} finally {
91+
await zip.close();
92+
}
93+
},
94+
);
95+
4596
it("should export math as native equations", { timeout: 10000 }, async () => {
4697
// Assembled outside the constructor call as the schema doesn't include
4798
// the math specs - like the default mappings, the math entries just

‎packages/math-block/src/docx-exporter/index.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@ function latexToDocxEquation(
3434
// component around the `m:oMath` root element - unwrap it, or it would
3535
// serialize as an (invalid) `<undefined>` element.
3636
const imported = ImportedXmlComponent.fromXmlString(
37-
mml2omml(mathML.mathML),
37+
// The converter doesn't re-escape decoded text when serializing OMML.
38+
// Preserve KaTeX's XML entities so characters like < and & stay valid XML.
39+
mml2omml(mathML.mathML, { disableDecode: true }),
3840
) as any;
3941
return { equation: imported.root[0] as ImportedXmlComponent };
4042
}

0 commit comments

Comments
 (0)