feat(layout): lay out accents sized to their letter, cramped lower limits, spaces beside brackets, sums in a script's script, pre-scripts, phantoms, boxes and centred equation arrays, as Word's round 26 shows (#3725)

Word's PDFs of the round-26 probes (word-stops-equations3, word-stops-equation-small2) settle most of the equation stops #3702 left: roots, brackets and braces narrowed to what the PDFs still leave between two sizes, accents over a letter sized to fit it where the MATH table attaches them, superscripts in lower limits cramped, TeX's spaces beside brackets and bars, more symbols' classes, a sum in a script's script, equation arrays without ampersands centred and alignment marks left as they are, boxes struck through, phantoms without their width, ascent or descent, pre-scripts, and small fractions with displayed equations' defaults on. A scripts box now carries its base's first glyph for kerning and its last script's italic correction, which an accent leaves out. A second ampersand in a row still stops, with the sides of a box and transparent phantoms where Word's way isn't settled; word-stops-equations4.ts probes those for the next batch.
This commit is contained in:
Dolan
2026-10-06 21:16:24 +01:00
committed by GitHub
parent 1f172c6939
commit 0c0f1f07b9
13 changed files with 3919 additions and 3051 deletions
+2 -2
View File
File diff suppressed because one or more lines are too long
+22 -14
View File
@@ -1,9 +1,10 @@
/**
* Generates src/layout/cambria-math.ts: what of Cambria Math, the font Word lays out equations in, Word's maths layout
* needs. From the font's own file, which Word installs: each glyph's width and the bottom and top of its ink, the glyphs
* of each character, and of its OpenType MATH table, the constants Word builds equations up by, each glyph's italic
* correction, its kerning beside scripts, the smaller glyphs of scripts (`ssty`), the flatter accents of tall parts
* (`flac`), and the taller and wider glyphs of brackets, roots, sums and braces. Word's PDFs of scripts/layout-probes/word-stops-equations.ts
* needs. From the font's own file, which Word installs: each glyph's width and the bottom, top, left and right of its
* ink, the glyphs of each character, and of its OpenType MATH table, the constants Word builds equations up by, each
* glyph's italic correction, where an accent is centred over it, its kerning beside scripts, the smaller glyphs of
* scripts (`ssty`), the flatter accents of tall parts (`flac`), and the taller and wider glyphs of brackets, roots, sums
* and braces. Word's PDFs of scripts/layout-probes/word-stops-equations.ts
* show it uses them: each glyph Word drew is one of the font's, and where it drew them is where these put them.
*
* Only the characters of the blocks equations are written in are kept: Latin, Greek, the accents, punctuation, letterlike
@@ -143,17 +144,17 @@ const glyphCount = u16(table("maxp") + 4);
const metricCount = u16(table("hhea") + 34);
const advanceOf = (glyph: number): number => u16(table("hmtx") + Math.min(glyph, metricCount - 1) * 4);
// Each glyph's ink, from the glyph's own bounds, which a composite glyph has too
// Each glyph's ink, from the glyph's own bounds, which a composite glyph has too: its bottom and top, and its left and right
const longOffsets = i16(table("head") + 50) === 1;
const inkOf = (glyph: number): readonly [number, number] => {
const inkOf = (glyph: number): readonly [number, number, number, number] => {
const loca = table("loca");
const start = longOffsets ? u32(loca + glyph * 4) : u16(loca + glyph * 2) * 2;
const end = longOffsets ? u32(loca + glyph * 4 + 4) : u16(loca + glyph * 2 + 2) * 2;
if (end === start) {
return [0, 0];
return [0, 0, 0, 0];
}
const glyf = table("glyf") + start;
return [i16(glyf + 4), i16(glyf + 8)];
return [i16(glyf + 4), i16(glyf + 8), i16(glyf + 2), i16(glyf + 6)];
};
// The characters' glyphs, from the cmap's table of all of Unicode (format 12)
@@ -197,6 +198,8 @@ const valuesOf = (offset: number): ReadonlyMap<number, number> => {
return new Map(glyphs.map((glyph, index) => [glyph, i16(offset + 4 + index * 4)]));
};
const italics = valuesOf(glyphInfo + u16(glyphInfo));
// Where an accent is centred over each glyph that says, from its left: for the others, Word centres it on the glyph
const attachments = u16(glyphInfo + 2) === 0 ? new Map<number, number>() : valuesOf(glyphInfo + u16(glyphInfo + 2));
const extended = new Set(u16(glyphInfo + 4) === 0 ? [] : coverage(glyphInfo + u16(glyphInfo + 4)));
type Kern = readonly [readonly number[], readonly number[]];
const kerns = new Map<number, readonly (Kern | undefined)[]>();
@@ -347,10 +350,10 @@ const keptOnly = <T>(map: ReadonlyMap<number, T>): readonly (readonly [number, T
const output = `/**
* What of Cambria Math, the font Word lays out equations in, Word's maths layout needs, in the font's units, 2048 to the
* em: each glyph's width and the bottom and top of its ink, the glyph of each character, and of the font's OpenType MATH
* table, the constants Word builds equations up by, each glyph's italic correction, its kerning beside scripts, the
* smaller glyphs of scripts, the flatter accents of tall parts, and the taller and wider glyphs of brackets, roots, sums
* and braces. Glyphs are by their number in the font.
* em: each glyph's width and the bottom, top, left and right of its ink, the glyph of each character, and of the font's
* OpenType MATH table, the constants Word builds equations up by, each glyph's italic correction, where an accent is
* centred over it, its kerning beside scripts, the smaller glyphs of scripts, the flatter accents of tall parts, and the
* taller and wider glyphs of brackets, roots, sums and braces. Glyphs are by their number in the font.
*
* Generated by scripts/generate-cambria-math.ts from Word's own copy of the font. Do not edit by hand.
*
@@ -373,8 +376,8 @@ export const CHARACTER_RUNS: readonly (readonly [number, number, number])[] = [
${lines(runs.map((run) => list(run)))}
];
/** Each glyph's width, and the bottom and top of its ink: [width, bottom, top] */
export const GLYPH_METRICS: ReadonlyMap<number, readonly [number, number, number]> = new Map([
/** Each glyph's width, and the bottom, top, left and right of its ink: [width, bottom, top, left, right] */
export const GLYPH_METRICS: ReadonlyMap<number, readonly [number, number, number, number, number]> = new Map([
${lines(ordered.map((glyph) => list([glyph, [advanceOf(glyph), ...inkOf(glyph)]])))}
]);
@@ -383,6 +386,11 @@ export const ITALIC_CORRECTIONS: ReadonlyMap<number, number> = new Map([
${lines(keptOnly(italics).map((entry) => list(entry)))}
]);
/** Where an accent is centred over each glyph that says, from the glyph's left; over the others it is centred on the glyph */
export const TOP_ACCENT_ATTACHMENTS: ReadonlyMap<number, number> = new Map([
${lines(keptOnly(attachments).map((entry) => list(entry)))}
]);
/** The glyphs that are shapes grown to a size, such as a tall integral, which scripts are put beside as beside a box */
export const EXTENDED_SHAPES: ReadonlySet<number> = new Set(${list(ordered.filter((glyph) => extended.has(glyph)))});
+11 -6
View File
@@ -112,12 +112,17 @@ whose PDFs Word saved in round 25. Read them with `word-stops-equations.py`, as
rounded down to the half point (EQ30), Word's sizes of roots' signs, brackets, accents and braces, and where it puts
them (EQ31 to EQ37), its spacing of symbols and operators (EQ32, EQ39), bold digits (EQ45), and the maths settings
followed (EQ42 to EQ44). Equations too long for their line (EQ40) and normal text (EQ41) still stop.
`word-stops-equations3.ts` has the cases around those, for the next batch: roots, brackets, accents and braces whose
size Word's PDFs leave between two (EQ46 to EQ49), superscripts in lower limits (EQ50), fractions, sums and functions
beside brackets (EQ51), symbols not yet seen beside letters (EQ52), a sum in a script's script (EQ53), equation arrays
lined up otherwise (EQ54), boxes with a side hidden, phantoms that take less room and pre-scripts (EQ55), in
`word-stops-equations3`, and small fractions with displayed equations' defaults on (EQ56), in
`word-stops-equation-small2`. They have no PDF from Word yet.
`word-stops-equations3.ts` has the cases around those: roots, brackets, accents and braces whose size Word's PDFs left
between two (EQ46 to EQ49), superscripts in lower limits (EQ50), fractions, sums and functions beside brackets (EQ51),
symbols not yet seen beside letters (EQ52), a sum in a script's script (EQ53), equation arrays lined up otherwise
(EQ54), boxes with a side hidden, phantoms that take less room and pre-scripts (EQ55), in `word-stops-equations3`, and
small fractions with displayed equations' defaults on (EQ56), in `word-stops-equation-small2`, whose PDFs Word saved in
round 26. Read them with `word-stops-equations.py`, as its own: they showed the accent over a letter sized to fit the
letter's width where the font attaches it (EQ48), lower limits cramped (EQ50), TeX's spaces beside brackets and bars
(EQ51), the symbols' classes (EQ52), rows of an equation array without ampersands centred and an alignment mark
(`m:aln`) left as it is (EQ54), boxes struck through as plain, phantoms without their width, ascent or descent, and
pre-scripts with the space after scripts before them (EQ55), and small fractions laid out as without them (EQ56). A
second ampersand in a row (EQ54b), which Word spaces by about 0.7 points for a reason not yet known, still stops.
`word-stops-tables3.ts` has what the round-25 table probes left open: long words across cells merged across columns of a
table narrowed to the page (LW9), the text of the cell before two borders of different styles that meet (BT7), thick outer
@@ -0,0 +1,130 @@
// cspell:ignore overbrace sqrt eqArr sPre transp borderBox hideTop hideBot hideLeft hideRight phant varsigma
/**
* Probes of what Word's PDFs of word-stops-equations3.ts left open, where docx/layout still stops at an equation Word
* builds up, or lays one out by a rule seen in one case only:
*
* - EQ57: equation arrays with a second ampersand in a row, which EQ54b showed Word spacing by about 0.7 points, after
* letters whose italic corrections differ (a, 𝑓 and 𝑊 before the ampersand: 50, 60 and 80 units), after digits, with
* a third ampersand, and with an ampersand in one row and none in the other ("an equation array with more than one
* ampersand in a row", "an equation array with an ampersand in some rows and none in others")
* - EQ58: the italic correction of a script's last letter, which Word adds at the end of an equation (EQ11b) and leaves
* out under an accent (EQ48k): before an ordinary atom, an operator and a bracket, and at the end of a numerator, a
* radicand and a bar, and accents over two and three letters, whose size the layout takes as the widest no wider than
* them
* - EQ59: boxes with a side hidden: the left, the right and the bottom around 𝑥, and the top and the bottom around a
* fraction ("a box with its left or right side hidden", "a box with its top or bottom hidden, where the room there
* would show in its line")
* - EQ60: transparent phantoms (`m:transp`) beside atoms that would space their part otherwise than an ordinary atom: a
* plus shown between letters, an equals sign hidden between letters, and a letter before a plus ("a transparent
* phantom whose part the atoms beside it would space otherwise than an ordinary atom")
* - EQ61: pre-scripts (`m:sPre`) of letters, before a fraction, before 𝑦, and before a base with a superscript of its own
* - EQ62: a bracket, a brace, accents and a root whose sizes Word's PDFs still leave between two: brackets around 𝑎^𝑏
* (0.816 to 0.835 of twice its reach), a brace over 𝑐𝑒 (0.981 to 1.021 of its width), hats over 𝑔𝑖 and 𝑏𝑡 (0.979 to 1
* of their width) and a root over 𝜍, whose depth of 423 units puts its sign between two in a line of text (a radicand
* of 1243 to 1260 units)
*
* Each probe is the equation in a line of text, "EQ57a ... after", and on a line of its own in `m:oMathPara`, between a
* line above and a line below, as in word-stops-equations3.ts. Calibri 11 on A4 with inch margins; equations in Cambria
* Math 11.
*
* Usage: npm run run-ts -- scripts/layout-probes/stops2/word-stops-equations4.ts [folder]
*/
import { Math as Equation, Paragraph, TextRun } from "docx";
import { latexToMath } from "../../../src/math";
import { type Child, PAGE, group, line, newPage, probe, write } from "./kit";
const name = (prefix: string, index: number): string => `${prefix}${"abcdefghijklmnopqrstuvwxyz"[index]}`;
const equation = (latex: string): Equation => new Equation({ children: latexToMath(latex) });
/** The equation in a line of text, and on a line of its own between lines above and below it */
const both = (probe: string, latex: string): Child[] => [
...group(probe, [new Paragraph({ children: [new TextRun(`${probe} `), equation(latex), new TextRun(" after")] })]),
...group(`${probe}d`, [new Paragraph({ children: [new TextRun("@@PARA@@"), equation(latex)] })]),
];
const CASES: readonly (readonly [string, readonly string[]])[] = [
[
"EQ58",
[
"x_i y",
"x^f y",
"x_i+y",
"(x_i)",
"\\frac{x_i}{2}",
"\\sqrt{x_i}",
"\\overline{x_i}",
"\\hat{x_i}",
"\\hat{ab}",
"\\hat{xy}",
"\\hat{abc}",
],
],
["EQ62", ["\\left( a^{b} \\right)", "\\overbrace{ce}^{n}", "\\hat{gi}", "\\hat{bt}"]],
];
// EQ57, EQ59 to EQ61 and EQ62e: what docx doesn't write, as Office Math markup, in place of a placeholder run
const run = (text: string, properties = ""): string => `<m:r>${properties ? `<m:rPr>${properties}</m:rPr>` : ""}<m:t>${text}</m:t></m:r>`;
const row = (...runs: readonly string[]): string => `<m:e>${runs.join("")}</m:e>`;
const fraction = `<m:f><m:num>${run("a")}</m:num><m:den>${run("b")}</m:den></m:f>`;
const box = (side: string, content: string): string =>
`<m:borderBox><m:borderBoxPr><m:${side} m:val="1"/></m:borderBoxPr>${row(content)}</m:borderBox>`;
const phantom = (properties: string, content: string): string => `<m:phant><m:phantPr>${properties}</m:phantPr>${row(content)}</m:phant>`;
const prescripts = (sub: string, sup: string, base: string): string =>
`<m:sPre><m:sub>${run(sub)}</m:sub><m:sup>${run(sup)}</m:sup>${row(base)}</m:sPre>`;
const RAW: readonly (readonly [string, string])[] = [
["EQ57a", `<m:eqArr>${row(run("f&amp;=g&amp;h"))}${row(run("W&amp;=x&amp;y"))}</m:eqArr>`],
["EQ57b", `<m:eqArr>${row(run("a&amp;=1&amp;c"))}${row(run("dd&amp;=2&amp;f"))}</m:eqArr>`],
["EQ57c", `<m:eqArr>${row(run("a&amp;=b&amp;c&amp;=d"))}${row(run("dd&amp;=e&amp;f&amp;=g"))}</m:eqArr>`],
["EQ57d", `<m:eqArr>${row(run("a&amp;=b"))}${row(run("c=d"))}</m:eqArr>`],
["EQ59a", box("hideLeft", run("x"))],
["EQ59b", box("hideRight", run("x"))],
["EQ59c", box("hideBot", run("x"))],
["EQ59d", box("hideTop", fraction)],
["EQ59e", box("hideBot", fraction)],
["EQ60a", `${run("a")}${phantom('<m:transp m:val="1"/>', run("+"))}${run("b")}`],
["EQ60b", `${run("a")}${phantom('<m:show m:val="0"/><m:transp m:val="1"/>', run("="))}${run("b")}`],
["EQ60c", `${phantom('<m:transp m:val="1"/>', run("a"))}${run("+b")}`],
["EQ61a", prescripts("a", "b", run("x"))],
["EQ61b", prescripts("1", "2", fraction)],
["EQ61c", prescripts("i", "j", run("y"))],
["EQ61d", prescripts("1", "2", `<m:sSup>${row(run("x"))}<m:sup>${run("3")}</m:sup></m:sSup>`)],
["EQ62e", `<m:rad><m:radPr><m:degHide m:val="1"/></m:radPr><m:deg/>${row(run("ς"))}</m:rad>`],
];
const children: Child[] = [
line("EQ above"),
...CASES.flatMap(([prefix, cases]) => [newPage(), ...cases.flatMap((latex, index) => both(name(prefix, index), latex))]),
newPage(),
...RAW.flatMap(([probe]) => [
...group(probe, [new Paragraph({ children: [new TextRun(`${probe} `), new TextRun(`@@RAW_${probe}@@`), new TextRun(" after")] })]),
...group(`${probe}d`, [new Paragraph({ children: [new TextRun(`@@RAWPARA_${probe}@@`)] })]),
]),
...probe("EQ end", []),
];
const MATHPARA = (xml: string): string => `<m:oMathPara>${xml}</m:oMathPara>`;
const mathPara = (parts: Map<string, string>): void => {
const text = parts.get("word/document.xml")!;
parts.set(
"word/document.xml",
text.replace(/<w:r><w:t xml:space="preserve">@@PARA@@<\/w:t><\/w:r>(<m:oMath>.*?<\/m:oMath>)/g, (_, found: string) =>
MATHPARA(found),
),
);
};
const raw = (parts: Map<string, string>): void => {
const text = parts.get("word/document.xml")!;
parts.set(
"word/document.xml",
RAW.reduce(
(written, [probe, xml]) =>
written
.replace(`<w:r><w:t xml:space="preserve">@@RAW_${probe}@@</w:t></w:r>`, `<m:oMath>${xml}</m:oMath>`)
.replace(`<w:r><w:t xml:space="preserve">@@RAWPARA_${probe}@@</w:t></w:r>`, MATHPARA(`<m:oMath>${xml}</m:oMath>`)),
text,
),
);
};
await write({ name: "word-stops-equations4", sections: [{ properties: PAGE, children }], injections: [mathPara, raw] });
+3255 -2856
View File
File diff suppressed because it is too large Load Diff
+289 -29
View File
@@ -376,6 +376,242 @@ describe("layOutEquation", () => {
}
});
it("should build up what Word's PDFs of word-stops-equations3.docx and word-stops-equation-small2.docx show, as wide and as tall as Word makes it", () => {
// Word's widths and lines, in points, from its PDFs of scripts/layout-probes/stops2/word-stops-equations3.ts, as
// word-stops-equations.py reads them: roots over radicands with a descender (EQ46), brackets around parts between
// two sizes (EQ47), accents over letters and parts (EQ48), braces over and under pairs of letters (EQ49),
// superscripts in lower limits (EQ50), fractions, sums and functions beside brackets and bars (EQ51), symbols
// beside letters (EQ52), a sum and a fraction in a script's script (EQ53), and sums, integrals and fractions with
// small fractions on in the document's maths settings (EQ56), each in a line of text, and displayed (the probe's
// name ending in "d"). EQ49g's line in a line of text, which Word drew with the line below it a grid unit lower
// than EQ49f's, is 0.03 points below Word's pinning, so only its width is checked
const probes: readonly (readonly [string, string, boolean, number | undefined, readonly [number, number] | undefined])[] = [
["EQ46a", "\\sqrt{p}", false, 14.446, [15.637, 16.092]],
["EQ46ad", "\\sqrt{p}", true, undefined, [15.877, 16.332]],
["EQ46b", "\\sqrt{q}", false, 14.438, [15.637, 16.092]],
["EQ46bd", "\\sqrt{q}", true, undefined, [15.877, 16.332]],
["EQ46c", "\\sqrt{\\rho}", false, 14.522, [15.637, 16.092]],
["EQ46cd", "\\sqrt{\\rho}", true, undefined, [15.877, 16.332]],
["EQ46d", "\\sqrt{\\eta}", false, 14.271, [15.637, 16.092]],
["EQ46dd", "\\sqrt{\\eta}", true, undefined, [15.877, 16.332]],
["EQ46e", "\\sqrt{\\mu}", false, 13.565, [13.465, 13.705]],
["EQ46ed", "\\sqrt{\\mu}", true, undefined, [15.865, 16.105]],
["EQ46f", "\\sqrt{\\chi}", false, 13.729, [13.477, 13.932]],
["EQ46fd", "\\sqrt{\\chi}", true, undefined, [15.637, 16.092]],
["EQ46g", "\\sqrt{\\gamma}", false, 13.315, [13.477, 13.932]],
["EQ46gd", "\\sqrt{\\gamma}", true, undefined, [15.637, 16.092]],
["EQ46h", "\\sqrt{y}", false, 14.524, [15.877, 16.332]],
["EQ46hd", "\\sqrt{y}", true, undefined, [15.625, 16.092]],
["EQ47a", "\\left( a^{a^{t}} \\right)", false, 25.34, [15.877, 16.332]],
["EQ47ad", "\\left( a^{a^{t}} \\right)", true, undefined, [15.877, 16.332]],
["EQ47b", "\\left[ a^{a^{t}} \\right]", false, 23.291, [16.117, 16.572]],
["EQ47bd", "\\left[ a^{a^{t}} \\right]", true, undefined, [15.877, 16.332]],
["EQ47c", "\\left\\{ a^{a^{t}} \\right\\}", false, 23.977, [15.877, 16.332]],
["EQ47cd", "\\left\\{ a^{a^{t}} \\right\\}", true, undefined, [15.877, 16.332]],
["EQ47d", "\\left| a^{a^{t}} \\right|", false, 22.421, [16.117, 16.572]],
["EQ47dd", "\\left| a^{a^{t}} \\right|", true, undefined, [15.877, 16.332]],
["EQ47e", "\\left( x^{a^{t}} \\right)", false, 25.405, [15.877, 16.332]],
["EQ47ed", "\\left( x^{a^{t}} \\right)", true, undefined, [15.877, 16.332]],
["EQ47f", "\\left( A^{a^{t}} \\right)", false, 25.8, [16.117, 16.572]],
["EQ47fd", "\\left( A^{a^{t}} \\right)", true, undefined, [15.865, 16.332]],
["EQ48a", "\\hat{d}", false, 6.733, [14.197, 14.652]],
["EQ48ad", "\\hat{d}", true, undefined, [13.717, 14.172]],
["EQ48b", "\\hat{g}", false, 6.929, [13.237, 13.692]],
["EQ48bd", "\\hat{g}", true, undefined, [12.517, 12.972]],
["EQ48c", "\\hat{u}", false, 6.599, [13.237, 13.692]],
["EQ48cd", "\\hat{u}", true, undefined, [12.757, 13.212]],
["EQ48d", "\\hat{T}", false, 6.8, [13.717, 14.172]],
["EQ48dd", "\\hat{T}", true, undefined, [13.477, 13.932]],
["EQ48e", "\\hat{W}", false, 10.89, [13.717, 14.172]],
["EQ48ed", "\\hat{W}", true, undefined, [13.465, 13.705]],
["EQ48f", "\\hat{Z}", false, 6.79, [13.945, 14.185]],
["EQ48fd", "\\hat{Z}", true, undefined, [13.237, 13.692]],
["EQ48g", "\\tilde{d}", false, 6.741, [14.197, 14.652]],
["EQ48gd", "\\tilde{d}", true, undefined, [13.477, 13.932]],
["EQ48h", "\\tilde{t}", false, 4.619, [13.237, 13.692]],
["EQ48hd", "\\tilde{t}", true, undefined, [12.517, 12.972]],
["EQ48id", "\\tilde{I}", true, undefined, [13.237, 13.692]],
["EQ48j", "\\hat{a^2}", false, 11.492, [14.677, 15.132]],
["EQ48jd", "\\hat{a^2}", true, undefined, [14.437, 14.892]],
["EQ48k", "\\hat{H_i}", false, 10.641, [13.717, 14.172]],
["EQ48kd", "\\hat{H_i}", true, undefined, [13.465, 13.932]],
["EQ49a", "\\overbrace{cc}^{n}", false, 10.477, [20.437, 20.892]],
["EQ49ad", "\\overbrace{cc}^{n}", true, undefined, [19.957, 20.412]],
["EQ49b", "\\overbrace{ee}^{n}", false, 11.167, [20.437, 20.892]],
["EQ49bd", "\\overbrace{ee}^{n}", true, undefined, [19.957, 20.412]],
["EQ49c", "\\overbrace{mm}^{n}", false, 18.641, [20.437, 20.892]],
["EQ49cd", "\\overbrace{mm}^{n}", true, undefined, [19.957, 20.412]],
["EQ49d", "\\overbrace{rr}^{n}", false, 10.715, [20.437, 20.892]],
["EQ49dd", "\\overbrace{rr}^{n}", true, undefined, [19.957, 20.412]],
["EQ49e", "\\overbrace{ww}^{n}", false, 16.589, [20.197, 20.652]],
["EQ49ed", "\\overbrace{ww}^{n}", true, undefined, [19.957, 20.412]],
["EQ49f", "\\overbrace{DD}^{n}", false, 15.561, [22.597, 23.052]],
["EQ49fd", "\\overbrace{DD}^{n}", true, undefined, [22.105, 22.345]],
["EQ49g", "\\overbrace{OO}^{n}", false, 15.163, undefined],
["EQ49gd", "\\overbrace{OO}^{n}", true, undefined, [22.117, 22.572]],
["EQ49hd", "\\underbrace{cc}_{n}", true, undefined, [22.345, 22.812]],
["EQ50a", "\\sum_{i^2} x", false, 23.255, [13.237, 13.692]],
["EQ50ad", "\\sum_{i^2} x", true, undefined, [29.557, 30.012]],
["EQ50b", "\\lim_{x^2} y", false, 23.382, [17.317, 17.772]],
["EQ50bd", "\\lim_{x^2} y", true, undefined, [17.317, 17.772]],
["EQ50c", "\\int_{a^2}^{b} x", false, 21.641, [17.797, 18.252]],
["EQ50cd", "\\int_{a^2}^{b} x", true, undefined, [29.785, 30.252]],
["EQ51a", "\\frac{a}{b}(x)", false, 22.352, [17.317, 17.772]],
["EQ51ad", "\\frac{a}{b}(x)", true, undefined, [22.357, 22.812]],
["EQ51b", "(x)\\frac{a}{b}", false, 22.354, [17.557, 18.012]],
["EQ51bd", "(x)\\frac{a}{b}", true, undefined, [22.357, 22.812]],
["EQ51c", "\\frac{a}{b}\\sin x", false, 28.976, [17.317, 17.772]],
["EQ51cd", "\\frac{a}{b}\\sin x", true, undefined, [22.585, 22.825]],
["EQ51d", "(a)\\sin x", false, 39.315, [13.225, 13.465]],
["EQ51dd", "(a)\\sin x", true, undefined, [12.757, 13.212]],
["EQ51e", "\\frac{a}{b}|x|", false, 20.187, [17.317, 17.772]],
["EQ51ed", "\\frac{a}{b}|x|", true, undefined, [22.585, 22.825]],
["EQ51f", "\\frac{a}{b}\\sum_i a_i", false, 29.399, [17.545, 17.785]],
["EQ51fd", "\\frac{a}{b}\\sum_i a_i", true, undefined, [29.077, 29.532]],
["EQ51g", "(a)\\sum_i a_i", false, 39.746, [13.237, 13.692]],
["EQ51gd", "(a)\\sum_i a_i", true, undefined, [29.065, 29.532]],
["EQ52a", "a\\lor b", false, 23.954, [13.237, 13.692]],
["EQ52ad", "a\\lor b", true, undefined, [12.517, 12.972]],
["EQ52b", "a\\otimes b", false, 28.414, [13.237, 13.692]],
["EQ52bd", "a\\otimes b", true, undefined, [12.757, 13.212]],
["EQ52c", "A\\subseteq B", false, 28.926, [13.237, 13.692]],
["EQ52cd", "A\\subseteq B", true, undefined, [12.517, 12.972]],
["EQ52d", "A\\supset B", false, 28.928, [13.237, 13.692]],
["EQ52dd", "A\\supset B", true, undefined, [12.757, 13.212]],
["EQ52e", "a\\notin B", false, 27.078, [13.237, 13.692]],
["EQ52ed", "a\\notin B", true, undefined, [12.517, 12.972]],
["EQ52f", "\\exists x", false, 12.65, [13.237, 13.692]],
["EQ52fd", "\\exists x", true, undefined, [12.757, 13.212]],
["EQ52g", "a\\Leftrightarrow b", false, 30.083, [13.237, 13.692]],
["EQ52gd", "a\\Leftrightarrow b", true, undefined, [12.517, 12.972]],
["EQ52h", "a\\leftarrow b", false, 27.907, [13.237, 13.692]],
["EQ52hd", "a\\leftarrow b", true, undefined, [12.757, 13.212]],
["EQ52i", "f\\circ g", false, 23.067, [13.225, 13.692]],
["EQ52id", "f\\circ g", true, undefined, [12.745, 13.212]],
["EQ52j", "a\\cdots b", false, 25.666, [12.997, 13.452]],
["EQ52jd", "a\\cdots b", true, undefined, [12.757, 13.212]],
["EQ52k", "\\lfloor x\\rfloor", false, 13.906, [13.237, 13.692]],
["EQ52kd", "\\lfloor x\\rfloor", true, undefined, [12.757, 13.212]],
["EQ52l", "a\\Longrightarrow b", false, 31.664, [12.997, 13.452]],
["EQ52ld", "a\\Longrightarrow b", true, undefined, [12.757, 13.212]],
["EQ52m", "a\\setminus b", false, 23.564, [13.237, 13.692]],
["EQ52md", "a\\setminus b", true, undefined, [12.745, 12.985]],
["EQ52n", "a\\propto b", false, 26.42, [13.225, 13.465]],
["EQ52nd", "a\\propto b", true, undefined, [12.745, 13.212]],
["EQ53a", "x^{y^{\\sum a}}", false, 22.964, [16.117, 16.572]],
["EQ53ad", "x^{y^{\\sum a}}", true, undefined, [15.637, 16.092]],
["EQ53b", "x^{y^{\\frac{a}{b}}}", false, 17.278, [19.717, 20.172]],
["EQ53bd", "x^{y^{\\frac{a}{b}}}", true, undefined, [19.465, 19.932]],
["EQ56a", "\\sum_{i=1}^{n} i", false, 26.997, [13.237, 13.692]],
["EQ56ad", "\\sum_{i=1}^{n} i", true, undefined, [35.797, 36.252]],
["EQ56b", "\\int_0^1 x", false, 19.111, [17.557, 18.012]],
["EQ56bd", "\\int_0^1 x", true, undefined, [29.557, 30.012]],
["EQ56c", "\\frac{a}{b}", false, 5.2, [17.317, 17.772]],
["EQ56cd", "\\frac{a}{b}", true, undefined, [22.345, 22.812]],
];
for (const [name, latex, display, width, line] of probes) {
const box = laidOut(latex, display);
expect(box, name).to.be.an("object");
if (line !== undefined) {
expect(lineOf(box as EquationBox, display), `${name}'s line`).to.be.within(line[0] - 1e-6, line[1] + 1e-6);
}
if (width !== undefined) {
expect((box as EquationBox).width, `${name}'s width`).to.be.closeTo(width, 0.03);
}
}
// Equation arrays, boxes, phantoms and pre-scripts (EQ54, EQ55), which docx doesn't write from LaTeX
const row = (...parts: readonly (string | object)[]): object => ({ "m:e": equation(...parts) });
const boxed = (side: string, ...parts: readonly string[]): object => ({
"m:borderBox": [{ "m:borderBoxPr": [property(side, "1")] }, row(...parts)],
});
const phantom = (...properties: readonly object[]): object => ({ "m:phant": [{ "m:phantPr": properties }, row("x")] });
const built: readonly (readonly [string, boolean, readonly object[], number | undefined, readonly [number, number]])[] = [
["EQ54a", false, [{ "m:eqArr": [row("a=b"), row("c=d")] }], 26.906, [22.117, 22.572]],
["EQ54ad", true, [{ "m:eqArr": [row("a=b"), row("c=d")] }], undefined, [21.877, 22.332]],
[
"EQ54c",
false,
[{ "m:eqArr": [row("a", run("=b", { "m:aln": {} })), row("cc", run("=d", { "m:aln": {} }))] }],
31.531,
[22.117, 22.572],
],
[
"EQ54cd",
true,
[{ "m:eqArr": [row("a", run("=b", { "m:aln": {} })), row("cc", run("=d", { "m:aln": {} }))] }],
undefined,
[22.117, 22.572],
],
["EQ55a", false, [boxed("m:hideTop", "x")], 11.331, [12.997, 13.452]],
["EQ55ad", true, [boxed("m:hideTop", "x")], undefined, [12.997, 13.452]],
["EQ55b", false, [boxed("m:strikeH", "x")], 11.333, [13.237, 13.692]],
["EQ55bd", true, [boxed("m:strikeH", "x")], undefined, [12.757, 13.212]],
["EQ55c", false, [phantom(property("m:show", "0"), property("m:zeroWid", "1")), ...equation("y")], 6.352, [13.237, 13.692]],
["EQ55cd", true, [phantom(property("m:show", "0"), property("m:zeroWid", "1")), ...equation("y")], undefined, [12.757, 13.212]],
[
"EQ55d",
false,
[{ "m:phant": [{ "m:phantPr": [property("m:show", "0"), property("m:zeroAsc", "1")] }, row("A")] }, ...equation("y")],
13.428,
[13.237, 13.692],
],
[
"EQ55dd",
true,
[{ "m:phant": [{ "m:phantPr": [property("m:show", "0"), property("m:zeroAsc", "1")] }, row("A")] }, ...equation("y")],
undefined,
[12.517, 12.972],
],
[
"EQ55e",
false,
[{ "m:phant": [{ "m:phantPr": [property("m:show", "0"), property("m:zeroDesc", "1")] }, row("g")] }, ...equation("y")],
13.275,
[13.237, 13.692],
],
[
"EQ55f",
false,
[{ "m:phant": [{ "m:phantPr": [property("m:transp", "1")] }, row("+")] }, ...equation("y")],
14.567,
[13.225, 13.465],
],
[
"EQ55fd",
true,
[{ "m:phant": [{ "m:phantPr": [property("m:transp", "1")] }, row("+")] }, ...equation("y")],
undefined,
[12.745, 12.985],
],
["EQ55g", false, [{ "m:sPre": [{ "m:sub": equation("1") }, { "m:sup": equation("2") }, row("x")] }], 11.289, [13.717, 14.172]],
[
"EQ55gd",
true,
[{ "m:sPre": [{ "m:sub": equation("1") }, { "m:sup": equation("2") }, row("x")] }],
undefined,
[12.985, 13.452],
],
];
for (const [name, display, parts, width, [low, high]] of built) {
const box = layOutEquation(equation(...parts), 11, display);
expect(box, name).to.be.an("object");
expect(lineOf(box as EquationBox, display), `${name}'s line`).to.be.within(low - 1e-6, high + 1e-6);
if (width !== undefined) {
expect((box as EquationBox).width, `${name}'s width`).to.be.closeTo(width, 0.03);
}
}
// A phantom without its ascent or descent is as tall or deep as nothing (EQ55d, EQ55e)
const fraction = { "m:f": [{ "m:num": equation("a") }, { "m:den": equation("b") }] };
const without = (name: string): EquationBox =>
layOutEquation(equation({ "m:phant": [{ "m:phantPr": [property(name, "1")] }, row(fraction)] }), 11, true) as EquationBox;
const plain = layOutEquation(equation("x"), 11, true) as EquationBox;
const whole = layOutEquation(equation(fraction), 11, true) as EquationBox;
expect(without("m:zeroAsc").ascent).to.equal(plain.ascent).and.to.be.lessThan(whole.ascent);
expect(without("m:zeroDesc").descent).to.equal(plain.descent).and.to.be.lessThan(whole.descent);
// Pre-scripts before a base that isn't a glyph
expect(widthOf({ "m:sPre": [{ "m:sub": equation("1") }, { "m:sup": equation("2") }, row(fraction)] })).to.be.a("number");
});
it("should space operators next to each other as Word does, and full stops, italic signs and runs of another size", () => {
// Word's widths, in points (`word-stops-equations.docx` EQ20 to EQ24): no space beside an operator before a
// relation (EQ20a), the rest as TeX spaces them; a full stop as punctuation but between digits (EQ21); an italic
@@ -465,9 +701,9 @@ describe("layOutEquation", () => {
it("should say why an equation Word builds up, or spaces or formats in a way not yet followed, can't be laid out", () => {
const empty = "a part of an equation with nothing in it";
expect(widthOf({ "m:f": [] })).to.equal(empty);
expect(widthOf({ "m:sPre": [{ "m:sub": equation("1") }, { "m:sup": equation("2") }, { "m:e": equation("x") }] })).to.equal(
BUILT_UP,
);
expect(widthOf({ "m:box": [{ "m:e": equation("x") }] })).to.equal(BUILT_UP);
expect(widthOf({ "m:acc": [{ "m:e": [] }] })).to.equal(empty);
expect(widthOf({ "m:sPre": [{ "m:sub": [] }, { "m:sup": equation("2") }, { "m:e": equation("x") }] })).to.equal(empty);
expect(widthOf({ "m:sSup": [{ "m:sup": equation("2") }] })).to.equal(empty);
expect(widthOf({ "m:m": [] })).to.equal(empty);
expect(widthOf({ "m:m": [{ "m:mr": [] }] })).to.equal(empty);
@@ -475,8 +711,8 @@ describe("layOutEquation", () => {
// symbols Word has seen only next to themselves
expect(widthOf("\u2212+a")).to.be.a("number");
expect(widthOf("a\u2192\u2192b")).to.be.a("number");
expect(widthOf("a\u2297b")).to.equal("an equation with a symbol Word hasn't been seen to space");
expect(widthOf("\u2297\u2297")).to.be.a("number");
expect(widthOf("a\u2a01b")).to.equal("an equation with a symbol Word hasn't been seen to space");
expect(widthOf("\u2a01\u2a01")).to.be.a("number");
expect(widthOf("\u2603")).to.equal("a character in an equation Cambria Math doesn't have");
expect(widthOf({ "m:r": [{ "w:rPr": [{ "w:i": {} }] }, { "m:t": ["x"] }] })).to.equal(
"an equation whose text has formatting of its own",
@@ -506,24 +742,16 @@ describe("layOutEquation", () => {
});
expect(widthOf(fraction("skw"))).to.equal("a skewed or linear fraction");
expect(widthOf(fraction("noBar"))).to.be.a("number");
// A superscript in a lower limit, which TeX cramps
const lower = "a superscript in a lower limit, which Word hasn't been seen to cramp or not";
expect(laidOut("\\sum_{i^2} x")).to.equal(lower);
expect(laidOut("\\lim_{x^2} y")).to.equal(lower);
// A superscript in a lower limit, which Word cramps as TeX does (`word-stops-equations3.docx` EQ50)
expect(laidOut("\\sum_{\\frac{1}{i^2}} x", true)).to.be.an("object");
// Spaces beside a fraction, a sum or a function Word hasn't been seen to put or not, as before a bracket
expect(laidOut("\\frac{a}{b}(x)")).to.equal(
"an equation with a fraction, a sum or a function beside a bracket or bar, which Word spaces in a way not yet followed",
);
expect(laidOut("=\\frac{a}{b}")).to.be.an("object");
// Sums Word hasn't been seen to grow, or put in a script's script, or a character without sizes for a displayed one
// Sums Word hasn't been seen to grow, or a character without sizes for a displayed one
const nary = (...properties: readonly object[]): object => ({
"m:nary": [{ "m:naryPr": properties }, { "m:sub": equation("i") }, { "m:sup": equation("n") }, { "m:e": equation("x") }],
});
expect(widthOf(nary(property("m:chr", "\u2211"), property("m:grow", "1")))).to.equal(BUILT_UP);
expect(widthOf(nary(property("m:limLoc", "other")))).to.equal(BUILT_UP);
expect(layOutEquation(equation(nary(property("m:chr", "x"))), 11, true)).to.equal(BUILT_UP);
expect(laidOut("x^{y^{\\sum a}}")).to.equal(BUILT_UP);
expect(widthOf(nary(property("m:chr", "\u2211")))).to.be.a("number");
expect(widthOf(nary())).to.be.a("number");
// Brackets Word hasn't been seen to keep from growing, shape, or grow when angled, and brackets taller than any
@@ -540,8 +768,9 @@ describe("layOutEquation", () => {
);
const tall = (count: number): object => (count === 0 ? equation("x")[0] : fraction("bar", tall(count - 1)));
expect(layOutEquation(equation(brackets([], tall(9))), 11, true)).to.equal("brackets taller than Cambria Math's tallest");
// A part between two sizes of a bracket, as Word's PDFs leave it
expect(laidOut("\\left( x^{a^{t}} \\right)")).to.equal("brackets whose size Word's PDFs leave between two");
// A part between two sizes of a bracket, as Word's PDFs leave it, within 0.816 and 0.835 of twice its reach
expect(laidOut("\\left( a^{b} \\right)")).to.equal("brackets whose size Word's PDFs leave between two");
expect(laidOut("\\left( a^{a^{t}} \\right)")).to.be.an("object");
// A matrix spaced or lined up otherwise
const matrix = (properties: readonly object[]): object => ({
"m:m": [{ "m:mPr": properties }, { "m:mr": [{ "m:e": equation("a") }] }],
@@ -557,7 +786,11 @@ describe("layOutEquation", () => {
true,
),
).to.equal("a root taller than Cambria Math's tallest root sign");
expect(laidOut("\\sqrt{p}")).to.equal("a root whose sign's size Word's PDFs leave between two");
// A radicand whose depth, 423 units for 𝜍, puts its sign between two sizes in a line of text, as Word's PDFs leave it,
// and not displayed, where the gap above it is larger
expect(laidOut("\\sqrt{\\varsigma}")).to.equal("a root whose sign's size Word's PDFs leave between two");
expect(laidOut("\\sqrt{\\varsigma}", true)).to.be.an("object");
expect(laidOut("\\sqrt{p}")).to.be.an("object");
// A brace or accent between two of its sizes, as Word's PDFs leave it, a character without sizes, and an arrow over a
// part too narrow for it made of its parts
const brace = (character: string | undefined, ...parts: readonly (string | object)[]): object => ({
@@ -566,22 +799,46 @@ describe("layOutEquation", () => {
{ "m:e": equation(...parts) },
],
});
expect(widthOf(brace(undefined, "abc"))).to.equal("a brace whose size Word's PDFs leave between two");
expect(widthOf({ "m:acc": [{ "m:e": equation("d") }] })).to.equal("an accent whose size Word's PDFs leave between two");
expect(widthOf(brace(undefined, "ce"))).to.equal("a brace whose size Word's PDFs leave between two");
expect(widthOf(brace(undefined, "abc"))).to.be.a("number");
// An accent over more than one glyph, between 0.979 and 1 of their width (𝑐𝑐, 1949 units with 𝑐's italic correction,
// under the fourth size of a hat, 1936), but not over one glyph, whose accent fits it or not
expect(widthOf({ "m:acc": [{ "m:e": equation("cc") }] })).to.equal("an accent whose size Word's PDFs leave between two");
expect(widthOf({ "m:acc": [{ "m:e": equation("d") }] })).to.be.a("number");
expect(widthOf(brace("x", "a+b+c"))).to.equal("a character grown over or under a part that Cambria Math has no sizes of");
expect(widthOf(brace("\u2192", "ei"))).to.equal(
"a character grown over or under a part narrower than the character made of its parts",
);
expect(widthOf(brace("\u2192", "xi"))).to.be.a("number");
// A box with a side hidden, a phantom that takes less than its part's room, and an equation array lined up otherwise
const box = { "m:borderBox": [{ "m:borderBoxPr": [property("m:hideTop", "1")] }, { "m:e": equation("x") }] };
expect(widthOf(box)).to.equal("a box with a side hidden or struck through");
const phantom = { "m:phant": [{ "m:phantPr": [property("m:zeroWid", "1")] }, { "m:e": equation("x") }] };
expect(widthOf(phantom)).to.equal("a phantom that takes less than its part's room");
// A box with its left or right side hidden, whose room there Word hasn't been seen to keep or not, and one with its top
// or bottom hidden where the room there would decide the line: not over 𝑥 with the top hidden, as Word showed
// (`word-stops-equations3.docx` EQ55a), but over a fraction, and under 𝑥, whose box reaches below the line
const box = (side: string, ...parts: readonly (string | object)[]): object => ({
"m:borderBox": [{ "m:borderBoxPr": [property(side, "1")] }, { "m:e": equation(...parts) }],
});
expect(widthOf(box("m:hideLeft", "x"))).to.equal("a box with its left or right side hidden");
expect(widthOf(box("m:hideRight", "x"))).to.equal("a box with its left or right side hidden");
const hidden = "a box with its top or bottom hidden, where the room there would show in its line";
expect(widthOf(box("m:hideTop", "x"))).to.be.a("number");
expect(widthOf(box("m:hideTop", fraction("bar")))).to.equal(hidden);
expect(widthOf(box("m:hideBot", "x"))).to.equal(hidden);
expect(widthOf(box("m:strikeV", "x"))).to.equal(widthOf(box("m:hideTop", "x")));
expect(laidOut("x^{\\boxed{y}}")).to.be.an("object");
// An accent over a digit, which the MATH table attaches no accent to, is centred on it
expect(laidOut("\\hat{1}")).to.be.an("object");
// A transparent phantom whose part the atoms beside it would space otherwise than an ordinary atom
const phantom = (...parts: readonly (string | object)[]): object => ({
"m:phant": [{ "m:phantPr": [property("m:transp", "1")] }, { "m:e": equation(...parts) }],
});
expect(widthOf("a", phantom("+"), "b")).to.equal(
"a transparent phantom whose part the atoms beside it would space otherwise than an ordinary atom",
);
expect(widthOf("a", phantom("x"), "b")).to.equal(widthOf("axb"));
expect(widthOf(phantom("+"), "y")).to.equal(widthOf("+y"));
// Equation arrays lined up otherwise: spaced at a second ampersand, or with ampersands in some rows only
const array = (properties: readonly object[], ...rows: readonly (readonly (string | object)[])[]): object => ({
"m:eqArr": [{ "m:eqArrPr": properties }, ...rows.map((row) => ({ "m:e": equation(...row) }))],
});
const otherwise = "an equation array lined up in a way not yet followed";
expect(widthOf(array([property("m:baseJc", "top")], ["a&=b"]))).to.equal(
"an equation array spaced or lined up in a way not yet followed",
);
@@ -591,9 +848,12 @@ describe("layOutEquation", () => {
expect(widthOf(array([property("m:rSp", "4")], ["a&=b"]))).to.equal(
"an equation array spaced or lined up in a way not yet followed",
);
expect(widthOf(array([], ["a=b"]))).to.equal(otherwise);
expect(widthOf(array([], ["a&=b&c"]))).to.equal(otherwise);
expect(widthOf(array([], [run("a", { "m:aln": {} }), "&=b"]))).to.equal(otherwise);
expect(widthOf(array([], ["a&=b&c"]))).to.equal(
"an equation array with more than one ampersand in a row, which Word spaces in a way not yet followed",
);
expect(widthOf(array([], ["a&=b"], ["c=d"]))).to.equal("an equation array with an ampersand in some rows and none in others");
expect(widthOf(array([], ["a=b"], ["cc=d"]))).to.equal(widthOf("cc=d"));
expect(widthOf(array([], [run("a", { "m:aln": {} }), "&=b"]))).to.equal(widthOf(array([], ["a&=b"])));
expect(widthOf(array([]))).to.equal("a part of an equation with nothing in it");
});
+196 -123
View File
@@ -4,10 +4,9 @@
* with its italic correction after it and the spaces TeX puts between atoms; and fractions, scripts, roots, sums,
* brackets, matrices, accents, bars, functions, limits, braces, boxes, equation arrays and phantoms built up by the
* table's constants, each part as tall as its ink. Word's PDFs of scripts/layout-probes/word-equations.ts,
* word-equations2.ts, word-stops-equations.ts and word-stops-equations2.ts showed where Word draws each glyph, to within
* its grid of 1/300 inch, and how tall it makes the line: as tall as the ink of the
* equation, with Cambria Math's line gap (300 of its 2048 units) above it, or as a line of Cambria Math, whichever is the
* taller.
* word-equations2.ts, word-stops-equations.ts, word-stops-equations2.ts and word-stops-equations3.ts showed where Word
* draws each glyph, to within its grid of 1/300 inch, and how tall it makes the line: as tall as the ink of the equation,
* with Cambria Math's line gap (300 of its 2048 units) above it, or as a line of Cambria Math, whichever is the taller.
*
* Where Word's PDFs haven't shown how it builds up a part, the layout stops at it, for why.
*
@@ -15,7 +14,7 @@
*/
// cspell:ignore oMath fName funcPr nabla limLoc subHide supHide degHide begChr endChr sepChr mcJc baseJc plcHide noBar ssty
// cspell:ignore limLow limUpp groupChr borderBox eqArr sPre undOvr subSup mcPr mPr dPr naryPr accPr barPr radPr fPr strikeBLTR strikeTLBR
// cspell:ignore phant transp aln
// cspell:ignore phant transp aln hideTop hideBot hideLeft hideRight zeroWid zeroAsc zeroDesc
import { type XmlObject, attributesOf, childrenOf, find, isOff, pointsOf } from "../text-layout";
import {
CHARACTER_RUNS,
@@ -29,6 +28,7 @@ import {
MATH_KERNS,
MIN_CONNECTOR_OVERLAP,
SCRIPT_GLYPHS,
TOP_ACCENT_ATTACHMENTS,
VERTICAL_VARIANTS,
} from "./cambria-math";
@@ -71,8 +71,8 @@ const glyphOf = (character: string): number =>
/** A glyph at a size, in points */
type Glyph = { readonly glyph: number; readonly size: number };
/** A glyph's width, and the bottom and top of its ink, in Cambria Math's units */
const metricsOf = (glyph: number): readonly [number, number, number] => GLYPH_METRICS.get(glyph)!;
/** A glyph's width, and the bottom, top, left and right of its ink, in Cambria Math's units */
const metricsOf = (glyph: number): readonly [number, number, number, number, number] => GLYPH_METRICS.get(glyph)!;
/**
* A glyph's kerning at a corner, beside a script, at a height, in its units: corners 0 to 3 are its top right, top left,
@@ -92,14 +92,12 @@ const kernAt = (glyph: number, corner: number, height: number): number => {
/**
* How a part of an equation is laid out, as TeX's styles are: its level, 0 for a displayed equation, 1 for one in a line
* of text, 2 for a script and 3 for a script's script; whether it is cramped, as a denominator is, with its superscripts
* lower; whether it is in a lower limit, which TeX cramps but Word hasn't been seen to; whether the equation is
* displayed; and the equation's size, in points
* of text, 2 for a script and 3 for a script's script; whether it is cramped, as a denominator or a lower limit is, with
* its superscripts lower; whether the equation is displayed; and the equation's size, in points
*/
type Style = {
readonly level: 0 | 1 | 2 | 3;
readonly cramped: boolean;
readonly lower?: boolean;
readonly display: boolean;
readonly size: number;
/** Where the document puts the limits of sums and integrals that don't say where theirs go */
@@ -126,13 +124,13 @@ const inPoints = (units: number, style: Style): number => (units * sizeOf(style)
const constantOf = (name: keyof typeof MATH_CONSTANTS, style: Style): number => inPoints(MATH_CONSTANTS[name], style);
/**
* The style of a script: a script's, or a script's script's, cramped when its base is, but not for being a subscript, as
* TeX's are (`word-stops-equations2.docx` EQ31c), and in a lower limit when it is one
* The style of a script: a script's, or a script's script's, cramped when its base is, or when it is a lower limit, as
* TeX's are, but not for being a subscript (`word-stops-equations2.docx` EQ31c, `word-stops-equations3.docx` EQ50)
*/
const scriptStyle = (style: Style, lower = false): Style => ({
...style,
level: style.level < 2 ? 2 : 3,
...(style.lower || lower ? { lower: true } : {}),
...(lower ? { cramped: true } : {}),
});
const cramp = (style: Style): Style => ({ ...style, cramped: true });
@@ -175,6 +173,8 @@ type Part = {
readonly space?: boolean;
/** Whether it is an operator that isn't binary where it is: before a relation, after another operator, or at the start */
readonly unary?: boolean;
/** Whether it is the part of a transparent phantom, which Word hasn't been seen to space as it is or as an ordinary atom */
readonly transparent?: boolean;
};
const glyphBox = (glyph: number, size: number): Box => {
@@ -195,21 +195,23 @@ const glyphBox = (glyph: number, size: number): Box => {
// ---- Characters
// The binary operators, relations, brackets, punctuation, bars and slashes Word has been seen to space, set operators,
// logic and arrows among them (`word-equations2.docx` EQ7, `word-stops-equations.docx` EQ20, `word-stops-equations2.docx`
// EQ39)
// logic and arrows among them, and the dots, which it spaces as TeX's inner atom (`word-equations2.docx` EQ7,
// `word-stops-equations.docx` EQ20, `word-stops-equations2.docx` EQ39, `word-stops-equations3.docx` EQ52)
const CLASSES: ReadonlyMap<string, AtomClass> = new Map([
...[..."+−±∓×÷⋅∗∘∪∩∧⊕"].map((character) => [character, "binary"] as const),
...[..."=<>≤≥≠≈≡∼→←⇒∈⊂↦"].map((character) => [character, "relation"] as const),
...[..."([{"].map((character) => [character, "open"] as const),
...[...")]}"].map((character) => [character, "close"] as const),
...[..."+−±∓×÷⋅∗∘∪∩∧∨⊕⊗∖"].map((character) => [character, "binary"] as const),
...[..."=<>≤≥≠≈≡∼→←⇒⇔⟹∈∉⊂⊃⊆↦∝"].map((character) => [character, "relation"] as const),
...[..."([{⌊"].map((character) => [character, "open"] as const),
...[...")]}⌋"].map((character) => [character, "close"] as const),
...[...",;:!?."].map((character) => [character, "punctuation"] as const),
...[..."|/"].map((character) => [character, "fence"] as const),
["⋯", "inner"],
]);
// The signs Word's PDFs showed as ordinary atoms beside letters and operators: the prime, infinity, the partial
// differential sign and nabla, the zero-width space LaTeX's empty base is written as, and "for all" and "not"
// (`word-equations2.docx` EQ7, `word-stops-equations.docx` EQ11e, `word-stops-equations2.docx` EQ39h, EQ39o)
const SIGNS = new Set([..."'\u2032\u221e\u2202\u2207\u200b\u2200\u00ac"]);
// differential sign and nabla, the zero-width space LaTeX's empty base is written as, "for all", "not" and "there exists"
// (`word-equations2.docx` EQ7, `word-stops-equations.docx` EQ11e, `word-stops-equations2.docx` EQ39h, EQ39o,
// `word-stops-equations3.docx` EQ52f)
const SIGNS = new Set([..."'\u2032\u221e\u2202\u2207\u200b\u2200\u00ac\u2203"]);
// Large operators written as text rather than as n-ary operators (`m:nary`), which Word's PDFs showed only next to
// themselves, with no space between them and an integral's italic correction after it (`word-stops-equations.docx` EQ27k)
@@ -382,11 +384,13 @@ const atomsOfRun = (run: unknown, style: Style): readonly Part[] => {
// ---- Rows
// The space TeX puts between two atoms, in eighteenths of an em, by their classes: ordinary, operator (a sum's or a
// function's), binary, relation, opening, closing, punctuation and inner (a fraction's or brackets'), as Word has been
// function's), binary, relation, opening, closing, punctuation and inner (a fraction's, or the dots'), as Word has been
// seen to: none between ordinary atoms, 4 either side of a binary operator, 5 either side of a relation, 3 after
// punctuation and after a function's name or a sum, and none beside a bracket, a bar or a slash (`word-equations.docx` EQ1,
// `word-equations2.docx` EQ7, EQ8, `word-stops-equations.docx` EQ13, EQ17, EQ20). A negative space is one TeX leaves out
// in a script
// punctuation and after a function's name or a sum, 3 beside a fraction or the dots next to an ordinary atom, a bracket,
// a bar, punctuation after it or another fraction, and 3 before a function or a sum, after a letter, a digit, a fraction
// or a closing bracket, and none beside a bracket, a bar or a slash otherwise (`word-equations.docx` EQ1,
// `word-equations2.docx` EQ7, EQ8, `word-stops-equations.docx` EQ13, EQ17, EQ20, `word-stops-equations2.docx` EQ32,
// `word-stops-equations3.docx` EQ51, EQ52j). A negative space is one TeX leaves out in a script
const TEX_CLASSES: readonly AtomClass[] = ["ordinary", "operator", "binary", "relation", "open", "close", "punctuation", "inner"];
const TEX_SPACES: readonly (readonly number[])[] = [
[0, 3, -4, -5, 0, 0, 0, -3],
@@ -406,35 +410,13 @@ const texSpace = (before: AtomClass, after: AtomClass, style: Style): number =>
return space < 0 ? (style.level > 1 ? 0 : -space) : space;
};
// The pairs of atoms Word has been seen to space as TeX does where that isn't as it spaces ordinary atoms: a fraction
// beside a letter, a digit, punctuation or another fraction, and a letter or digit before a sum or a function
// (`word-stops-equations2.docx` EQ32)
const SPACED_AS_TEX = new Set([
"ordinary inner",
"inner ordinary",
"inner inner",
"punctuation inner",
"inner punctuation",
"ordinary operator",
]);
/**
* The space between two parts of a row, in eighteenths of an em: TeX's, but none between an operator that isn't binary
* and a relation after it (`word-stops-equations.docx` EQ20a). Or why it can't be laid out: where TeX spaces a fraction, a
* sum or a function otherwise than an ordinary atom beside an atom Word hasn't been seen to space it beside, such as a
* bracket
* and a relation after it (`word-stops-equations.docx` EQ20a)
*/
const spaceBetween = (previous: Part, next: Part, style: Style): number => {
const before = previous.unary ? "ordinary" : (previous.after ?? previous.kind);
if (previous.unary && next.kind === "relation") {
return 0;
}
const space = texSpace(before, next.kind, style);
const plain = (kind: AtomClass): AtomClass => (kind === "inner" || kind === "operator" ? "ordinary" : kind);
if (space !== texSpace(plain(before), plain(next.kind), style) && !SPACED_AS_TEX.has(`${before} ${next.kind}`)) {
stop("an equation with a fraction, a sum or a function beside a bracket or bar, which Word spaces in a way not yet followed");
}
return space;
return previous.unary && next.kind === "relation" ? 0 : texSpace(before, next.kind, style);
};
// The atoms after which a binary operator is binary, rather than unary, as Word has been seen to space them
@@ -480,17 +462,42 @@ const checkSeen = (parts: readonly Part[]): void => {
});
};
/** The space between each two atoms of a row, in turn, in eighteenths of an em, by their classes (see {@link classesOf}) */
const spacesOf = (atoms: readonly Part[], style: Style): readonly number[] => {
const classes = classesOf(atoms);
return classes.slice(1).map((part, index) => spaceBetween(classes[index], part, style));
};
/**
* Why a row with the parts of a transparent phantom (`m:transp`) can't be laid out: where seeing through it makes a
* difference to the spaces of the row. Word has been seen to space one only where it doesn't, a plus at the start of its
* row, unary either way (`word-stops-equations3.docx` EQ55f)
*/
const checkTransparent = (atoms: readonly Part[], style: Style): void => {
if (!atoms.some((part) => part.transparent)) {
return;
}
const plain = atoms.map((part): Part => (part.transparent ? { box: part.box, kind: "ordinary" } : part));
const seenThrough = spacesOf(atoms, style);
if (spacesOf(plain, style).some((space, index) => space !== seenThrough[index])) {
stop("a transparent phantom whose part the atoms beside it would space otherwise than an ordinary atom");
}
};
/**
* Lays out the parts of a row in turn: the atoms of its runs and the parts Word builds up, with the spaces between them
* (see {@link spaceBetween}) and each italic correction Word adds: after a glyph that has one, unless an ordinary
* character follows it in its run, as before an operator, a bracket, punctuation, a space, a part Word builds up and the
* row's end (`word-equations.docx` EQ1, `word-equations2.docx` EQ7, `word-stops-equations.docx` EQ13b, EQ18c, EQ24), but
* not before a run of another size (EQ22). The italic correction at its end is kept apart, for scripts
* not before a run of another size (EQ22), and after scripts whose last glyph has one, whatever follows, as TeX adds it
* (`word-stops-equations.docx` EQ11b, EQ17d, `word-stops-equations3.docx` EQ51f). The italic correction at its end is
* kept apart, for scripts
*/
const rowOf = (given: readonly Part[], style: Style): Box => {
const atoms = given.filter((part) => !part.space);
const classes = classesOf(atoms);
checkSeen(classes);
checkTransparent(atoms, style);
const resolved = new Map(atoms.map((part, index) => [part, classes[index]] as const));
const em = inPoints(UNITS, style);
let width = 0;
@@ -515,7 +522,7 @@ const rowOf = (given: readonly Part[], style: Style): Box => {
!LARGE_OPERATORS.has(next.character);
const otherSize =
next?.box.first !== undefined && original.box.last !== undefined && next.box.first.size !== original.box.last.size;
italic = ordinaryNext || otherSize ? 0 : part.box.italic;
italic = (ordinaryNext && part.character !== undefined) || otherSize ? 0 : part.box.italic;
previous = part;
});
const first = atoms.at(0)?.box.first;
@@ -568,7 +575,10 @@ const partsOf = (elements: readonly XmlObject[], style: Style): readonly Part[]
if (IGNORED.has(name) || PROPERTIES.has(name)) {
return [];
}
return name === "m:r" ? atomsOfRun(element[name], style) : [built(name, element[name], style)];
if (name === "m:r") {
return atomsOfRun(element[name], style);
}
return name === "m:phant" ? phantom(childrenOf(element[name]), style) : [built(name, element[name], style)];
});
/**
@@ -626,8 +636,8 @@ const built = (name: string, element: unknown, style: Style): Part => {
return { box: bordered(children, style), kind: "ordinary" };
case "m:eqArr":
return { box: equationArray(children, style), kind: "ordinary" };
case "m:phant":
return { box: phantom(children, style), kind: "ordinary" };
case "m:sPre":
return { box: prescripts(children, style), kind: "ordinary" };
default:
return stop(BUILT_UP);
}
@@ -724,8 +734,9 @@ const kerningOf = (base: Box, script: Box, shift: number, superscript: boolean):
* EQ13). The superscript goes after its base's italic correction, both are kerned with their base by the MATH table, and
* Word puts the table's space after them. Beside a sum or integral (`operator`), they aren't kerned, and an integral's
* subscript goes back by its italic correction (EQ13b, EQ13d). A superscript in a cramped part, such as a denominator, a
* radicand or what is under a bar or an accent, is raised by the table's shift for cramped ones
* (`word-stops-equations2.docx` EQ31); one in a lower limit, which TeX cramps, hasn't been seen
* radicand, what is under a bar or an accent, or a lower limit, is raised by the table's shift for cramped ones
* (`word-stops-equations2.docx` EQ31, `word-stops-equations3.docx` EQ50). The italic correction of the script that reaches
* furthest is the box's own, as a glyph's is, which an accent over the scripts leaves out (EQ48k)
*/
const attachScripts = (
base: Box,
@@ -738,9 +749,6 @@ const attachScripts = (
let up = 0;
let down = 0;
if (superscript !== undefined) {
if (style.lower && !style.cramped) {
stop("a superscript in a lower limit, which Word hasn't been seen to cramp or not");
}
up = constantOf(style.cramped ? "superscriptShiftUpCramped" : "superscriptShiftUp", style);
if (boxed) {
up = Math.max(up, base.height - constantOf("superscriptBaselineDropMax", style));
@@ -763,18 +771,21 @@ const attachScripts = (
}
}
let end = base.width;
let reach = base.width;
let { height, depth } = base;
if (superscript !== undefined) {
const x = base.width + (operator?.integral ? 0 : base.italic) + (operator ? 0 : kerningOf(base, superscript, up, true));
end = Math.max(end, x + superscript.width + superscript.italic);
reach = Math.max(reach, x + superscript.width);
height = Math.max(height, up + superscript.height);
}
if (subscript !== undefined) {
const x = base.width - (operator?.integral ? base.italic : 0) + (operator ? 0 : kerningOf(base, subscript, down, false));
end = Math.max(end, x + subscript.width + subscript.italic);
reach = Math.max(reach, x + subscript.width);
depth = Math.max(depth, down + subscript.depth);
}
return { width: end + (operator ? 0 : constantOf("spaceAfterScript", style)), height, depth, italic: 0, characters: false };
return { width: reach + (operator ? 0 : constantOf("spaceAfterScript", style)), height, depth, italic: end - reach, characters: false };
};
/** A superscript (`m:sSup`), subscript (`m:sSub`) or both (`m:sSubSup`) on its base, as an atom of its base's kind */
@@ -785,16 +796,18 @@ const scripts = (children: readonly XmlObject[], style: Style): Part => {
const superscript = find(children, "m:sup") === undefined ? undefined : argument(find(children, "m:sup"), scriptStyle(style));
const real = baseParts.filter((part) => !part.space);
return {
box: attachScripts(base, subscript, superscript, style),
// Its first glyph is its base's, which a base before it is kerned with (`word-stops-equations3.docx` EQ53)
box: { ...attachScripts(base, subscript, superscript, style), ...(base.first === undefined ? {} : { first: base.first }) },
kind: real.length === 1 ? (CLASSES.get(real[0].character ?? "") ?? "ordinary") : "ordinary",
};
};
// The least height Word takes a radicand to have, in Cambria Math's units, choosing the size of its sign: 1250, which
// Word's PDFs put above 1241 and no higher than 1261, as `word-stops-equations2.docx` EQ35b and EQ35c show (√A's smallest
// sign, √𝑥ᵢ's next), and EQ35d (√𝑎ᵢⱼ's next in a line of text, though its sign goes as far below its baseline as the
// radicand), so a radicand whose sign would be another size between 1242 and 1260 stops the layout
const ROOT_LEAST = [1242, 1250, 1260];
// Word's PDFs put above 1242 and no higher than 1261, as `word-stops-equations2.docx` EQ35b and EQ35c show (√A's smallest
// sign, √𝑥ᵢ's next), EQ35d (√𝑎ᵢⱼ's next in a line of text, though its sign goes as far below its baseline as the
// radicand) and `word-stops-equations3.docx` EQ46 (√𝑝's, √𝑞's, √𝜌's, √𝜂's and √𝑦's next in a line of text, √𝜇's, √𝜒's
// and √𝛾's smallest), so a radicand whose sign would be another size between 1243 and 1260 stops the layout
const ROOT_LEAST = [1243, 1250, 1260];
// How far above the radicand's ink, in Cambria Math's units, Word centres the root's sign over it: 250, which Word's PDFs
// put between 240 and 260 (`word-stops-equations2.docx` EQ35)
const ROOT_ABOVE = 250;
@@ -864,15 +877,15 @@ const INTEGRALS = new Set([..."∫∬∭∮∯∰∱∲∳"]);
* (`word-stops-equations.docx` EQ13); its limits under and over it when displayed (`m:limLoc` "undOvr", a sum's unless
* told otherwise), and beside it as scripts otherwise, with no kerning, an integral's subscript back by its italic correction,
* and with no space after them; and a thin space before its argument, but after limits beside it when displayed. In a
* script, it is as in a line of text, in the script's size (`word-stops-equations2.docx` EQ37c). One that grows with its
* argument (`m:grow`), or in a script's script, hasn't been seen
* script, or a script's script, it is as in a line of text, in the script's size (`word-stops-equations2.docx` EQ37c,
* `word-stops-equations3.docx` EQ53a). One that grows with its argument (`m:grow`) hasn't been seen
*/
const nary = (children: readonly XmlObject[], style: Style): Box => {
const properties = childrenOf(find(children, "m:naryPr"));
const character = propertyOf(properties, "m:chr") ?? "∫";
const integral = INTEGRALS.has(character);
const location = propertyOf(properties, "m:limLoc") ?? (integral ? style.limits.integrals : style.limits.sums);
if (isOn(properties, "m:grow") || style.level > 2 || (location !== "subSup" && location !== "undOvr")) {
if (isOn(properties, "m:grow") || (location !== "subSup" && location !== "undOvr")) {
stop(BUILT_UP);
}
const plain = glyphOf(character);
@@ -894,7 +907,7 @@ const nary = (children: readonly XmlObject[], style: Style): Box => {
const beside = style.level === 0 && location === "subSup" && (subscript !== undefined || superscript !== undefined);
const space = beside ? 0 : inPoints((UNITS * 3) / 18, style);
return {
width: limits.width + space + content.width,
width: limits.width + limits.italic + space + content.width,
height: Math.max(limits.height, content.height),
depth: Math.max(limits.depth, content.depth),
italic: 0,
@@ -927,9 +940,10 @@ const BRACKETS: ReadonlyMap<string, string> = new Map([
["⟩", "〉"],
]);
// How tall Word makes a bracket around a part, as a share of twice the part's ink's furthest reach from the maths axis:
// its PDFs show a share of 0.816 to 0.840 (`word-stops-equations.docx` EQ10e, EQ14, EQ15, `word-stops-equations2.docx`
// EQ33, EQ34), so a part whose bracket would be another size between them stops the layout
const BRACKET_SHARES = [0.816, 0.84];
// its PDFs show a share of 0.816 to 0.835 (`word-stops-equations.docx` EQ10e, EQ14, EQ15, `word-stops-equations2.docx`
// EQ33, EQ34, `word-stops-equations3.docx` EQ47), so a part whose bracket would be another size between them stops the
// layout
const BRACKET_SHARES = [0.816, 0.835];
/**
* Brackets around parts (`m:d`), with separators between them (`m:sepChr`): each bracket the first of its sizes as tall
@@ -1033,31 +1047,55 @@ const rowsBox = (heights: readonly number[], depths: readonly number[], style: S
return { width: 0, height: top + shift, depth: bottom - shift, italic: 0, characters: false };
};
// How wide an accent may be, at most, as a share of its base: Word's PDFs show a share of 0.901 to 0.959
// (`word-stops-equations.docx` EQ16f, `word-stops-equations2.docx` EQ31e), so a base whose accent would be another size
// between them stops the layout
const ACCENT_SHARES = [0.901, 0.959];
// How wide an accent over a part of more than one glyph may be, at most, as a share of the part, with its italic
// correction: Word's PDFs show a share of 0.979 to 1 (`word-stops-equations2.docx` EQ31e, `word-stops-equations3.docx`
// EQ48j, EQ48k), so a part whose accent would be another size between them stops the layout
const ACCENT_SHARES = [0.979, 1];
/**
* An accent over a part (`m:acc`): the widest of its sizes no wider than its share of the part (see {@link ACCENT_SHARES}),
* raised by as far as the part's ink goes above the MATH table's base height for accents, and drawn flatter over a part
* taller than its height for flatter accents (`word-stops-equations.docx` EQ16, `word-stops-equations2.docx` EQ31e). It
* takes the part's width, with its italic correction
* The size of an accent over one glyph: the widest of the accent's sizes whose ink, centred where the MATH table attaches
* accents to the glyph, or on the glyph where it doesn't say, stays within the glyph's width, without its italic
* correction, or its smallest, as Word draws it over 𝑥, 𝑛, 𝑔, 𝑢, 𝑇, 𝑊, 𝑍, 𝑑, 𝑡 and 𝐼 (`word-stops-equations.docx` EQ16,
* `word-stops-equations3.docx` EQ48): the second size over 𝑇, where it fits, and the smallest over 𝑍, nearly as wide,
* where the second would reach past its right
*/
const accentOver = (glyph: number, variants: readonly (readonly [number, number])[]): number => {
const [width] = metricsOf(glyph);
const centre = TOP_ACCENT_ATTACHMENTS.get(glyph) ?? width / 2;
const fits = ([variant]: readonly [number, number]): boolean => {
const [, , , left, right] = metricsOf(variant);
const half = (right - left) / 2;
return centre - half >= 0 && centre + half <= width;
};
return (variants.filter(fits).at(-1) ?? variants[0])[0];
};
/**
* An accent over a part (`m:acc`): over one glyph, the widest of its sizes that fits the glyph (see {@link accentOver}),
* and over more, the widest no wider than its share of the part (see {@link ACCENT_SHARES}), raised by as far as the
* part's ink goes above the MATH table's base height for accents, and drawn flatter over a part taller than its height
* for flatter accents (`word-stops-equations.docx` EQ16, `word-stops-equations2.docx` EQ31e, `word-stops-equations3.docx`
* EQ48). It takes the part's width, with its italic correction where the part ends with a glyph (EQ16, EQ48h), but
* without a script's (EQ48k), even where it is wider than the part, as over 𝐼 (EQ48i)
*/
const accented = (children: readonly XmlObject[], style: Style): Box => {
const character = propertyOf(childrenOf(find(children, "m:accPr")), "m:chr") ?? "\u0302";
const base = argument(find(children, "m:e"), cramp(style));
const width = base.width + base.italic;
const parts = partsOf(childrenOf(find(children, "m:e")), cramp(style));
const base = parts.length === 0 ? stop("a part of an equation with nothing in it") : rowOf(parts, cramp(style));
const width = base.width + (base.last === undefined ? 0 : base.italic);
const plain = glyphOf(character);
const variants = HORIZONTAL_VARIANTS.get(plain) ?? [[plain, 0] as const];
const [narrower, wider] = ACCENT_SHARES.map(
(share) => variants.filter(([, wide], index) => index === 0 || inPoints(wide, style) <= width * share).at(-1)![0],
);
if (narrower !== wider) {
stop("an accent whose size Word's PDFs leave between two");
}
const flat = base.height > constantOf("flattenedAccentBaseHeight", style) ? FLATTENED_ACCENTS.get(narrower) : undefined;
const accent = glyphBox(flat ?? narrower, sizeOf(style));
const atoms = parts.filter((part) => !part.space);
const only = atoms.length === 1 && atoms[0].character !== undefined ? atoms[0].box.first : undefined;
const widest = (): number => {
const [narrower, wider] = ACCENT_SHARES.map(
(share) => variants.filter(([, wide], index) => index === 0 || inPoints(wide, style) <= width * share).at(-1)![0],
);
return narrower === wider ? narrower : stop("an accent whose size Word's PDFs leave between two");
};
const chosen = only === undefined ? widest() : accentOver(only.glyph, variants);
const flat = base.height > constantOf("flattenedAccentBaseHeight", style) ? FLATTENED_ACCENTS.get(chosen) : undefined;
const accent = glyphBox(flat ?? chosen, sizeOf(style));
const raise = Math.max(0, base.height - constantOf("accentBaseHeight", style));
return { width, height: Math.max(base.height, raise + accent.height), depth: base.depth, italic: 0, characters: false };
};
@@ -1077,30 +1115,40 @@ const barred = (children: readonly XmlObject[], style: Style): Box => {
return { ...base, depth: bottom + constantOf("underbarExtraDescender", style), characters: false };
};
// The properties of a box (`m:borderBoxPr`) that hide its sides or strike through it, which Word's PDFs haven't shown
const BOX_SIDES = ["m:hideTop", "m:hideBot", "m:hideLeft", "m:hideRight", "m:strikeH", "m:strikeV", "m:strikeBLTR", "m:strikeTLBR"];
/**
* A box around a part (`m:borderBox`): its border as far from the part's ink on every side as a bar over or under it,
* the MATH table's gap and rule (`word-stops-equations.docx` EQ18c, `word-stops-equations2.docx` EQ36). One with a side
* hidden or struck through hasn't been seen
* the MATH table's gap and rule (`word-stops-equations.docx` EQ18c, `word-stops-equations2.docx` EQ36), struck through
* or not (`m:strikeH`, `word-stops-equations3.docx` EQ55b). One with its top hidden takes the same room, as far as Word
* has shown: around 𝑥, whose line is the font's with or without the room above the box (EQ55a). Or why it can't be laid
* out: one with its left or right side hidden, whose room there would show in its width, or with its top or bottom
* hidden over a part so tall that the room there would show in its line, which Word hasn't been seen to keep or not
*/
const bordered = (children: readonly XmlObject[], style: Style): Box => {
const properties = childrenOf(find(children, "m:borderBoxPr"));
if (BOX_SIDES.some((name) => isOn(properties, name))) {
stop("a box with a side hidden or struck through");
if (isOn(properties, "m:hideLeft") || isOn(properties, "m:hideRight")) {
stop("a box with its left or right side hidden");
}
const base = settled(argument(find(children, "m:e"), style));
const room = constantOf("overbarVerticalGap", style) + constantOf("overbarRuleThickness", style);
return { width: base.width + 2 * room, height: base.height + room, depth: base.depth + room, italic: 0, characters: false };
const box: Box = { width: base.width + 2 * room, height: base.height + room, depth: base.depth + room, italic: 0, characters: false };
const line: Style = { ...style, level: style.level < 2 ? style.level : 1 };
if (
(isOn(properties, "m:hideTop") && box.height + constantOf("mathLeading", line) > inPoints(ASCENT, line)) ||
(isOn(properties, "m:hideBot") && box.depth > inPoints(DESCENT, line))
) {
stop("a box with its top or bottom hidden, where the room there would show in its line");
}
return box;
};
/**
* An equation array (`m:eqArr`): its rows spaced as a matrix's (see {@link matrix}), each lined up at the ampersand in it,
* which isn't drawn, what is before it right-aligned and what is after it left-aligned, with the space between the atoms
* either side of it after it, and the whole centred on the maths axis (`word-stops-equations2.docx` EQ37d). Rows lined up
* otherwise, with more than one ampersand or none, or at an alignment mark (`m:aln`), rows spaced otherwise, and arrays
* lined up otherwise with the line, haven't been seen
* either side of it after it, or, where no row has an ampersand, each centred, and the whole centred on the maths axis
* (`word-stops-equations2.docx` EQ37d, `word-stops-equations3.docx` EQ54a). An alignment mark (`m:aln`) on a run leaves
* the rows as they are without it (EQ54c). Rows with more than one ampersand, which Word lines up at the first and
* spaces at the second in a way not yet known (EQ54b), rows with an ampersand beside rows without, rows spaced
* otherwise, and arrays lined up otherwise with the line, haven't been seen
*/
const equationArray = (children: readonly XmlObject[], style: Style): Box => {
const properties = childrenOf(find(children, "m:eqArrPr"));
@@ -1113,23 +1161,22 @@ const equationArray = (children: readonly XmlObject[], style: Style): Box => {
const rows = children
.filter((child) => "m:e" in child)
.map((row) => {
const elements = childrenOf(row["m:e"]);
const parts = partsOf(elements, style);
const parts = partsOf(childrenOf(row["m:e"]), style);
const at = parts.findIndex((part) => part.character === "&");
const marked = elements.some(
(element) => "m:r" in element && find(childrenOf(find(childrenOf(element["m:r"]), "m:rPr")), "m:aln"),
);
if (at === -1 || marked || parts.some((part, index) => index !== at && part.character === "&")) {
stop("an equation array lined up in a way not yet followed");
if (parts.some((part, index) => index !== at && part.character === "&")) {
stop("an equation array with more than one ampersand in a row, which Word spaces in a way not yet followed");
}
const before = parts.slice(0, at);
const before = at === -1 ? [] : parts.slice(0, at);
const whole = rowOf([...before, ...parts.slice(at + 1)], style);
const left = before.length === 0 ? 0 : settled(rowOf(before, style)).width;
return { left, right: whole.width + whole.italic - left, height: whole.height, depth: whole.depth };
return { aligned: at !== -1, left, right: whole.width + whole.italic - left, height: whole.height, depth: whole.depth };
});
if (rows.length === 0) {
stop("a part of an equation with nothing in it");
}
if (rows.some(({ aligned }) => aligned) && !rows.every(({ aligned }) => aligned)) {
stop("an equation array with an ampersand in some rows and none in others");
}
return {
...rowsBox(
rows.map(({ height }) => height),
@@ -1141,15 +1188,41 @@ const equationArray = (children: readonly XmlObject[], style: Style): Box => {
};
/**
* A phantom (`m:phant`): its part, shown or not, taking its room (`word-stops-equations2.docx` EQ37e). One that takes
* none of its width, height or depth, or that the spacing around it sees through, hasn't been seen
* A phantom (`m:phant`), as the parts of its row: its part, shown or not, taking its room, or none of its width
* (`m:zeroWid`), its height (`m:zeroAsc`) or its depth (`m:zeroDesc`), as an ordinary atom (`word-stops-equations2.docx`
* EQ37e, `word-stops-equations3.docx` EQ55c to EQ55e); or, where it is transparent (`m:transp`), its part's own atoms,
* which the row lays out only where seeing through them makes no difference (see {@link checkSeen}, EQ55f)
*/
const phantom = (children: readonly XmlObject[], style: Style): Box => {
const phantom = (children: readonly XmlObject[], style: Style): readonly Part[] => {
const properties = childrenOf(find(children, "m:phantPr"));
if (["m:zeroWid", "m:zeroAsc", "m:zeroDesc", "m:transp"].some((name) => isOn(properties, name))) {
stop("a phantom that takes less than its part's room");
}
return { ...settled(argument(find(children, "m:e"), style)), characters: false };
const less = (box: Box): Box => ({
...box,
...(isOn(properties, "m:zeroWid") ? { width: 0, italic: 0 } : {}),
...(isOn(properties, "m:zeroAsc") ? { height: 0 } : {}),
...(isOn(properties, "m:zeroDesc") ? { depth: 0 } : {}),
});
return isOn(properties, "m:transp")
? partsOf(childrenOf(find(children, "m:e")), style).map((part) => ({ ...part, box: less(part.box), transparent: true }))
: [{ box: { ...less(settled(argument(find(children, "m:e"), style))), characters: false }, kind: "ordinary" }];
};
/**
* Pre-scripts (`m:sPre`): a subscript and a superscript before their base, lined up at their left, as far above and
* below the baseline as scripts after it would be (see {@link attachScripts}), with the MATH table's space after
* scripts before them instead of after, and the base straight after them, not kerned with them, though the table would
* tuck 𝑥 under its subscript (`word-stops-equations3.docx` EQ55g)
*/
const prescripts = (children: readonly XmlObject[], style: Style): Box => {
const base = argument(find(children, "m:e"), style);
const subscript = argument(find(children, "m:sub"), scriptStyle(style));
const superscript = argument(find(children, "m:sup"), scriptStyle(style));
const attached = attachScripts({ ...base, width: 0, italic: 0, first: undefined, last: undefined }, subscript, superscript, style);
return {
...attached,
width: attached.width + attached.italic + base.width,
italic: base.italic,
...(base.last === undefined ? {} : { last: base.last }),
};
};
/**
@@ -1196,10 +1269,10 @@ const assembly = (
return (inPoints(longest, style) < width ? parts : fixed).map(([glyph]) => glyph);
};
// How wide a brace of one of its own sizes may be, at most, as a share of its part: Word's PDFs show a share of 0.921 to
// 1.086 (`word-stops-equations2.docx` EQ37f, EQ37g), so a part whose brace would be another size between them stops the
// layout
const BRACE_SHARES = [0.921, 1.086];
// How wide a brace of one of its own sizes may be, at most, as a share of its part: Word's PDFs show a share of 0.981 to
// 1.021, the widest no wider than the part (`word-stops-equations2.docx` EQ37f, EQ37g, `word-stops-equations3.docx`
// EQ49), so a part whose brace would be another size between them stops the layout
const BRACE_SHARES = [0.981, 1.021];
/**
* A brace or other character grown over or under a part (`m:groupChr`): the widest of the character's sizes no wider
+12 -14
View File
@@ -733,7 +733,7 @@ describe("readDocument", () => {
expect(reasonOf(readBody([p(r(t("a")), r(t("b")), { "w:del": [displayed] })]))).to.equal(undefined);
});
it("should stop at equations in a maths font other than Cambria Math, or with small fractions, and displayed ones with margins, in a document's maths settings, and put limits where they say", () => {
it("should stop at equations in a maths font other than Cambria Math, and displayed ones with margins, in a document's maths settings, and put limits where they say", () => {
const equation = p(r(t("a ")), { "m:oMath": [{ "m:r": [{ "m:t": ["x"] }] }] });
const setting = (name: string, val: string): object => ({ [name]: { _attr: { "m:val": val } } });
const reasonWith = (...settings: readonly object[]): string | undefined =>
@@ -772,13 +772,12 @@ describe("readDocument", () => {
const pairWith = (...settings: readonly object[]): readonly LayoutItem[] =>
itemsOf(readWithSettings([pair], [{ "m:mathPr": settings }]));
expect(pairWith(setting("m:interSp", "240"))).to.deep.equal(pairWith(...word));
// Displayed equations' own defaults off, and small fractions with them, which Word lays out alike, but small
// fractions with them on, which haven't been seen (`word-stops-equation-small.docx` EQ43)
const small = "an equation in a document whose maths settings make fractions small";
// Displayed equations' own defaults off, and small fractions with them off or on, which Word lays out alike
// (`word-stops-equation-small.docx` EQ43, `word-stops-equation-small2.docx` EQ56)
expect(reasonWith(...word, setting("m:dispDef", "0"))).to.equal(undefined);
expect(reasonWith(...word, setting("m:dispDef", "0"), setting("m:smallFrac", "1"))).to.equal(undefined);
expect(reasonWith(...word, setting("m:smallFrac", "1"))).to.equal(small);
expect(reasonWith(...word, setting("m:dispDef", "1"), { "m:smallFrac": {} })).to.equal(small);
expect(reasonWith(...word, setting("m:smallFrac", "1"))).to.equal(undefined);
expect(reasonWith(...word, setting("m:dispDef", "1"), { "m:smallFrac": {} })).to.equal(undefined);
// A displayed sum's limits, and an integral's, under and over it or beside it as the settings say, unless its own
// properties say otherwise (`word-stops-equation-limits.docx` EQ42)
const run = (characters: string): object => ({ "m:r": [{ "m:t": [characters] }] });
@@ -7567,14 +7566,13 @@ describe("readDocument", () => {
it("should read an equation that can't be laid out in the line, but can displayed, as displayed", () => {
const run = (characters: string): object => ({ "m:r": [{ "m:t": [characters] }] });
const eleven = { styles: { default: { document: { run: { size: 22 } } } } };
// A sum in a superscript of a fraction's numerator, which in a line of text is in a script's script's style
const sum = { "m:nary": [{ "m:naryPr": [] }, { "m:sub": [run("i")] }, { "m:sup": [run("n")] }, { "m:e": [run("a")] }] };
const numerator = { "m:sSup": [{ "m:e": [run("x")] }, { "m:sup": [sum] }] };
const either = guessed(
[p(r(t("a ")), { "m:oMath": [{ "m:f": [{ "m:num": [numerator] }, { "m:den": [run("b")] }] }] })],
eleven,
);
expect(read(either)[0][0]).to.equal("an equation with a part Word builds up in a way not yet followed");
// A root over 𝜍, whose sign's size Word's PDFs leave between two in a line of text, where the gap above the
// radicand is smaller, but not displayed
const root = {
"m:rad": [{ "m:radPr": [{ "m:degHide": { _attr: { "m:val": "1" } } }] }, { "m:deg": [] }, { "m:e": [run("\u03c2")] }],
};
const either = guessed([p(r(t("a ")), { "m:oMath": [root] })], eleven);
expect(read(either)[0][0]).to.equal("a root whose sign's size Word's PDFs leave between two");
expect(itemsOf(either).map(({ type }) => type)).to.deep.equal(["text", "box"]);
});
+2 -7
View File
@@ -5427,8 +5427,8 @@ const readHyphenation = (settings: readonly XmlObject[]): Hyphenation =>
* they are depends on the computer. It puts the limits of a displayed sum or integral that doesn't say where its own go
* where the settings say (`m:naryLim`, `m:intLim`), and leaves those in a line of text beside it
* (`word-stops-equation-limits.docx` EQ42). It lays equations out alike with displayed equations' own defaults off
* (`m:dispDef`), and with small fractions on (`m:smallFrac`) too (`word-stops-equation-small.docx` EQ43), but small
* fractions with those defaults on haven't been seen. Margins of displayed equations (`m:lMargin`, `m:rMargin`) Word
* (`m:dispDef`), and with small fractions on (`m:smallFrac`) too, with those defaults off or on
* (`word-stops-equation-small.docx` EQ43, `word-stops-equation-small2.docx` EQ56). Margins of displayed equations (`m:lMargin`, `m:rMargin`) Word
* centres an equation that fits as without, but breaks one within (`word-stops-equation-settings.docx` EQS1), so one that
* fits the line but not the room between them would be laid out on one line where Word breaks it. Space around displayed
* equations, and between equations (`m:interSp`), Word leaves out, even between equations side by side in one paragraph of
@@ -5441,11 +5441,6 @@ const readMathsSettings = (settings: readonly XmlObject[]): Pick<Reader, "maths"
if ((valueIn("m:mathFont") ?? "Cambria Math") !== "Cambria Math") {
return { maths: "an equation in a maths font other than Cambria Math" };
}
const off = (name: string): boolean => find(maths, name) !== undefined && isOff(valueIn(name));
const on = (name: string): boolean => find(maths, name) !== undefined && !isOff(valueIn(name));
if (on("m:smallFrac") && !off("m:dispDef")) {
return { maths: "an equation in a document whose maths settings make fractions small" };
}
const given = (name: string): boolean => (numberOf(valueIn(name)) ?? 0) !== 0;
return {
...(given("m:lMargin") || given("m:rMargin")