Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Convert Word equations to 한글 equations in DOCX → HWPX, HWP and PDF (#143)

KnifeLemonfc9729af45b5
diff --git a/docs/ENGINES.md b/docs/ENGINES.md
index 3ff7b465..0b8e39b0 100644
--- a/docs/ENGINES.md
+++ b/docs/ENGINES.md
@@ -238,6 +238,7 @@ Readers turn the source into a small document model (`Hwp/Hwpx/HwpxModel.cs`) an
- tables with merged cells, column widths, borders and shading from the table style and cells, repeated header rows;
- pictures inline and floating, text boxes, rectangles/ellipses/lines with solid or gradient fills, groups;
- footnotes, endnotes, bookmarks, hyperlinks (web and within the document, e.g. a table of contents);
+ - equations (Word's equation editor, Office Math) as 한글 equations, see *Equations* below;
- Word's document grid ("lines"), which 한글 does not have, as an "at least" line spacing.
- **XLSX, XLS, ODS, CSV and TSV** (`Office/Sheets`, see [Spreadsheets](#spreadsheets)): every visible sheet becomes a section with one table. Cells show what Excel
shows (number formats via ExcelNumberFormat, dates, percentages, cached formula results), with fonts, fills,
@@ -280,7 +281,29 @@ Every generated file is checked in the tests with three independent readers: rhw
text) and LibreOffice + H2Orestart (opens it), see `tests/Filee.Engines.Tests/DocxToHwpxTests.cs` and
`OfficeTests.cs`.
-Not converted: Word charts, SmartArt, equations (kept as text), free-form shapes, tracked changes and comments.
+Not converted: Word charts, SmartArt, free-form shapes, tracked changes and comments.
+
+### Equations
+
+Word equations (`m:oMath`, `m:oMathPara`) become 한글 equation objects (`hp:equation`) with an equation script
+(`Hwp/Hwpx/Docx/OmmlReader.cs` reads them into a small math tree, `Hwp/Hwpx/EquationScript.cs` writes the script),
+so DOCX → HWPX and HWP keep editable equations and DOCX → PDF draws them with rhwp (#143):
+
+- fractions (`{a} over {b}`, also without bar or written linear `a/b`), sub- and superscripts and scripts before the
+ base, square roots and roots with an index, sums, products, unions and integrals with their limits, brackets that
+ grow (`LEFT ( … RIGHT )`), matrices (`pmatrix`, `bmatrix`, `dmatrix`), cases, equation arrays (`pile`), function
+ names and `lim` with what goes under it, accents (hat, bar, vec, dot, tilde …), over- and underlines;
+- Greek letters, operators and arrows as 한글's commands (`omega`, `TIMES`, `LEQ`, `INF`, `rarrow` …), upright text
+ (`m:sty="p"`, normal text) in `rm`, bold in `bold`; a display equation alone in its paragraph is centred;
+- variables are written letter by letter when they read like a command (`x _{i n}`, not `in` = ∈);
+- boxes, phantoms and group characters (braces above or below) keep only their content; other characters are
+ written as they are.
+
+The box an equation is stored with (`hp:sz`) is measured like rhwp lays the script out (estimated character
+widths, script scale 0.7, fraction and root spacing, from rhwp's `equation/layout.rs`): rhwp stretches an equation to
+its stored width, so a wrong box would distort it. 한글 lays the script out again when the equation is edited.
+The model's other writers (HTML, EPUB, Markdown, TXT …) write a linear form instead, `(a+b)/(2c)`, `x_i^2`, `√(x)`,
+which is also the equation's alternative text in HWPX.
## Spreadsheets
@@ -725,7 +748,10 @@ For HWP / HWPX → PDF, rhwp renders a copy of the HWPX (an HWP is exported with
change something for it (`Hwp/RhwpInput.cs`): fonts that are installed, the laid-out size of boxes sized relative to
the column, spaced equation commands, and, in an HWPX exported from an HWP (rhwp's `META-INF/rhwp-hwp5-origin`
marker), the stored line of a cell paragraph that holds only a floating table moved up to the paragraph's top, so the
-table is not drawn over the paragraphs below it (#49).
+table is not drawn over the paragraphs below it (#49). Paragraphs without stored lines (Word equations written by the
+HWPX writer) get room for their equations: rhwp puts a line's baseline at 85 % of its tallest equation and the
+equation's own baseline on it, so a fraction, matrix or sum hangs below the line; that overhang is added as space
+after the paragraph (#143).
rhwp renders text slowly: about 1 s per KB of section XML, some 4 s per page of a novel (rhwp 0.8.7 on an
i7-1185G7, pictures cost little). So each rhwp run's time limit follows the document's text: 2 minutes + 30 minutes
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
index 3c45ecc6..ce34ec9c 100644
--- a/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/DocxReader.cs
@@ -508,7 +508,7 @@ internal sealed partial class DocxReader
if (element.Name.Namespace == M)
{
if (name is "oMath" or "oMathPara")
- builder.Add(new HText(string.Concat(element.Descendants(M + "t").Select(t => t.Value)), CharFormat(styleRun) with { Italic = true }));
+ Equations(element, builder, styleRun);
continue;
}
if (element.Name.Namespace != W)
@@ -655,6 +655,41 @@ internal sealed partial class DocxReader
}
}
+ /// <summary>
+ /// Word math (m:oMath, or m:oMathPara with one or more lines) as equations in the size of its runs. A display
+ /// equation alone in its paragraph is aligned like Word shows it (centred unless m:jc says otherwise).
+ /// </summary>
+ private void Equations(XElement math, ParagraphBuilder builder, RunProps styleRun)
+ {
+ var rPr = math.Descendants(M + "r").Select(r => r.Element(W + "rPr")).FirstOrDefault(p => p is not null);
+ var format = CharFormat(RunProperties(rPr, styleRun)) with { Italic = true };
+ var lines = math.Name.LocalName == "oMathPara" ? math.Elements(M + "oMath").ToList() : [math];
+
+ if (math.Name.LocalName == "oMathPara" && math.Parent is { } paragraph
+ && !paragraph.Descendants(W + "t").Any(t => t.Value.Trim().Length > 0 && !t.Ancestors(M + "oMathPara").Any()))
+ {
+ var align = Attr(math.Element(M + "oMathParaPr")?.Element(M + "jc"), "val", M) switch
+ {
+ "left" => HAlign.Left,
+ "right" => HAlign.Right,
+ _ => HAlign.Center,
+ };
+ builder.Current.Format = builder.Current.Format with { Align = align };
+ }
+
+ var first = true;
+ foreach (var line in lines)
+ {
+ var equation = OmmlReader.Read(line);
+ if (equation is MathRow { Items.Count: 0 })
+ continue;
+ if (!first)
+ builder.Add(new HLineBreak(format));
+ builder.Add(new HEquation(equation, format));
+ first = false;
+ }
+ }
+
private HNote? Note(XElement reference, Dictionary<string, XElement> notes, Part? part, bool endnote)
{
if (part is null || !notes.TryGetValue(Attr(reference, "id") ?? "", out var element))
diff --git a/src/Filee.Engines/Hwp/Hwpx/Docx/OmmlReader.cs b/src/Filee.Engines/Hwp/Hwpx/Docx/OmmlReader.cs
new file mode 100644
index 00000000..fffd45e7
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/Docx/OmmlReader.cs
@@ -0,0 +1,603 @@
+// Word equations (Office Math, m:oMath) → the equation tree of EquationScript, which the HWPX writer stores as a 한글
+// equation (and other writers as linear text). Covers what Word's equation editor makes: fractions, scripts, roots,
+// sums and integrals with limits, brackets, matrices, equation arrays and cases, functions and limits, accents and bars.
+// Boxes, border boxes, phantoms and group characters keep their content. Plain (m:sty="p") and normal text is upright.
+
+using System.Text;
+using System.Xml.Linq;
+
+namespace Filee.Engines.Hwp.Hwpx.Docx;
+
+internal static class OmmlReader
+{
+ private static readonly XNamespace M = "http://schemas.openxmlformats.org/officeDocument/2006/math";
+ private static readonly XNamespace W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
+
+ /// <summary>Unicode symbols written as 한글 equation commands (all known to rhwp too).</summary>
+ private static readonly Dictionary<char, string> Commands = new()
+ {
+ ['α'] = "alpha",
+ ['β'] = "beta",
+ ['γ'] = "gamma",
+ ['δ'] = "delta",
+ ['ε'] = "epsilon",
+ ['ϵ'] = "epsilon",
+ ['ζ'] = "zeta",
+ ['η'] = "eta",
+ ['θ'] = "theta",
+ ['ϑ'] = "vartheta",
+ ['ι'] = "iota",
+ ['κ'] = "kappa",
+ ['λ'] = "lambda",
+ ['μ'] = "mu",
+ ['ν'] = "nu",
+ ['ξ'] = "xi",
+ ['ο'] = "omicron",
+ ['π'] = "pi",
+ ['ϖ'] = "varpi",
+ ['ρ'] = "rho",
+ ['σ'] = "sigma",
+ ['ς'] = "varsigma",
+ ['τ'] = "tau",
+ ['υ'] = "upsilon",
+ ['φ'] = "phi",
+ ['ϕ'] = "phi",
+ ['χ'] = "chi",
+ ['ψ'] = "psi",
+ ['ω'] = "omega",
+ ['Α'] = "Alpha",
+ ['Β'] = "Beta",
+ ['Γ'] = "Gamma",
+ ['Δ'] = "Delta",
+ ['Ε'] = "Epsilon",
+ ['Ζ'] = "Zeta",
+ ['Η'] = "Eta",
+ ['Θ'] = "Theta",
+ ['Ι'] = "Iota",
+ ['Κ'] = "Kappa",
+ ['Λ'] = "Lambda",
+ ['Μ'] = "Mu",
+ ['Ν'] = "Nu",
+ ['Ξ'] = "Xi",
+ ['Ο'] = "Omicron",
+ ['Π'] = "Pi",
+ ['Ρ'] = "Rho",
+ ['Σ'] = "Sigma",
+ ['Τ'] = "Tau",
+ ['Υ'] = "Upsilon",
+ ['Φ'] = "Phi",
+ ['Χ'] = "Chi",
+ ['Ψ'] = "Psi",
+ ['Ω'] = "Omega",
+ ['×'] = "TIMES",
+ ['÷'] = "DIV",
+ ['±'] = "PLUSMINUS",
+ ['∓'] = "MINUSPLUS",
+ ['·'] = "CDOT",
+ ['⋅'] = "CDOT",
+ ['∘'] = "CIRC",
+ ['•'] = "BULLET",
+ ['∙'] = "BULLET",
+ ['≠'] = "NEQ",
+ ['≤'] = "LEQ",
+ ['≦'] = "LEQ",
+ ['≥'] = "GEQ",
+ ['≧'] = "GEQ",
+ ['≈'] = "APPROX",
+ ['≡'] = "EQUIV",
+ ['≅'] = "CONG",
+ ['∼'] = "SIM",
+ ['≃'] = "SIMEQ",
+ ['∝'] = "PROPTO",
+ ['∞'] = "INF",
+ ['∂'] = "PARTIAL",
+ ['∈'] = "IN",
+ ['∉'] = "NOTIN",
+ ['∋'] = "OWNS",
+ ['⊂'] = "SUBSET",
+ ['⊃'] = "SUPERSET",
+ ['⊆'] = "SUBSETEQ",
+ ['⊇'] = "SUPSETEQ",
+ ['∪'] = "CUP",
+ ['∩'] = "CAP",
+ ['∀'] = "FORALL",
+ ['∃'] = "EXIST",
+ ['¬'] = "LNOT",
+ ['∧'] = "WEDGE",
+ ['∨'] = "VEE",
+ ['∅'] = "EMPTYSET",
+ ['∴'] = "THEREFORE",
+ ['∵'] = "BECAUSE",
+ ['→'] = "rarrow",
+ ['←'] = "larrow",
+ ['↔'] = "lrarrow",
+ ['↑'] = "uparrow",
+ ['↓'] = "downarrow",
+ ['⇒'] = "RARROW",
+ ['⇐'] = "LARROW",
+ ['⇔'] = "LRARROW",
+ ['⋯'] = "CDOTS",
+ ['…'] = "LDOTS",
+ ['⋮'] = "VDOTS",
+ ['⋱'] = "DDOTS",
+ ['°'] = "DEG",
+ ['′'] = "prime",
+ ['ℓ'] = "ELL",
+ ['ℏ'] = "HBAR",
+ ['ℵ'] = "ALEPH",
+ ['∠'] = "ANGLE",
+ ['△'] = "TRIANGLE",
+ ['⊥'] = "BOT",
+ ['{'] = "LBRACE",
+ ['}'] = "RBRACE",
+ ['\\'] = "RSLANT",
+ ['~'] = "SIM",
+ };
+
+ /// <summary>Large operators (m:nary, or the character typed as text) → their command.</summary>
+ private static readonly Dictionary<string, string> BigOperators = new()
+ {
+ ["∑"] = "SUM",
+ ["∏"] = "PROD",
+ ["∐"] = "COPROD",
+ ["⋃"] = "BIGCUP",
+ ["⋂"] = "BIGCAP",
+ ["⋁"] = "BIGVEE",
+ ["⋀"] = "BIGWEDGE",
+ ["∫"] = "INT",
+ ["∬"] = "DINT",
+ ["∭"] = "TINT",
+ ["∮"] = "OINT",
+ ["∯"] = "ODINT",
+ ["∰"] = "OTINT",
+ };
+
+ /// <summary>Function names both 한글 and rhwp write upright by themselves.</summary>
+ private static readonly HashSet<string> Functions = new(StringComparer.Ordinal)
+ {
+ "sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh", "coth",
+ "log", "ln", "lg", "exp", "det", "dim", "ker", "hom", "arg", "gcd", "lcm", "max", "min", "mod",
+ };
+
+ /// <summary>
+ /// Words of the equation language, compared ignoring case: a variable spelled like one ("in", "to", "max", "Pi") is
+ /// written one letter at a time so that 한글 and rhwp do not read it as a command.
+ /// </summary>
+ private static readonly HashSet<string> Reserved = new(StringComparer.OrdinalIgnoreCase)
+ {
+ "over", "atop", "sup", "sub", "sqrt", "root", "of", "left", "right", "bigg", "int", "integral", "oint", "smallint",
+ "lim", "sum", "union", "inter", "prod", "rel", "buildrel", "pile", "lpile", "rpile", "cases", "choose", "binom",
+ "matrix", "pmatrix", "bmatrix", "dmatrix", "vmatrix", "col", "lcol", "rcol", "lsub", "lsup", "ladder", "sladder",
+ "longdiv", "color", "arch", "under", "not", "rm", "it", "bold", "from", "to", "inf", "infty", "in", "le", "ge",
+ "ne", "ll", "gg", "text", "frac", "begin", "end", "quad", "qquad", "phantom", "eqalign", "benzene", "base",
+ "top", "bot", "well", "att", "hund", "thou", "ohm", "mho", "wp", "ell", "liter", "image", "imag", "dots", "vert",
+ "nabla", "deg", "prime", "star", "ast", "pm", "mp", "neg", "land", "lor", "xor", "gets", "implies", "iff",
+ "mapsto", "pr", "limsup", "liminf", "ni", "exists", "angle", "triangle", "sim", "times", "div", "divide",
+ };
+
+ /// <summary>
+ /// Beginnings that rhwp (and Filee's equation fixes before rhwp, RhwpInput) split off a longer word as a command
+ /// ("overa" → over a, "sinx" → sin x, "lek" → le k, "INPUT" → IN PUT).
+ /// </summary>
+ private static readonly string[] ReservedPrefixes =
+ [
+ "over", "atop", "bold", "it", "rm", "times", "sim", "prime", "root", "sqrt", "sin", "cos", "tan", "sec", "csc",
+ "cot", "bar", "vec", "hat", "tilde", "dot", "ddot", "acute", "grave", "check", "breve", "leq", "geq", "neq",
+ "triangle", "angle", "cap", "cup", "cdot", "ldots", "vdots", "ddots", "widehat", "widetilde", "le", "ge", "in",
+ "circ", "subset", "superset", "notin", "approx", "equiv", "div", "pm", "mp", "smallinter", "smallunion", "owns",
+ "inter", "union", "cong", "plusminus", "minusplus", "bullet", "oplus", "forall", "exist", "therefore", "because",
+ "deg", "inf", "partial", "rarrow", "larrow", "lrarrow", "emptyset", "propto", "underline",
+ ];
+
+ /// <summary>A word that stays one variable (italic letters side by side) in 한글 and rhwp.</summary>
+ private static bool IsPlainWord(string word) =>
+ word.Length == 1
+ || (!Reserved.Contains(word)
+ && !Commands.Values.Concat(BigOperators.Values).Concat(Functions).Concat(Accents.Values).Contains(word, StringComparer.OrdinalIgnoreCase)
+ && !ReservedPrefixes.Any(p => word.StartsWith(p, StringComparison.OrdinalIgnoreCase)));
+
+ /// <summary>Accent characters (m:acc) → decoration command.</summary>
+ private static readonly Dictionary<char, string> Accents = new()
+ {
+ ['\u0302'] = "hat",
+ ['^'] = "hat",
+ ['\u030C'] = "check",
+ ['\u0303'] = "tilde",
+ ['~'] = "tilde",
+ ['\u0301'] = "acute",
+ ['\u0300'] = "grave",
+ ['\u0307'] = "dot",
+ ['\u0308'] = "ddot",
+ ['\u0304'] = "bar",
+ ['\u0305'] = "bar",
+ ['¯'] = "bar",
+ ['\u20D7'] = "vec",
+ ['\u20D6'] = "vec",
+ ['→'] = "vec",
+ ['\u20E1'] = "dyad",
+ };
+
+ /// <summary>The equation tree of one m:oMath.</summary>
+ public static MathNode Read(XElement oMath) => Content(oMath, roman: false);
+
+ // ───────────────────────── Containers ─────────────────────────
+
+ /// <summary>The children of an argument (m:e, m:num, m:sub ...) side by side; null and empty give an empty row.</summary>
+ private static MathRow Content(XElement? container, bool roman)
+ {
+ var items = new List<MathNode>();
+ foreach (var child in container?.Elements() ?? [])
+ Element(child, items, roman);
+ return new MathRow(items);
+ }
+
+ private static MathRow Argument(XElement parent, string name, bool roman = false) => Content(parent.Element(M + name), roman);
+
+ /// <summary>Adds a row as one group, or its only item by itself (the same to 한글, a simpler script).</summary>
+ private static void Add(List<MathNode> output, MathRow row)
+ {
+ if (row.Items.Count == 1)
+ output.Add(row.Items[0]);
+ else if (row.Items.Count > 0)
+ output.Add(row);
+ }
+
+ private static void Element(XElement element, List<MathNode> output, bool roman)
+ {
+ if (element.Name.Namespace == W)
+ {
+ switch (element.Name.LocalName)
+ {
+ case "r":
+ // A non-math run inside an equation: upright text.
+ Text(string.Concat(element.Elements(W + "t").Select(t => t.Value)), output, Style.Normal);
+ break;
+ case "ins" or "smartTag" or "customXml" or "sdt" or "sdtContent":
+ foreach (var child in element.Elements())
+ Element(child, output, roman);
+ break;
+ }
+ return;
+ }
+ if (element.Name.Namespace != M)
+ return;
+
+ switch (element.Name.LocalName)
+ {
+ case "r":
+ Run(element, output, roman);
+ break;
+ case "f":
+ output.Add(Fraction(element));
+ break;
+ case "sSub":
+ output.Add(Scripts(Argument(element, "e", roman), Argument(element, "sub"), null));
+ break;
+ case "sSup":
+ output.Add(Scripts(Argument(element, "e", roman), null, Argument(element, "sup")));
+ break;
+ case "sSubSup":
+ output.Add(Scripts(Argument(element, "e", roman), Argument(element, "sub"), Argument(element, "sup")));
+ break;
+ case "sPre":
+ // Scripts before the base: {} _{a} ^{b} base.
+ output.Add(new MathScripts(MathRow.Empty, Argument(element, "sub"), Argument(element, "sup")));
+ Add(output, Argument(element, "e"));
+ break;
+ case "rad":
+ {
+ var degree = Argument(element, "deg");
+ var hidden = Flag(element.Element(M + "radPr")?.Element(M + "degHide"));
+ output.Add(new MathRoot(hidden || IsEmpty(degree) ? null : degree, Argument(element, "e")));
+ break;
+ }
+ case "nary":
+ Nary(element, output);
+ break;
+ case "d":
+ output.Add(Delimiter(element));
+ break;
+ case "m":
+ output.Add(Matrix(element, "matrix"));
+ break;
+ case "eqArr":
+ output.Add(new MathPile(element.Elements(M + "e").Select(e => (MathNode)WithoutAlign(Content(e, roman))).ToList()));
+ break;
+ case "func":
+ Add(output, Argument(element, "fName", roman: true));
+ Add(output, Argument(element, "e"));
+ break;
+ case "limLow":
+ {
+ var name = Argument(element, "e", roman);
+ var limit = Argument(element, "lim");
+ output.Add(name.Items is [MathLimit] ? new MathLimit(limit) : Scripts(name, limit, null));
+ break;
+ }
+ case "limUpp":
+ output.Add(Scripts(Argument(element, "e", roman), null, Argument(element, "lim")));
+ break;
+ case "acc":
+ {
+ var chr = Val(element.Element(M + "accPr")?.Element(M + "chr"));
+ var body = Argument(element, "e", roman);
+ var mark = string.IsNullOrEmpty(chr) ? '\u0302' : chr[0];
+ output.Add(Accents.TryGetValue(mark, out var command) ? new MathAccent(command, body) : body);
+ break;
+ }
+ case "bar":
+ {
+ var top = Val(element.Element(M + "barPr")?.Element(M + "pos")) == "top";
+ output.Add(new MathAccent(top ? "OVERLINE" : "UNDERLINE", Argument(element, "e", roman)));
+ break;
+ }
+ case "box" or "borderBox" or "phant" or "groupChr":
+ Add(output, Argument(element, "e", roman));
+ break;
+ case "oMath":
+ Add(output, Content(element, roman));
+ break;
+ }
+ }
+
+ private static MathNode Fraction(XElement f)
+ {
+ var numerator = Argument(f, "num");
+ var denominator = Argument(f, "den");
+ return Val(f.Element(M + "fPr")?.Element(M + "type")) switch
+ {
+ "noBar" => new MathFraction(numerator, denominator, Bar: false),
+ "lin" or "skw" => new MathRow([numerator, new MathSymbol("/"), denominator]),
+ _ => new MathFraction(numerator, denominator),
+ };
+ }
+
+ /// <summary>Scripts; a large operator character as the base (∑ typed as text) takes them as limits.</summary>
+ private static MathNode Scripts(MathRow baseRow, MathRow? sub, MathRow? sup)
+ {
+ if (baseRow.Items is [MathBigOperator { Lower: null, Upper: null } big])
+ return big with { Lower = sub, Upper = sup };
+ return new MathScripts(baseRow.Items.Count == 1 ? baseRow.Items[0] : baseRow, sub, sup);
+ }
+
+ private static void Nary(XElement nary, List<MathNode> output)
+ {
+ var properties = nary.Element(M + "naryPr");
+ var chr = properties?.Element(M + "chr") is { } chrElement ? Val(chrElement) ?? "∫" : "∫";
+ var sub = Flag(properties?.Element(M + "subHide")) ? null : Argument(nary, "sub");
+ var sup = Flag(properties?.Element(M + "supHide")) ? null : Argument(nary, "sup");
+ if (sub is not null && IsEmpty(sub))
+ sub = null;
+ if (sup is not null && IsEmpty(sup))
+ sup = null;
+ output.Add(BigOperators.TryGetValue(chr, out var command)
+ ? new MathBigOperator(command, chr, sub, sup)
+ : new MathScripts(new MathText(chr), sub, sup));
+ Add(output, Argument(nary, "e"));
+ }
+
+ private static MathNode Delimiter(XElement d)
+ {
+ var properties = d.Element(M + "dPr");
+ string Character(string name, string fallback) =>
+ properties?.Element(M + name) is { } element ? Val(element) ?? "" : fallback;
+ var open = Character("begChr", "(");
+ var close = Character("endChr", ")");
+ var separator = Character("sepChr", "|");
+ var parts = d.Elements(M + "e").ToList();
+
+ // A matrix in brackets is a pmatrix / bmatrix / dmatrix; a brace before an equation array is cases.
+ if (parts.Count == 1 && Arguments(parts[0]) is [var only])
+ {
+ var style = (open, close) switch
+ {
+ ("(", ")") => "pmatrix",
+ ("[", "]") => "bmatrix",
+ ("|", "|") => "dmatrix",
+ _ => null,
+ };
+ if (only.Name == M + "m" && style is not null)
+ return Matrix(only, style);
+ if (only.Name == M + "eqArr" && open == "{" && close.Length == 0)
+ return Cases(only);
+ }
+
+ var items = new List<MathNode>();
+ for (var i = 0; i < parts.Count; i++)
+ {
+ if (i > 0)
+ Text(separator, items, Style.Plain);
+ items.AddRange(Content(parts[i], roman: false).Items);
+ }
+ var body = new MathRow(items);
+ if (EquationScript.IsBracket(open) && EquationScript.IsBracket(close))
+ return new MathBrackets(open, close, body);
+
+ // Brackets 한글 cannot stretch (rare): written as characters around the content.
+ var row = new List<MathNode>();
+ Text(open, row, Style.Plain);
+ row.Add(body);
+ Text(close, row, Style.Plain);
+ return new MathRow(row);
+ }
+
+ private static MathMatrix Matrix(XElement m, string command) =>
+ new(command, m.Elements(M + "mr").Select(row => (IReadOnlyList<MathNode>)row.Elements(M + "e").Select(e => (MathNode)Content(e, roman: false)).ToList()).ToList());
+
+ /// <summary>Cases: each line of the equation array split into cells at its alignment marks.</summary>
+ private static MathCases Cases(XElement eqArr)
+ {
+ var rows = new List<IReadOnlyList<MathNode>>();
+ foreach (var line in eqArr.Elements(M + "e"))
+ {
+ var cells = new List<MathNode>();
+ var cell = new List<MathNode>();
+ foreach (var item in Content(line, roman: false).Items)
+ {
+ if (item is MathAlign)
+ {
+ cells.Add(new MathRow(cell));
+ cell = [];
+ }
+ else
+ {
+ cell.Add(item);
+ }
+ }
+ cells.Add(new MathRow(cell));
+ rows.Add(cells);
+ }
+ return new MathCases(rows);
+ }
+
+ private static MathRow WithoutAlign(MathRow row) => new(row.Items.Where(i => i is not MathAlign).ToList());
+
+ /// <summary>The argument elements of a container (properties left out).</summary>
+ private static List<XElement> Arguments(XElement container) =>
+ container.Elements().Where(e => e.Name.Namespace == M && !e.Name.LocalName.EndsWith("Pr", StringComparison.Ordinal)).ToList();
+
+ // ───────────────────────── Text ─────────────────────────
+
+ private enum Style
+ {
+ Italic,
+ Plain,
+ Bold,
+ Normal, // non-math text: upright, spaces kept
+ }
+
+ private static void Run(XElement r, List<MathNode> output, bool roman)
+ {
+ var properties = r.Element(M + "rPr");
+ var style = Flag(properties?.Element(M + "nor")) ? Style.Normal
+ : Val(properties?.Element(M + "sty")) switch
+ {
+ "p" => Style.Plain,
+ "b" or "bi" => Style.Bold,
+ _ => roman ? Style.Plain : Style.Italic,
+ };
+ var text = new StringBuilder();
+ foreach (var child in r.Elements())
+ {
+ if (child.Name == M + "t" || child.Name == W + "t")
+ text.Append(child.Value);
+ else if (child.Name == W + "sym" && int.TryParse((string?)child.Attribute(W + "char"), System.Globalization.NumberStyles.HexNumber, null, out var code))
+ text.Append((char)code);
+ }
+ Text(text.ToString(), output, style);
+ }
+
+ /// <summary>Tokens of a text: letters one by one, numbers, operators, symbols as commands.</summary>
+ private static void Text(string text, List<MathNode> output, Style style)
+ {
+ if (text.Length == 0)
+ return;
+ var upright = style is Style.Plain or Style.Normal;
+ if (upright && Functions.Contains(text.Trim()))
+ {
+ output.Add(new MathFunction(text.Trim()));
+ return;
+ }
+ if (upright && text.Trim() == "lim")
+ {
+ output.Add(new MathLimit(null));
+ return;
+ }
+
+ var items = new List<MathNode>();
+ for (var i = 0; i < text.Length; i++)
+ {
+ var c = text[i];
+ if (char.IsAsciiDigit(c))
+ {
+ var start = i;
+ while (i + 1 < text.Length && (char.IsAsciiDigit(text[i + 1]) || (text[i + 1] == '.' && i + 2 < text.Length && char.IsAsciiDigit(text[i + 2]))))
+ i++;
+ items.Add(new MathNumber(text[start..(i + 1)]));
+ }
+ else if (char.IsAsciiLetter(c))
+ {
+ var start = i;
+ while (i + 1 < text.Length && char.IsAsciiLetter(text[i + 1]))
+ i++;
+ var word = text[start..(i + 1)];
+ if (IsPlainWord(word))
+ items.Add(new MathText(word));
+ else
+ items.AddRange(word.Select(letter => new MathText(letter.ToString())));
+ }
+ else if (c is ' ' or '\u00A0' or '\u2009' or '\u2005' or '\u2006' or '\u200A')
+ {
+ if (style == Style.Normal)
+ items.Add(new MathSpace());
+ }
+ else if (c == '&')
+ {
+ items.Add(new MathAlign());
+ }
+ else if (c is '\u2212' or '\u2013')
+ {
+ items.Add(new MathSymbol("-"));
+ }
+ else if (c is '+' or '-' or '=' or '<' or '>' or ',' or '.' or '!' or '|' or '/' or '*' or ':' or '\'' or '(' or ')' or '[' or ']')
+ {
+ items.Add(new MathSymbol(c.ToString()));
+ }
+ else if (Commands.TryGetValue(c, out var command))
+ {
+ items.Add(new MathCommand(command, c.ToString()));
+ }
+ else if (BigOperators.TryGetValue(c.ToString(), out var big))
+ {
+ items.Add(new MathBigOperator(big, c.ToString(), null, null));
+ }
+ else if (c is '#' or '_' or '^' or '`')
+ {
+ items.Add(new MathQuoted(c.ToString()));
+ }
+ else if (c == '"' || char.IsControl(c) || c == '\u200B')
+ {
+ // Quote marks would end a quoted text; zero-width and control characters show nothing.
+ }
+ else if (char.IsHighSurrogate(c) && i + 1 < text.Length)
+ {
+ items.Add(new MathText(MathAlphanumeric(char.ConvertToUtf32(c, text[i + 1]))));
+ i++;
+ }
+ else
+ {
+ items.Add(new MathText(c.ToString()));
+ }
+ }
+
+ if (style is Style.Plain or Style.Normal or Style.Bold && items.Any(i => i is MathText))
+ output.Add(new MathStyled(style == Style.Bold ? "bold" : "rm", new MathRow(items)));
+ else
+ output.AddRange(items);
+ }
+
+ /// <summary>
+ /// Mathematical alphanumeric symbols (U+1D400…, italic 𝑥 from some converters) → the plain letter or digit; the
+ /// equation's own style makes them italic or bold.
+ /// </summary>
+ private static string MathAlphanumeric(int codePoint)
+ {
+ if (codePoint is >= 0x1D400 and <= 0x1D6A3)
+ {
+ var index = (codePoint - 0x1D400) % 52;
+ return ((char)(index < 26 ? 'A' + index : 'a' + index - 26)).ToString();
+ }
+ if (codePoint is >= 0x1D7CE and <= 0x1D7FF)
+ return ((char)('0' + (codePoint - 0x1D7CE) % 10)).ToString();
+ return char.ConvertFromUtf32(codePoint);
+ }
+
+ // ───────────────────────── Helpers ─────────────────────────
+
+ private static string? Val(XElement? element) => (string?)element?.Attribute(M + "val");
+
+ /// <summary>An on/off property: present without a value, or with 1 / on / true.</summary>
+ private static bool Flag(XElement? element) => element is not null && Val(element) is null or "1" or "on" or "true";
+
+ private static bool IsEmpty(MathRow row) => row.Items.All(i => i is MathRow inner ? IsEmpty(inner) : i is MathAlign);
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/EquationScript.cs b/src/Filee.Engines/Hwp/Hwpx/EquationScript.cs
new file mode 100644
index 00000000..8acdaff5
--- /dev/null
+++ b/src/Filee.Engines/Hwp/Hwpx/EquationScript.cs
@@ -0,0 +1,739 @@
+// Equations for 한글 (hp:equation): a small math tree that readers build (DOCX math, see Docx/OmmlReader), written as
+// 한글's equation script (Equation Version 60, e.g. "{a} over {b}", "sqrt {x}", "SUM _{i=1} ^{n}"), as linear text
+// ("(a)/(b)", "√(x)") for formats without equations, and measured for the equation's box.
+//
+// The box: 한글 stores the size an equation was laid out at (hp:sz), and rhwp stretches the drawing to that width when
+// it renders the document (to PDF), so a box that is too wide or too narrow distorts the equation. Measure follows
+// rhwp's own equation layout (rhwp 0.8.7, src/renderer/equation/layout.rs, MIT): its estimated character widths,
+// script scale 0.7, fraction, root, bracket and matrix spacing. rhwp then draws the equation at its natural width.
+// 한글 lays the script out again when the equation is edited.
+//
+// The script is written so that 한글 and rhwp read the same tree from it: every token is separated by a space,
+// variables are written one letter at a time (so "in", "ln" or "max" in a subscript never become commands), groups
+// are braced, and only commands that both know are used.
+
+using System.Text;
+
+namespace Filee.Engines.Hwp.Hwpx;
+
+internal abstract record MathNode;
+
+/// <summary>Items side by side.</summary>
+internal sealed record MathRow(IReadOnlyList<MathNode> Items) : MathNode
+{
+ public static readonly MathRow Empty = new([]);
+}
+
+/// <summary>One character of a variable or text: italic Latin letters, upright CJK.</summary>
+internal sealed record MathText(string Text) : MathNode;
+
+internal sealed record MathNumber(string Digits) : MathNode;
+
+/// <summary>An ASCII operator or bracket written as it is: + - = &lt; &gt; ( ) [ ] , . / | ! * : '</summary>
+internal sealed record MathSymbol(string Text) : MathNode;
+
+/// <summary>A symbol written as a command: Greek letters, TIMES, LEQ, INF, rarrow, LBRACE ...</summary>
+internal sealed record MathCommand(string Command, string Glyph) : MathNode;
+
+/// <summary>A text written in quotes (characters with a meaning in the script: # &amp; _ ^).</summary>
+internal sealed record MathQuoted(string Text) : MathNode;
+
+/// <summary>A function name 한글 writes upright by itself: sin, log, max ...</summary>
+internal sealed record MathFunction(string Name) : MathNode;
+
+/// <summary>A fraction, or one part above the other without a bar (ATOP).</summary>
+internal sealed record MathFraction(MathNode Numerator, MathNode Denominator, bool Bar = true) : MathNode;
+
+/// <summary>Square root, or a root with an index.</summary>
+internal sealed record MathRoot(MathNode? Index, MathNode Body) : MathNode;
+
+/// <summary>Subscript and / or superscript.</summary>
+internal sealed record MathScripts(MathNode Base, MathNode? Sub, MathNode? Sup) : MathNode;
+
+/// <summary>A large operator with limits: SUM, PROD ... above and below, INT, OINT ... at the side.</summary>
+internal sealed record MathBigOperator(string Command, string Glyph, MathNode? Lower, MathNode? Upper) : MathNode
+{
+ public bool Integral => Glyph is "∫" or "∬" or "∭" or "∮" or "∯" or "∰";
+}
+
+/// <summary>lim with what goes under it.</summary>
+internal sealed record MathLimit(MathNode? Lower) : MathNode;
+
+/// <param name="Command">matrix, pmatrix (round brackets), bmatrix (square) or dmatrix (bars).</param>
+internal sealed record MathMatrix(string Command, IReadOnlyList<IReadOnlyList<MathNode>> Rows) : MathNode;
+
+/// <summary>Cases: rows of cells after one large left brace.</summary>
+internal sealed record MathCases(IReadOnlyList<IReadOnlyList<MathNode>> Rows) : MathNode;
+
+/// <summary>Lines stacked and centred (PILE).</summary>
+internal sealed record MathPile(IReadOnlyList<MathNode> Rows) : MathNode;
+
+/// <summary>Brackets that grow with their content (LEFT ... RIGHT); an empty side has no bracket.</summary>
+internal sealed record MathBrackets(string Left, string Right, MathNode Body) : MathNode;
+
+/// <summary>A mark over (or a line under) the content: hat, bar, vec, tilde, OVERLINE, UNDERLINE ...</summary>
+internal sealed record MathAccent(string Command, MathNode Body) : MathNode;
+
+/// <summary>Upright (rm) or bold content.</summary>
+internal sealed record MathStyled(string Command, MathNode Body) : MathNode;
+
+/// <summary>A normal space (~).</summary>
+internal sealed record MathSpace : MathNode;
+
+/// <summary>An alignment mark (&amp;) of a Word equation array: the cell boundary of cases, nothing elsewhere.</summary>
+internal sealed record MathAlign : MathNode;
+
+/// <summary>Width, height and baseline (from the top) of laid out math.</summary>
+internal readonly record struct MathBox(double Width, double Height, double Baseline);
+
+internal static class EquationScript
+{
+ // rhwp's layout constants (fractions of the font size).
+ private const double ScriptScale = 0.7;
+ private const double FractionPad = 0.2;
+ private const double FractionLine = 0.04;
+ private const double RootPad = 0.1;
+ private const double BracketPad = 0.08;
+ private const double BigOperatorScale = 1.5;
+ private const double IntegralScale = 2.5;
+ private const double BigOperatorTrail = 0.45;
+ private const double MatrixColumnGap = 0.8;
+ private const double MatrixRowGap = 0.3;
+ private const double Axis = 0.25;
+
+ // ───────────────────────── Script ─────────────────────────
+
+ /// <summary>The 한글 equation script of <paramref name="node"/>.</summary>
+ public static string Script(MathNode node)
+ {
+ var sb = new StringBuilder();
+ Write(node, sb);
+ return Collapse(sb.ToString());
+ }
+
+ /// <summary>One space between tokens and none inside the braces of a group ("x _{i}"), quoted text left alone.</summary>
+ private static string Collapse(string script)
+ {
+ var sb = new StringBuilder(script.Length);
+ var quoted = false;
+ foreach (var ch in script)
+ {
+ if (ch == '"')
+ quoted = !quoted;
+ if (!quoted && ch == ' ' && (sb.Length == 0 || sb[^1] is ' ' or '{'))
+ continue;
+ if (!quoted && ch == '}' && sb.Length > 0 && sb[^1] == ' ')
+ sb.Length--;
+ sb.Append(ch);
+ }
+ return sb.ToString().Trim();
+ }
+
+ private static void Write(MathNode node, StringBuilder sb)
+ {
+ switch (node)
+ {
+ case MathRow row:
+ for (var i = 0; i < row.Items.Count; i++)
+ {
+ sb.Append(' ');
+ if (row.Items[i] is MathRow inner)
+ Group(inner, sb);
+ else
+ Write(row.Items[i], sb);
+ }
+ break;
+ case MathText text:
+ sb.Append(' ').Append(text.Text).Append(' ');
+ break;
+ case MathNumber number:
+ sb.Append(' ').Append(number.Digits).Append(' ');
+ break;
+ case MathSymbol symbol:
+ sb.Append(' ').Append(symbol.Text).Append(' ');
+ break;
+ case MathCommand command:
+ sb.Append(' ').Append(command.Command).Append(' ');
+ break;
+ case MathQuoted quoted:
+ sb.Append(" \"").Append(quoted.Text.Replace('"', '\'')).Append("\" ");
+ break;
+ case MathFunction function:
+ sb.Append(' ').Append(function.Name).Append(' ');
+ break;
+ case MathFraction fraction:
+ sb.Append(" {");
+ Group(fraction.Numerator, sb);
+ sb.Append(fraction.Bar ? " over " : " atop ");
+ Group(fraction.Denominator, sb);
+ sb.Append("} ");
+ break;
+ case MathRoot root:
+ if (root.Index is null)
+ {
+ sb.Append(" sqrt ");
+ }
+ else
+ {
+ sb.Append(" root ");
+ Group(root.Index, sb);
+ sb.Append(" of ");
+ }
+ Group(root.Body, sb);
+ break;
+ case MathScripts scripts:
+ if (IsAtom(scripts.Base))
+ Write(scripts.Base, sb);
+ else
+ Group(scripts.Base, sb);
+ if (scripts.Sub is not null)
+ {
+ sb.Append(" _");
+ Group(scripts.Sub, sb);
+ }
+ if (scripts.Sup is not null)
+ {
+ sb.Append(" ^");
+ Group(scripts.Sup, sb);
+ }
+ sb.Append(' ');
+ break;
+ case MathBigOperator big:
+ sb.Append(' ').Append(big.Command);
+ if (big.Lower is not null)
+ {
+ sb.Append(" _");
+ Group(big.Lower, sb);
+ }
+ if (big.Upper is not null)
+ {
+ sb.Append(" ^");
+ Group(big.Upper, sb);
+ }
+ sb.Append(' ');
+ break;
+ case MathLimit limit:
+ sb.Append(" lim ");
+ if (limit.Lower is not null)
+ {
+ sb.Append('_');
+ Group(limit.Lower, sb);
+ }
+ sb.Append(' ');
+ break;
+ case MathMatrix matrix:
+ sb.Append(' ').Append(matrix.Command).Append(" {");
+ Cells(matrix.Rows, sb);
+ sb.Append("} ");
+ break;
+ case MathCases cases:
+ sb.Append(" cases {");
+ Cells(cases.Rows, sb);
+ sb.Append("} ");
+ break;
+ case MathPile pile:
+ sb.Append(" pile {");
+ for (var i = 0; i < pile.Rows.Count; i++)
+ {
+ if (i > 0)
+ sb.Append(" # ");
+ Write(pile.Rows[i], sb);
+ }
+ sb.Append("} ");
+ break;
+ case MathBrackets brackets:
+ sb.Append(" LEFT ").Append(BracketToken(brackets.Left)).Append(' ');
+ Write(brackets.Body, sb);
+ sb.Append(" RIGHT ").Append(BracketToken(brackets.Right)).Append(' ');
+ break;
+ case MathAccent accent:
+ sb.Append(' ').Append(accent.Command).Append(' ');
+ Group(accent.Body, sb);
+ break;
+ case MathStyled styled:
+ // Braced so the style ends with the content (rm and bold switch the rest of a group in 한글).
+ sb.Append(" {").Append(styled.Command).Append(' ');
+ Group(styled.Body, sb);
+ sb.Append("} ");
+ break;
+ case MathSpace:
+ sb.Append(" ~ ");
+ break;
+ case MathAlign:
+ break;
+ }
+ }
+
+ private static void Group(MathNode node, StringBuilder sb)
+ {
+ sb.Append('{');
+ if (node is MathRow row)
+ Write(row, sb);
+ else
+ Write(node, sb);
+ sb.Append('}');
+ }
+
+ private static void Cells(IReadOnlyList<IReadOnlyList<MathNode>> rows, StringBuilder sb)
+ {
+ for (var r = 0; r < rows.Count; r++)
+ {
+ if (r > 0)
+ sb.Append(" # ");
+ for (var c = 0; c < rows[r].Count; c++)
+ {
+ if (c > 0)
+ sb.Append(" & ");
+ Write(rows[r][c], sb);
+ }
+ }
+ }
+
+ /// <summary>A base that takes scripts without braces: one letter, number, symbol command or function name.</summary>
+ private static bool IsAtom(MathNode node) => node is MathText or MathNumber or MathCommand or MathFunction;
+
+ private static string BracketToken(string bracket) => bracket switch
+ {
+ "" => ".",
+ "{" => "LBRACE",
+ "}" => "RBRACE",
+ "⟨" or "〈" => "LANGLE",
+ "⟩" or "〉" => "RANGLE",
+ "⌈" => "LCEIL",
+ "⌉" => "RCEIL",
+ "⌊" => "LFLOOR",
+ "⌋" => "RFLOOR",
+ "‖" => "VERT",
+ _ => bracket,
+ };
+
+ /// <summary>Brackets <see cref="MathBrackets"/> can hold; others are written as text inside.</summary>
+ public static bool IsBracket(string bracket) =>
+ bracket is "" or "(" or ")" or "[" or "]" or "{" or "}" or "|" or "⟨" or "⟩" or "〈" or "〉" or "⌈" or "⌉" or "⌊" or "⌋" or "‖";
+
+ // ───────────────────────── Linear text ─────────────────────────
+
+ /// <summary>The equation as one line of text, for formats without equations: "(a+b)/(2c)", "x_i^2", "√(x)".</summary>
+ public static string Linear(MathNode node)
+ {
+ var sb = new StringBuilder();
+ Linear(node, sb);
+ return sb.ToString();
+ }
+
+ private static void Linear(MathNode node, StringBuilder sb)
+ {
+ switch (node)
+ {
+ case MathRow row:
+ foreach (var item in row.Items)
+ Linear(item, sb);
+ break;
+ case MathText text:
+ sb.Append(text.Text);
+ break;
+ case MathNumber number:
+ sb.Append(number.Digits);
+ break;
+ case MathSymbol symbol:
+ sb.Append(symbol.Text);
+ break;
+ case MathCommand command:
+ sb.Append(command.Glyph);
+ break;
+ case MathQuoted quoted:
+ sb.Append(quoted.Text);
+ break;
+ case MathFunction function:
+ sb.Append(function.Name).Append(' ');
+ break;
+ case MathFraction fraction:
+ LinearOperand(fraction.Numerator, sb);
+ sb.Append(fraction.Bar ? "/" : " ");
+ LinearOperand(fraction.Denominator, sb);
+ break;
+ case MathRoot root:
+ if (root.Index is not null)
+ {
+ sb.Append('[');
+ Linear(root.Index, sb);
+ sb.Append(']');
+ }
+ sb.Append('√');
+ LinearOperand(root.Body, sb);
+ break;
+ case MathScripts scripts:
+ Linear(scripts.Base, sb);
+ LinearScripts(scripts.Sub, scripts.Sup, sb);
+ break;
+ case MathBigOperator big:
+ sb.Append(big.Glyph);
+ LinearScripts(big.Lower, big.Upper, sb);
+ sb.Append(' ');
+ break;
+ case MathLimit limit:
+ sb.Append("lim");
+ LinearScripts(limit.Lower, null, sb);
+ sb.Append(' ');
+ break;
+ case MathMatrix matrix:
+ {
+ var (open, close) = matrix.Command switch
+ {
+ "pmatrix" => ("(", ")"),
+ "bmatrix" => ("[", "]"),
+ "dmatrix" => ("|", "|"),
+ _ => ("[", "]"),
+ };
+ sb.Append(open);
+ LinearCells(matrix.Rows, ", ", sb);
+ sb.Append(close);
+ break;
+ }
+ case MathCases cases:
+ sb.Append('{');
+ LinearCells(cases.Rows, " ", sb);
+ break;
+ case MathPile pile:
+ for (var i = 0; i < pile.Rows.Count; i++)
+ {
+ if (i > 0)
+ sb.Append("; ");
+ Linear(pile.Rows[i], sb);
+ }
+ break;
+ case MathBrackets brackets:
+ sb.Append(brackets.Left);
+ Linear(brackets.Body, sb);
+ sb.Append(brackets.Right);
+ break;
+ case MathAccent accent:
+ {
+ var mark = accent.Command switch
+ {
+ "hat" => "\u0302",
+ "check" => "\u030C",
+ "tilde" => "\u0303",
+ "acute" => "\u0301",
+ "grave" => "\u0300",
+ "dot" => "\u0307",
+ "ddot" => "\u0308",
+ "bar" or "OVERLINE" => "\u0305",
+ "vec" => "\u20D7",
+ "dyad" => "\u20E1",
+ _ => "\u0332", // UNDERLINE, under
+ };
+ var body = Linear(accent.Body);
+ if (body.Length == 1)
+ {
+ sb.Append(body).Append(mark);
+ }
+ else
+ {
+ sb.Append(accent.Command.ToLowerInvariant()).Append('(').Append(body).Append(')');
+ }
+ break;
+ }
+ case MathStyled styled:
+ Linear(styled.Body, sb);
+ break;
+ case MathSpace:
+ sb.Append(' ');
+ break;
+ }
+ }
+
+ private static void LinearScripts(MathNode? sub, MathNode? sup, StringBuilder sb)
+ {
+ if (sub is not null)
+ {
+ sb.Append('_');
+ LinearOperand(sub, sb);
+ }
+ if (sup is not null)
+ {
+ sb.Append('^');
+ LinearOperand(sup, sb);
+ }
+ }
+
+ /// <summary>An operand of /, _ or ^: in brackets unless it is one letter, symbol, number or bracketed group.</summary>
+ private static void LinearOperand(MathNode node, StringBuilder sb)
+ {
+ var text = Linear(node);
+ var single = node is MathRow { Items.Count: 1 } row ? row.Items[0] : node;
+ var simple = single is MathNumber or MathCommand or MathBrackets or MathText { Text.Length: 1 };
+ if (simple || text.Length <= 1)
+ sb.Append(text);
+ else
+ sb.Append('(').Append(text).Append(')');
+ }
+
+ private static void LinearCells(IReadOnlyList<IReadOnlyList<MathNode>> rows, string cellSeparator, StringBuilder sb)
+ {
+ for (var r = 0; r < rows.Count; r++)
+ {
+ if (r > 0)
+ sb.Append("; ");
+ for (var c = 0; c < rows[r].Count; c++)
+ {
+ if (c > 0)
+ sb.Append(cellSeparator);
+ Linear(rows[r][c], sb);
+ }
+ }
+ }
+
+ // ───────────────────────── Size ─────────────────────────
+
+ /// <summary>The box of <paramref name="node"/> at font size <paramref name="size"/> (any unit; the box is in the same unit).</summary>
+ public static MathBox Measure(MathNode node, double size) => node switch
+ {
+ MathRow row => MeasureRow(row.Items, size),
+ MathText text => Character(TextWidth(text.Text, size, italic: !IsCjk(text.Text)), size),
+ MathNumber number => Character(TextWidth(number.Digits, size, false), size),
+ MathSymbol symbol => Character(TextWidth(symbol.Text, size, false)
+ + 2 * size * (symbol.Text is "+" or "-" or "=" or "<" or ">" ? 0.15 : 0.05), size),
+ MathCommand command => Character(TextWidth(command.Glyph, size, false), size),
+ MathQuoted quoted => Character(TextWidth(quoted.Text, size, false), size),
+ MathFunction function => Character(TextWidth(function.Name, size, false) + size * 0.02, size),
+ MathFraction fraction => MeasureFraction(fraction, size),
+ MathRoot root => MeasureRoot(root, size),
+ MathScripts scripts => MeasureScripts(Measure(scripts.Base, size), scripts.Sub, scripts.Sup, size),
+ MathBigOperator big => big.Integral ? MeasureIntegral(big, size) : MeasureBigOperator(big, size),
+ MathLimit limit => MeasureLimit(limit, size),
+ MathMatrix matrix => MeasureMatrix(matrix, size),
+ MathCases cases => MeasureCases(cases, size),
+ MathPile pile => MeasurePile(pile, size),
+ MathBrackets brackets => MeasureBrackets(brackets, size),
+ MathAccent accent => Raise(Measure(accent.Body, size), size * 0.25),
+ MathStyled styled => Measure(styled.Body, size),
+ MathSpace => Character(size * 0.33, size),
+ MathTab => Character(size, size),
+ _ => default,
+ };
+
+ private static MathBox Character(double width, double size) => new(width, size, size * 0.8);
+
+ /// <summary>Room above the content for an accent mark.</summary>
+ private static MathBox Raise(MathBox body, double room) => new(body.Width, body.Height + room, body.Baseline + room);
+
+ /// <summary>A group as rhwp parses it: an empty group is nothing, a group of one item is that item.</summary>
+ private static MathBox MeasureRow(IReadOnlyList<MathNode> items, double size)
+ {
+ var parts = items.Where(i => i is not MathAlign).ToList();
+ if (parts.Count == 0)
+ return default;
+ if (parts.Count == 1)
+ return Measure(parts[0], size);
+ var boxes = parts.Select(i => Measure(i, size)).Where(b => b.Width > 0).ToList();
+ if (boxes.Count == 0)
+ return new MathBox(0, size, size * 0.8);
+ var ascent = boxes.Max(b => b.Baseline);
+ var descent = boxes.Max(b => b.Height - b.Baseline);
+ return new MathBox(boxes.Sum(b => b.Width), ascent + descent, ascent);
+ }
+
+ private static MathBox MeasureFraction(MathFraction fraction, double size)
+ {
+ var n = Measure(fraction.Numerator, size);
+ var d = Measure(fraction.Denominator, size);
+ var pad = size * FractionPad;
+ var width = Math.Max(n.Width, d.Width) + pad * 2;
+ var top = n.Height + pad;
+ var bottom = d.Height + pad;
+ if (!fraction.Bar)
+ return new MathBox(width, top + bottom, top + size * Axis);
+ var line = size * FractionLine;
+ return new MathBox(width, top + line + bottom, top + line / 2 + size * Axis);
+ }
+
+ private static MathBox MeasureRoot(MathRoot root, double size)
+ {
+ var body = Measure(root.Body, size);
+ var pad = size * RootPad;
+ var sign = size * 0.6;
+ var index = root.Index is null ? 0 : Measure(root.Index, size * ScriptScale).Width;
+ var bodyWidth = body.Width + pad;
+ return new MathBox(Math.Max(index, sign * 0.5) + sign * 0.5 + bodyWidth, body.Height + pad * 2, pad + body.Baseline);
+ }
+
+ private static MathBox MeasureScripts(MathBox b, MathNode? subNode, MathNode? supNode, double size)
+ {
+ if (subNode is null && supNode is null)
+ return b;
+ if (subNode is null)
+ {
+ var s = Measure(supNode!, size * ScriptScale);
+ var shift = b.Baseline - s.Height * 0.7;
+ var baseY = shift >= 0 ? Math.Max(s.Height - b.Height, 0) : -shift;
+ return new MathBox(b.Width + s.Width, Math.Max(baseY + b.Height, s.Height), baseY + b.Baseline);
+ }
+ if (supNode is null)
+ {
+ var s = Measure(subNode, size * ScriptScale);
+ var shift = b.Baseline * 0.4;
+ return new MathBox(b.Width + s.Width, Math.Max(b.Height, shift + s.Height), b.Baseline);
+ }
+
+ var sub = Measure(subNode, size * ScriptScale);
+ var sup = Measure(supNode, size * ScriptScale);
+ var supShift = b.Baseline - sup.Height * 0.7;
+ var subShift = b.Baseline * 0.4;
+ var ascent = supShift < 0 ? sup.Height - Math.Abs(supShift) : Math.Max(sup.Height, 0);
+ var top = Math.Abs(Math.Min(supShift, 0));
+ var height = Math.Max(Math.Max(top + b.Height, top + subShift + sub.Height), ascent + b.Height);
+ var y = Math.Max(top, supShift > 0 ? 0 : Math.Max(sup.Height - Math.Abs(supShift) - b.Baseline, 0));
+ height = Math.Max(Math.Max(height, y + b.Height), y + subShift + sub.Height);
+ return new MathBox(b.Width + Math.Max(sup.Width, sub.Width), height, y + b.Baseline);
+ }
+
+ private static MathBox MeasureBigOperator(MathBigOperator big, double size)
+ {
+ var opSize = size * BigOperatorScale;
+ var opWidth = TextWidth(big.Glyph, opSize, false);
+ var lower = big.Lower is null ? (MathBox?)null : Measure(big.Lower, size * ScriptScale);
+ var upper = big.Upper is null ? (MathBox?)null : Measure(big.Upper, size * ScriptScale);
+ var upperHeight = upper is { } u ? u.Height + size * 0.05 : 0;
+ var lowerHeight = lower is { } l ? l.Height + size * 0.05 : 0;
+ var width = Math.Max(opWidth, Math.Max(lower?.Width ?? 0, upper?.Width ?? 0));
+ return new MathBox(width + size * BigOperatorTrail, upperHeight + opSize + lowerHeight, upperHeight + opSize * 0.6);
+ }
+
+ /// <summary>
+ /// An integral is a large symbol (INT) whose limits are ordinary scripts: rhwp places both limits next to the drawn
+ /// sign, one limit as a sub- or superscript of the sign.
+ /// </summary>
+ private static MathBox MeasureIntegral(MathBigOperator integral, double size)
+ {
+ var height = size * IntegralScale;
+ var glyphWidth = size * 0.52;
+ var sign = new MathBox(glyphWidth + size * BigOperatorTrail, height, height * 0.7);
+ if (integral.Lower is null || integral.Upper is null)
+ return MeasureScripts(sign, integral.Lower, integral.Upper, size);
+
+ var sub = Measure(integral.Lower, size * ScriptScale);
+ var sup = Measure(integral.Upper, size * ScriptScale);
+ var gap = size * 0.22;
+ var topY = height * 0.04;
+ var bottomY = height * 0.96;
+ var head = Math.Max(-(topY - sup.Height * 0.30), 0);
+ var supX = size * 0.50 + gap;
+ var subX = size * 0.04 + gap;
+ var supY = head + topY - sup.Height * 0.30;
+ var subY = head + bottomY - sub.Height * 0.72;
+ var right = Math.Max(Math.Max(supX + sup.Width, subX + sub.Width), glyphWidth);
+ var total = Math.Max(Math.Max(subY + sub.Height, head + height), supY + sup.Height);
+ return new MathBox(right + size * BigOperatorTrail, total, head + height * 0.7);
+ }
+
+ private static MathBox MeasureLimit(MathLimit limit, double size)
+ {
+ var nameWidth = TextWidth("lim", size, false);
+ if (limit.Lower is null)
+ return new MathBox(nameWidth, size, size * 0.8);
+ var lower = Measure(limit.Lower, size * ScriptScale);
+ return new MathBox(Math.Max(nameWidth, lower.Width), size + lower.Height + size * 0.05, size * 0.8);
+ }
+
+ private static MathBox MeasureMatrix(MathMatrix matrix, double size)
+ {
+ if (matrix.Rows.Count == 0)
+ return new MathBox(0, size, size * 0.8);
+ var cells = matrix.Rows.Select(r => r.Select(c => Measure(c, size)).ToList()).ToList();
+ var columns = cells.Max(r => r.Count);
+ var widths = new double[columns];
+ foreach (var row in cells)
+ {
+ for (var c = 0; c < row.Count; c++)
+ widths[c] = Math.Max(widths[c], row[c].Width);
+ }
+ var height = cells.Sum(r => r.Select(c => c.Height).Append(size).Max()) + size * MatrixRowGap * (cells.Count - 1);
+ var width = widths.Sum() + size * MatrixColumnGap * Math.Max(0, columns - 1);
+ var brackets = matrix.Command == "matrix" ? 0 : size * 0.3;
+ return new MathBox(width + brackets * 2 + size * 0.2 * 2, height, height / 2);
+ }
+
+ private static MathBox MeasureCases(MathCases cases, double size)
+ {
+ var rows = cases.Rows.Select(r => MeasureRow(CaseRow(r), size)).ToList();
+ var height = rows.Sum(r => r.Height) + size * MatrixRowGap * Math.Max(0, rows.Count - 1);
+ var width = rows.Select(r => r.Width).DefaultIfEmpty(0).Max() + size * 0.6;
+ return new MathBox(width + size * 0.3, height, height / 2);
+ }
+
+ /// <summary>A row of cases as rhwp reads it: the cells with a tab (&amp;) between them.</summary>
+ private static List<MathNode> CaseRow(IReadOnlyList<MathNode> cells)
+ {
+ var items = new List<MathNode>();
+ for (var c = 0; c < cells.Count; c++)
+ {
+ if (c > 0)
+ items.Add(new MathTab());
+ items.AddRange(cells[c] is MathRow row ? row.Items : [cells[c]]);
+ }
+ return items;
+ }
+
+ /// <summary>The tab rhwp makes of &amp; in cases: one font size wide.</summary>
+ private sealed record MathTab : MathNode;
+
+ private static MathBox MeasurePile(MathPile pile, double size)
+ {
+ var rows = pile.Rows.Select(r => Measure(r, size)).ToList();
+ var height = rows.Sum(r => r.Height) + size * MatrixRowGap * Math.Max(0, rows.Count - 1);
+ return new MathBox(rows.Select(r => r.Width).DefaultIfEmpty(0).Max(), height, height / 2);
+ }
+
+ private static MathBox MeasureBrackets(MathBrackets brackets, double size)
+ {
+ var body = Measure(brackets.Body, size);
+ var stretch = body.Height > size * 1.2 && brackets.Left == "(" && brackets.Right == ")";
+ var pad = stretch ? size * 0.03 : size * BracketPad;
+ var bracket = stretch ? size * 0.27 : size * 0.333;
+ var left = brackets.Left.Length == 0 ? 0 : bracket;
+ var right = brackets.Right.Length == 0 ? 0 : bracket;
+ return new MathBox(left + pad + body.Width + pad + right, body.Height, body.Baseline);
+ }
+
+ private static bool IsCjk(string text) =>
+ text.Any(c => c is >= '\u3000' and <= '\u9FFF' or >= '\uF900' and <= '\uFAFF' or >= '\uAC00' and <= '\uD7AF');
+
+ /// <summary>rhwp's estimate of a text's width.</summary>
+ internal static double TextWidth(string text, double size, bool italic)
+ {
+ var width = 0.0;
+ foreach (var rune in text.EnumerateRunes())
+ width += size * CharacterWidth(rune.Value);
+ return italic ? width * 1.05 : width;
+ }
+
+ private static double CharacterWidth(int c)
+ {
+ if (c < 0x80)
+ return c is >= 'A' and <= 'Z' ? 0.65 : c is >= 'a' and <= 'z' or >= '0' and <= '9' ? 0.55 : 0.5;
+ return c switch
+ {
+ '′' or '″' or '‴' => 0.3,
+ >= 'α' and <= 'ω' or 'ϑ' or 'ϖ' => 0.55,
+ >= 'Α' and <= 'Ω' or 'ϒ' => 0.65,
+ '±' or '∓' or '×' or '÷' or '·' or '∘' or '†' or '‡' or '•' => 0.6,
+ '≠' or '≤' or '≥' or '≈' or '≡' or '≅' or '∼' or '≃' or '≍' or '≐' or '∝' or '≺' or '≻' => 0.7,
+ '∈' or '∉' or '∋' or '⊂' or '⊃' or '⊆' or '⊇' or '∀' or '∃' or '¬' or '∧' or '∨' => 0.65,
+ '⊏' or '⊐' or '⊑' or '⊒' or '⊻' or '⊢' or '⊣' or '⊨' => 0.65,
+ '∫' or '∬' or '∭' or '∮' or '∯' or '∰' => 0.5,
+ '∑' or '∏' or '∐' => 0.8,
+ '∪' or '∩' or '⊔' or '⊓' or '⊎' or '⋀' or '⋁' => 0.7,
+ '⊕' or '⊗' or '⊙' or '⊖' or '⊘' => 0.7,
+ >= '←' and <= '↕' or >= '⇐' and <= '⇕' or '↖' or '↗' or '↘' or '↙' or '↦' or '↩' or '↪' => 0.8,
+ '⋯' or '…' or '⋮' or '⋱' => 0.8,
+ '∂' or '∅' or '∇' or '∞' or '∠' or '∡' or '∢' or '⊾' => 0.6,
+ '⊥' or '⊤' or '°' or '‰' or '‱' or '♯' => 0.5,
+ 'ℵ' or 'ℏ' or 'ı' or 'ȷ' or 'ℓ' or '℘' or 'ℑ' or 'ℜ' or 'ℒ' or 'Å' or '℧' => 0.6,
+ '℃' or '℉' => 0.9,
+ '△' or '▽' or '○' or '◇' or '⋄' => 0.7,
+ >= 0x3000 and <= 0x9FFF or >= 0xF900 and <= 0xFAFF or >= 0xAC00 and <= 0xD7AF => 1.0,
+ _ => 0.6,
+ };
+ }
+}
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
index 7dc3dbdc..0002f6d9 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxModel.cs
@@ -191,12 +191,21 @@ internal readonly record struct HBorders(HBorder Left, HBorder Right, HBorder To
internal abstract class HInline;
-internal sealed class HText(string text, HCharFormat format) : HInline
+internal class HText(string text, HCharFormat format) : HInline
{
public string Text { get; } = text;
public HCharFormat Format { get; } = format;
}
+/// <summary>
+/// An equation (from Word math): a 한글 equation object in HWPX. It is text too, its linear form ("(a)/(b)", "x^2"),
+/// which the writers without equations (HTML, EPUB, Markdown, plain text) write instead.
+/// </summary>
+internal sealed class HEquation(MathNode math, HCharFormat format) : HText(EquationScript.Linear(math), format)
+{
+ public MathNode Math { get; } = math;
+}
+
internal sealed class HLineBreak(HCharFormat format) : HInline
{
public HCharFormat Format { get; } = format;
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
index 16da0507..d33c669b 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Body.cs
@@ -223,6 +223,10 @@ internal sealed partial class HwpxWriter
{
switch (inline)
{
+ case HEquation equation:
+ runs.Control(CharPr(charPrBase, equation.Format, link), Equation(equation, charPrBase), isObject: true);
+ _plainText.Append(equation.Text);
+ break;
case HText text:
runs.Text(CharPr(charPrBase, text.Format, link), Escape(text.Text));
_plainText.Append(text.Text);
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
index 9018d333..8b3e574c 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Layout.cs
@@ -187,7 +187,13 @@ internal sealed partial class HwpxWriter
if (inline is HLink link)
Flatten(link.Content);
else
- pieces.Add((inline, inline is HText text ? TextWidth(text.Text, text.Format.Size ?? size) : 0));
+ pieces.Add((inline, inline switch
+ {
+ // An equation is as wide as its box and margins (a centred display equation between tabs).
+ HEquation equation => EquationScript.Measure(equation.Math, equation.Format.Size ?? size).Width + 2 * EquationMargin,
+ HText text => TextWidth(text.Text, text.Format.Size ?? size),
+ _ => 0,
+ }));
}
}
Flatten(paragraph.Inlines);
diff --git a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
index 3fe3a7d9..d89c3152 100644
--- a/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
+++ b/src/Filee.Engines/Hwp/Hwpx/HwpxWriter.Objects.cs
@@ -85,6 +85,34 @@ internal sealed partial class HwpxWriter
"</hp:pic>";
}
+ // ───────────────────────── Equations ─────────────────────────
+
+ /// <summary>Space left and right of an equation (as 한글 inserts them).</summary>
+ private const int EquationMargin = 56;
+
+ /// <summary>
+ /// A 한글 equation laid out like a character. The box is the size rhwp lays the script out at (see
+ /// EquationScript), so it draws the equation unstretched; baseLine is where the text line runs, in percent of the
+ /// height from the top.
+ /// </summary>
+ private string Equation(HEquation equation, string charPrBase)
+ {
+ var size = Math.Max(100, equation.Format.Size ?? BaseSize(charPrBase));
+ var box = EquationScript.Measure(equation.Math, size);
+ var width = Math.Max(1, (int)Math.Ceiling(box.Width));
+ var height = Math.Max(1, (int)Math.Ceiling(box.Height));
+ var baseline = box.Height > 0 ? Math.Clamp((int)Math.Round(box.Baseline * 100 / box.Height), 0, 100) : 85;
+ var id = NextId();
+ return $"<hp:equation id=\"{id}\" zOrder=\"{_zOrder++}\" numberingType=\"EQUATION\" textWrap=\"TOP_AND_BOTTOM\" textFlow=\"BOTH_SIDES\" lock=\"0\" dropcapstyle=\"None\" " +
+ $"version=\"Equation Version 60\" baseLine=\"{baseline}\" textColor=\"{equation.Format.Color ?? "#000000"}\" baseUnit=\"{size}\" lineMode=\"CHAR\" font=\"HYhwpEQ\">" +
+ $"<hp:sz width=\"{width}\" widthRelTo=\"ABSOLUTE\" height=\"{height}\" heightRelTo=\"ABSOLUTE\" protect=\"0\"/>" +
+ Position(null) +
+ // The comment (alternative text) is the linear form. Never an empty element: rhwp reads an empty
+ // <hp:shapeComment/> of an equation up to the next closing tag and loses the rest of the section.
+ $"<hp:outMargin left=\"{EquationMargin}\" right=\"{EquationMargin}\" top=\"0\" bottom=\"0\"/><hp:shapeComment>{Escape(equation.Text)}</hp:shapeComment>" +
+ $"<hp:script>{Escape(EquationScript.Script(equation.Math))}</hp:script></hp:equation>";
+ }
+
/// <summary>hp:pos: inline objects are laid out like a character; floating ones use the anchor.</summary>
private string Position(HAnchor? anchor)
{
diff --git a/src/Filee.Engines/Hwp/RhwpInput.cs b/src/Filee.Engines/Hwp/RhwpInput.cs
index 65945fe4..7f249f33 100644
--- a/src/Filee.Engines/Hwp/RhwpInput.cs
+++ b/src/Filee.Engines/Hwp/RhwpInput.cs
@@ -14,6 +14,9 @@
// text, its line is moved up to the paragraph's top (the line minus the table's offset, margins and height):
// nothing is drawn on it, and rhwp then puts the table where 한글 does.
//
+// - Equation lines (#143): in paragraphs without stored lines (Word equations written by Filee) rhwp draws a fraction,
+// matrix or sum partly below its line, over the next line. Those paragraphs get the overhang as space after them.
+//
// rhwp's equation fonts are Latin Modern Math, STIX Two and Times New Roman; without the first two or Arial Unicode MS
// (which Office installs) ∪ ∈ ⊂ ∘ ∼ came out empty, so Cambria Math (part of Windows) is asked for then.
@@ -86,8 +89,15 @@ internal static partial class RhwpInput
changed["Contents/header.xml"] = header;
foreach (var (name, xml) in sections)
+ {
if (FixShapeSizes(xml) | NormaliseEquations(xml) | (fromHwp && AnchorTablesInCells(xml)))
changed[name] = xml;
+ if (SpaceEquationLines(xml, header))
+ {
+ changed[name] = xml;
+ changed["Contents/header.xml"] = header;
+ }
+ }
if (changed.Count == 0)
return null;
@@ -200,6 +210,68 @@ internal static partial class RhwpInput
return changed;
}
+ /// <summary>
+ /// Paragraphs without stored lines (written by Filee) that hold equations: room above and below for what rhwp
+ /// draws outside the line. rhwp makes a line as tall as its tallest equation, puts the line's baseline at 85 % of
+ /// that height and the equation's own baseline on it, so an equation whose baseline is higher (a fraction, a matrix,
+ /// a sum with limits) reaches below the line into the next one. The paragraph gets that much more space after it
+ /// (and before it, for an equation reaching above). True when something changed.
+ /// </summary>
+ internal static bool SpaceEquationLines(XDocument section, XDocument header)
+ {
+ const int MinimumOverhang = 100;
+ var paraProperties = header.Descendants().FirstOrDefault(e => e.Name.LocalName == "paraProperties");
+ if (paraProperties is null)
+ return false;
+ var shapes = paraProperties.Elements().Where(e => e.Name.LocalName == "paraPr").ToDictionary(e => (string?)e.Attribute("id") ?? "");
+ var nextId = shapes.Keys.Select(k => int.TryParse(k, out var id) ? id : 0).DefaultIfEmpty(-1).Max() + 1;
+ var spaced = new Dictionary<(string Id, int Before, int After), string>();
+ var changed = false;
+
+ foreach (var paragraph in section.Descendants().Where(e => e.Name.LocalName == "p" && Child(e, "linesegarray") is null))
+ {
+ var boxes = paragraph.Elements().Where(e => e.Name.LocalName == "run").Elements()
+ .Where(e => e.Name.LocalName == "equation" && (string?)Child(e, "pos")?.Attribute("treatAsChar") == "1")
+ .Select(e => (Height: Number(Child(e, "sz"), "height") ?? 0, Baseline: Number(e, "baseLine") ?? 85))
+ .Where(b => b.Height > 0)
+ .ToList();
+ if (boxes.Count == 0)
+ continue;
+ var line = boxes.Max(b => b.Height);
+ var lineBaseline = line * 0.85;
+ var before = (int)Math.Ceiling(boxes.Max(b => Math.Max(0, b.Height * b.Baseline / 100.0 - lineBaseline)));
+ var after = (int)Math.Ceiling(boxes.Max(b => Math.Max(0, lineBaseline - b.Height * b.Baseline / 100.0 + b.Height - line)));
+ // Less than a point (a subscript in running text) stays in the line spacing.
+ before = before < MinimumOverhang ? 0 : before;
+ after = after < MinimumOverhang ? 0 : after;
+ var id = (string?)paragraph.Attribute("paraPrIDRef") ?? "";
+ if ((before == 0 && after == 0) || !shapes.TryGetValue(id, out var shape))
+ continue;
+
+ if (!spaced.TryGetValue((id, before, after), out var newId))
+ {
+ var copy = new XElement(shape);
+ newId = (nextId++).ToString(System.Globalization.CultureInfo.InvariantCulture);
+ copy.SetAttributeValue("id", newId);
+ foreach (var margin in copy.Descendants().Where(e => e.Name.LocalName is "prev" or "next"))
+ {
+ var extra = margin.Name.LocalName == "prev" ? before : after;
+ // 한글 writes the margins doubled in hp:default (hp:case holds the real values).
+ if (margin.Ancestors().Any(a => a.Name.LocalName == "default"))
+ extra *= 2;
+ margin.SetAttributeValue("value", (Number(margin, "value") ?? 0) + extra);
+ }
+ paraProperties.Add(copy);
+ spaced[(id, before, after)] = newId;
+ }
+ paragraph.SetAttributeValue("paraPrIDRef", newId);
+ changed = true;
+ }
+ if (changed)
+ paraProperties.SetAttributeValue("itemCnt", paraProperties.Elements().Count(e => e.Name.LocalName == "paraPr"));
+ return changed;
+ }
+
private static XElement? Child(XElement? element, string name) => element?.Elements().FirstOrDefault(e => e.Name.LocalName == name);
private static int? Number(XElement? element, string attribute) =>
diff --git a/tests/Filee.Engines.Tests/DocxBuilder.cs b/tests/Filee.Engines.Tests/DocxBuilder.cs
index a17c6ab0..5b2739da 100644
--- a/tests/Filee.Engines.Tests/DocxBuilder.cs
+++ b/tests/Filee.Engines.Tests/DocxBuilder.cs
@@ -18,6 +18,7 @@ internal sealed class DocxBuilder
"xmlns:wpg=\"http://schemas.microsoft.com/office/word/2010/wordprocessingGroup\" " +
"xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\" " +
"xmlns:v=\"urn:schemas-microsoft-com:vml\" " +
+ "xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\" " +
"xmlns:w10=\"urn:schemas-microsoft-com:office:word\"";
/// <summary>A4 portrait, 1 inch margins, header/footer 0.5 inch.</summary>
diff --git a/tests/Filee.Engines.Tests/DocxEquationTests.cs b/tests/Filee.Engines.Tests/DocxEquationTests.cs
new file mode 100644
index 00000000..4e8e573d
--- /dev/null
+++ b/tests/Filee.Engines.Tests/DocxEquationTests.cs
@@ -0,0 +1,222 @@
+// Word equations (Office Math) in DOCX → HWPX, HWP and PDF (#143): every equation becomes a 한글 equation object
+// with an equation script instead of its characters run together ("Jdωg-ωrefdt=..."), sized so that rhwp draws it
+// unstretched, and the text after it still arrives. Formats without equations get a linear form ("(a+b)/(2c)").
+
+using System.Xml.Linq;
+using Filee.Core.Conversion;
+using Filee.Core.Presets;
+using Filee.Engines.Hwp;
+using Filee.Engines.Hwp.Hwpx;
+using Filee.Engines.Hwp.Hwpx.Docx;
+using Filee.Engines.Infrastructure;
+using UglyToad.PdfPig;
+using static Filee.Engines.Tests.DocxBuilder;
+using static Filee.Engines.Tests.HwpxAssert;
+
+namespace Filee.Engines.Tests;
+
+public class DocxEquationTests(EngineFixture fx) : IClassFixture<EngineFixture>
+{
+ // ───────── OMML snippets ─────────
+
+ private static string MR(string text, string sty = "") =>
+ $"<m:r>{(sty.Length > 0 ? $"<m:rPr><m:sty m:val=\"{sty}\"/></m:rPr>" : "")}<m:t>{System.Security.SecurityElement.Escape(text)}</m:t></m:r>";
+
+ private static string Frac(string numerator, string denominator) => $"<m:f><m:num>{numerator}</m:num><m:den>{denominator}</m:den></m:f>";
+
+ private static string Sup(string body, string sup) => $"<m:sSup><m:e>{body}</m:e><m:sup>{sup}</m:sup></m:sSup>";
+
+ private static string Sub(string body, string sub) => $"<m:sSub><m:e>{body}</m:e><m:sub>{sub}</m:sub></m:sSub>";
+
+ private static string SubSup(string body, string sub, string sup) =>
+ $"<m:sSubSup><m:e>{body}</m:e><m:sub>{sub}</m:sub><m:sup>{sup}</m:sup></m:sSubSup>";
+
+ private static string Rad(string body, string degree = "") =>
+ $"<m:rad><m:radPr>{(degree.Length == 0 ? "<m:degHide m:val=\"1\"/>" : "")}</m:radPr><m:deg>{degree}</m:deg><m:e>{body}</m:e></m:rad>";
+
+ private static string Nary(string chr, string sub, string sup, string body) =>
+ $"<m:nary><m:naryPr><m:chr m:val=\"{chr}\"/><m:limLoc m:val=\"undOvr\"/></m:naryPr><m:sub>{sub}</m:sub><m:sup>{sup}</m:sup><m:e>{body}</m:e></m:nary>";
+
+ private static string Delimited(string content, string open = "", string close = "") =>
+ $"<m:d><m:dPr>{(open.Length > 0 ? $"<m:begChr m:val=\"{open}\"/>" : "")}{(close.Length > 0 || open.Length > 0 ? $"<m:endChr m:val=\"{close}\"/>" : "")}</m:dPr><m:e>{content}</m:e></m:d>";
+
+ private static string Matrix(params string[][] rows) =>
+ "<m:m>" + string.Concat(rows.Select(r => "<m:mr>" + string.Concat(r.Select(c => $"<m:e>{c}</m:e>")) + "</m:mr>")) + "</m:m>";
+
+ private static string Math(string content) => $"<m:oMath>{content}</m:oMath>";
+
+ private static string Display(string content) => $"<m:oMathPara><m:oMath>{content}</m:oMath></m:oMathPara>";
+
+ /// <summary>The equations of the issue and of a math class: one display equation per paragraph, then text.</summary>
+ private static readonly (string Omml, string Script, string Linear)[] Samples =
+ [
+ (Frac(MR("a+b"), MR("2c")), "{{a + b} over {2 c}}", "(a+b)/(2c)"),
+ (Sup(MR("x"), MR("2")) + MR("+") + SubSup(MR("y"), MR("i"), MR("n")), "x ^{2} + y _{i} ^{n}", "x^2+y_i^n"),
+ (Rad(Sup(MR("b"), MR("2")) + MR("−4ac")) + MR("+") + Rad(MR("x"), MR("3")), "sqrt {b ^{2} - 4 ac} + root {3} of {x}", "√(b^2-4ac)+[3]√x"),
+ (Nary("∑", MR("i=1"), MR("n"), Sup(MR("i"), MR("2"))), "SUM _{i = 1} ^{n} i ^{2}", "∑_(i=1)^n i^2"),
+ (Nary("∫", MR("0"), MR("∞"), Sup(MR("e"), MR("−") + Sup(MR("x"), MR("2"))) + MR("dx")), "INT _{0} ^{INF} {e ^{- x ^{2}} dx}", "∫_0^∞ e^(-x^2)dx"),
+ (MR("α+β=γ, Ω"), "alpha + beta = gamma , Omega", "α+β=γ,Ω"),
+ (MR("A=") + Delimited(Matrix([MR("1"), MR("2")], [MR("3"), MR("4")])), "A = pmatrix {1 & 2 # 3 & 4}", "A=(1, 2; 3, 4)"),
+ (Sub(MR("ω"), MR("ref")) + MR("+") + Sub(MR("x"), MR("in")) + MR("+") + Delimited(MR("t−1")),
+ "omega _{ref} + x _{i n} + LEFT ( t - 1 RIGHT )", "ω_(ref)+x_(in)+(t-1)"),
+ ("<m:func><m:fName><m:limLow><m:e>" + MR("lim", "p") + "</m:e><m:lim>" + MR("x→0") + "</m:lim></m:limLow></m:fName><m:e>" +
+ Frac("<m:func><m:fName>" + MR("sin", "p") + "</m:fName><m:e>" + MR("x") + "</m:e></m:func>", MR("x")) + "</m:e></m:func>",
+ "lim _{x rarrow 0} {{sin x} over {x}}", "lim_(x→0) (sin x)/x"),
+ ("<m:acc><m:e>" + MR("a") + "</m:e></m:acc>" + MR("+") + "<m:bar><m:barPr><m:pos m:val=\"top\"/></m:barPr><m:e>" + MR("AB") + "</m:e></m:bar>",
+ "hat {a} + OVERLINE {AB}", "â+overline(AB)"),
+ (MR("f(x)=") + Delimited("<m:eqArr><m:e>" + MR("x,&x≥0") + "</m:e><m:e>" + MR("−x,&x<0") + "</m:e></m:eqArr>", "{"),
+ "f ( x ) = cases {x , & x GEQ 0 # - x , & x < 0}", "f(x)={x, x≥0; -x, x<0"),
+ ];
+
+ private DocxBuilder SampleDocument()
+ {
+ var docx = new DocxBuilder();
+ docx.Paragraph(P(R("Inline ") + Math(MR("E=m") + Sup(MR("c"), MR("2"))) + R(" in a sentence.")));
+ foreach (var (omml, _, _) in Samples)
+ docx.Paragraph(P(Display(omml)));
+ docx.Paragraph(P(R("Text after the equations.")));
+ return docx;
+ }
+
+ private async Task<string> ConvertAsync(DocxBuilder docx, string name, string target)
+ {
+ var path = docx.Save(Path.Combine(fx.NewFolder(), name + ".docx"));
+ var job = await fx.ConvertAsync([path], new Preset { TargetFormat = target });
+ Assert.True(job.State == JobState.Completed, string.Join("; ", job.Files.Select(f => $"{f.ErrorKey} {f.ErrorDetail}")));
+ return job.Outputs.Single();
+ }
+
+ [Fact]
+ public void Omml_becomes_equation_script_and_linear_text()
+ {
+ foreach (var (omml, script, linear) in Samples)
+ {
+ var math = OmmlReader.Read(XElement.Parse($"<m:oMath {Namespaces}>{omml}</m:oMath>"));
+ Assert.Equal(script, EquationScript.Script(math));
+ Assert.Equal(linear.Normalize(), EquationScript.Linear(math).Normalize()); // â is a + combining circumflex
+ // Filee's own fixes before rhwp renders (RhwpInput) leave the script alone.
+ Assert.Equal(script, RhwpInput.NormaliseEquation(script));
+ }
+ }
+
+ [Fact]
+ public void Equation_boxes_follow_the_layout_of_the_script()
+ {
+ static MathBox Box(string omml) => EquationScript.Measure(OmmlReader.Read(XElement.Parse($"<m:oMath {Namespaces}>{omml}</m:oMath>")), 1000);
+
+ var letter = Box(MR("x"));
+ Assert.Equal(577.5, letter.Width, 6); // rhwp: 0.55 em, italic 5 % wider
+ Assert.Equal((1000, 800), (letter.Height, letter.Baseline));
+ var fraction = Box(Frac(MR("a"), MR("b")));
+ Assert.True(fraction.Height > 2 * letter.Height && fraction.Width > letter.Width);
+ Assert.True(Box(Nary("∑", MR("i=1"), MR("n"), MR("i"))).Height > fraction.Height);
+ Assert.True(Box(Sup(MR("x"), MR("2"))).Width < Box(MR("x2")).Width); // the exponent is smaller
+ }
+
+ [Fact]
+ public async Task Word_equations_become_hwpx_equation_objects()
+ {
+ var hwpx = await ConvertAsync(SampleDocument(), "equations", "hwpx");
+ ValidPackage(hwpx, 0);
+ var section = Xml(hwpx);
+
+ var equations = section.Descendants(Hp + "equation").ToList();
+ Assert.Equal(["E = m c ^{2}", .. Samples.Select(s => s.Script)], equations.Select(e => e.Element(Hp + "script")!.Value));
+ foreach (var equation in equations)
+ {
+ Assert.Equal("1", (string?)equation.Element(Hp + "pos")!.Attribute("treatAsChar"));
+ Assert.Equal("1000", (string?)equation.Attribute("baseUnit")); // the 10 pt of the runs
+ var size = equation.Element(Hp + "sz")!;
+ Assert.True((int)size.Attribute("width")! > 0 && (int)size.Attribute("height")! >= 1000);
+ Assert.NotEmpty(equation.Element(Hp + "shapeComment")!.Value);
+ }
+ Assert.Equal("(a+b)/(2c)", equations[1].Element(Hp + "shapeComment")!.Value);
+
+ // The inline equation stays between its words; a display equation alone in its paragraph is centred.
+ var inline = ParagraphWith(section, "Inline");
+ Assert.Contains(inline.Descendants(Hp + "equation"), e => e.Element(Hp + "script")!.Value == "E = m c ^{2}");
+ Assert.Contains("in a sentence.", inline.Value);
+ var display = equations[1].Ancestors(Hp + "p").First();
+ var paraPr = HeadItem(hwpx, "paraPr", (string)display.Attribute("paraPrIDRef")!);
+ Assert.Equal("CENTER", (string?)paraPr.Element(Hh + "align")!.Attribute("horizontal"));
+
+ await ReadableByH2OrestartAsync(fx, hwpx);
+ RenderWithRhwp(fx, hwpx, "docx-equations");
+ }
+
+ [Fact]
+ public async Task Rhwp_draws_the_equations_unstretched_and_keeps_the_text_after_them()
+ {
+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");
+ Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not found (pwsh build/fetch-engines.ps1 -Only rhwp)");
+
+ var pdf = await ConvertAsync(SampleDocument(), "equations", "pdf");
+ using (var document = PdfDocument.Open(pdf))
+ {
+ var text = string.Concat(document.GetPages().Select(p => p.Text));
+ Assert.Contains("sentence", text);
+ Assert.Contains("equations", text); // the paragraph after them
+ foreach (var symbol in new[] { "α", "β", "γ", "Ω", "∑" })
+ Assert.Contains(symbol, text);
+ }
+
+ // rhwp stretches an equation whose stored width differs from its own layout by more than 1 %.
+ var hwpx = await ConvertAsync(SampleDocument(), "equations-svg", "hwpx");
+ var exe = Path.Combine(EngineEnvironment.FindBundled("rhwp")!, OperatingSystem.IsWindows() ? "rhwp.exe" : "rhwp");
+ var folder = Path.Combine(Path.GetDirectoryName(hwpx)!, "svg");
+ await ProcessRunner.RunAsync(exe, ["export-svg", hwpx, "-o", folder], TimeSpan.FromMinutes(2), TestContext.Current.CancellationToken);
+ var svg = string.Concat(Directory.GetFiles(folder, "*.svg").Select(File.ReadAllText));
+ Assert.Contains("∑", svg);
+ Assert.DoesNotContain("scale(", svg);
+ }
+
+ [Fact]
+ public async Task Rhwp_gets_room_below_equations_that_reach_under_their_line()
+ {
+ var hwpx = await ConvertAsync(SampleDocument(), "equations-room", "hwpx");
+ var copy = RhwpInput.Prepare(hwpx, Path.GetDirectoryName(hwpx)!, _ => new InstalledFont(true, _ => true));
+ Assert.NotNull(copy);
+ ValidPackage(copy);
+ var section = Xml(copy);
+ var head = Xml(copy, "Contents/header.xml");
+ int After(XElement paragraph) =>
+ (int)head.Descendants(Hh + "paraPr").Single(p => (string?)p.Attribute("id") == (string?)paragraph.Attribute("paraPrIDRef"))
+ .Descendants(Hc + "next").First().Attribute("value")!;
+
+ // rhwp puts a line's baseline at 85 % of its height; a matrix has its own baseline in the middle, so 35 % of
+ // it hangs below the line.
+ var matrix = section.Descendants(Hp + "equation").Single(e => e.Element(Hp + "script")!.Value.Contains("pmatrix"));
+ var height = (int)matrix.Element(Hp + "sz")!.Attribute("height")!;
+ Assert.Equal("50", (string?)matrix.Attribute("baseLine"));
+ Assert.Equal((int)System.Math.Ceiling(height * 0.35), After(matrix.Ancestors(Hp + "p").First()));
+ Assert.Equal(0, After(ParagraphWith(section, "Text after")));
+ Assert.Equal(0, After(ParagraphWith(section, "Inline"))); // a text line holds E = mc^2
+ }
+
+ [Fact]
+ public async Task Hwp_keeps_the_equations()
+ {
+ var rhwp = fx.Converters.Single(c => c.Id == "rhwp");
+ Assert.SkipUnless(fx.Catalog.StatusOf(rhwp).IsAvailable, "rhwp not found (pwsh build/fetch-engines.ps1 -Only rhwp)");
+
+ var hwp = await ConvertAsync(SampleDocument(), "equations-hwp", "hwp");
+ var back = Path.Combine(Path.GetDirectoryName(hwp)!, "back.hwpx");
+ await rhwp.ConvertAsync(new ConversionStep(hwp, "hwp", "hwpx", new Preset(), new FixedPath(back), Path.GetDirectoryName(hwp)!),
+ null, TestContext.Current.CancellationToken);
+ var scripts = Xml(back).Descendants(Hp + "equation").Select(e => e.Element(Hp + "script")!.Value).ToList();
+ Assert.Contains("{{a + b} over {2 c}}", scripts);
+ Assert.Contains("A = pmatrix {1 & 2 # 3 & 4}", scripts);
+ }
+
+ [Fact]
+ public void Formats_without_equations_get_the_linear_form()
+ {
+ var dir = fx.NewFolder();
+ var path = SampleDocument().Save(Path.Combine(dir, "linear.docx"));
+ var document = DocxReader.Read(path, Path.Combine(dir, "media"));
+ var text = string.Join("\n", document.Sections.SelectMany(s => s.Blocks).OfType<HParagraph>().Select(p => HDocumentWalker.Text(p.Inlines)));
+ Assert.Contains("Inline E=mc^2 in a sentence.", text);
+ Assert.Contains("(a+b)/(2c)", text);
+ Assert.Contains("lim_(x→0) (sin x)/x", text);
+ }
+}