Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/MathOMML.swift3// Description: Office Math (OMML) side of the math converter: writes the math tree as m:oMath content and reads4// m:oMath content (as produced by Word, pandoc and LibreOffice) back into the math tree.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910// MARK: - Writer1112struct MathOMMLWriter {13 private struct Context {14 var sty: String?15 var scr: String?16 }1718 static func write(_ nodes: [MathNode]) -> String { MathOMMLWriter().row(nodes, Context()) }1920 private func run(_ text: String, sty: String? = nil, scr: String? = nil, nor: Bool = false) -> String {21 guard !text.isEmpty else { return "" }22 var pr = ""23 if nor { pr += "<m:nor/>" }24 if let scr, !nor { pr += xmlTag("m:scr", [("m:val", scr)]) }25 if let sty, !nor { pr += xmlTag("m:sty", [("m:val", sty)]) }26 let preserve = text.contains { $0.isWhitespace }27 return "<m:r>" + (pr.isEmpty ? "" : "<m:rPr>\(pr)</m:rPr>")28 + xmlTag("m:t", preserve ? [("xml:space", "preserve")] : [], XMLEscape.text(text)) + "</m:r>"29 }3031 private func row(_ nodes: [MathNode], _ ctx: Context) -> String {32 var out = ""33 var pending = ""34 for n in nodes {35 if case .char(let c) = n { pending += c; continue }36 out += run(pending, sty: ctx.sty, scr: ctx.scr)37 pending = ""38 out += node(n, ctx)39 }40 return out + run(pending, sty: ctx.sty, scr: ctx.scr)41 }4243 private func arg(_ name: String, _ n: MathNode?, _ ctx: Context) -> String {44 guard let n, !n.isEmptyRow else { return "<\(name)/>" }45 return "<\(name)>" + row(n.items, ctx) + "</\(name)>"46 }4748 private func node(_ n: MathNode, _ ctx: Context) -> String {49 switch n {50 case .row(let items): return row(items, ctx)51 case .char(let c): return run(c, sty: ctx.sty, scr: ctx.scr)52 case .text(let s): return run(s, nor: true)53 case .funcName(let name): return run(MathTables.functionDisplay(name), sty: "p")54 case .styled(let style, let body):55 var c = ctx56 if let scr = style.scr { c.scr = scr }57 if let sty = style.sty { c.sty = sty }58 return row(body.items, c)59 case .frac(let a, let b, let type):60 let pr = type == .bar ? "" : "<m:fPr>" + xmlTag("m:type", [("m:val", type.rawValue)]) + "</m:fPr>"61 return "<m:f>" + pr + arg("m:num", a, ctx) + arg("m:den", b, ctx) + "</m:f>"62 case .sqrt(let index, let body):63 if let index, !index.isEmptyRow { return "<m:rad>" + arg("m:deg", index, ctx) + arg("m:e", body, ctx) + "</m:rad>" }64 return "<m:rad><m:radPr><m:degHide m:val=\"1\"/></m:radPr><m:deg/>" + arg("m:e", body, ctx) + "</m:rad>"65 case .sup(let b, let p): return "<m:sSup>" + arg("m:e", b, ctx) + arg("m:sup", p, ctx) + "</m:sSup>"66 case .sub(let b, let s): return "<m:sSub>" + arg("m:e", b, ctx) + arg("m:sub", s, ctx) + "</m:sSub>"67 case .subsup(let b, let s, let p): return "<m:sSubSup>" + arg("m:e", b, ctx) + arg("m:sub", s, ctx) + arg("m:sup", p, ctx) + "</m:sSubSup>"68 case .nary(let op, let sub, let sup, let body):69 var pr = xmlTag("m:chr", [("m:val", op)]) + xmlTag("m:limLoc", [("m:val", MathTables.integrals.contains(op) ? "subSup" : "undOvr")])70 if sub == nil { pr += "<m:subHide m:val=\"1\"/>" }71 if sup == nil { pr += "<m:supHide m:val=\"1\"/>" }72 return "<m:nary><m:naryPr>\(pr)</m:naryPr>" + arg("m:sub", sub, ctx) + arg("m:sup", sup, ctx) + arg("m:e", body, ctx) + "</m:nary>"73 case .delim(let open, let close, let sep, let parts):74 var pr = xmlTag("m:begChr", [("m:val", open)])75 if parts.count > 1 || sep != "|" { pr += xmlTag("m:sepChr", [("m:val", sep)]) }76 pr += xmlTag("m:endChr", [("m:val", close)])77 let body = parts.isEmpty ? "<m:e/>" : parts.map { arg("m:e", $0, ctx) }.joined()78 return "<m:d><m:dPr>\(pr)</m:dPr>" + body + "</m:d>"79 case .accent(let name, let body):80 return "<m:acc><m:accPr>" + xmlTag("m:chr", [("m:val", MathTables.accents[name] ?? "\u{0302}")]) + "</m:accPr>" + arg("m:e", body, ctx) + "</m:acc>"81 case .bar(let top, let body):82 return "<m:bar><m:barPr><m:pos m:val=\"\(top ? "top" : "bot")\"/></m:barPr>" + arg("m:e", body, ctx) + "</m:bar>"83 case .function(let head, let a):84 return "<m:func>" + arg("m:fName", head, ctx) + arg("m:e", a, ctx) + "</m:func>"85 case .under(let b, let u): return "<m:limLow>" + arg("m:e", b, ctx) + arg("m:lim", u, ctx) + "</m:limLow>"86 case .over(let b, let o): return "<m:limUpp>" + arg("m:e", b, ctx) + arg("m:lim", o, ctx) + "</m:limUpp>"87 case .groupChr(let ch, let top, let body):88 let pr = xmlTag("m:chr", [("m:val", ch)]) + "<m:pos m:val=\"\(top ? "top" : "bot")\"/><m:vertJc m:val=\"\(top ? "bot" : "top")\"/>"89 return "<m:groupChr><m:groupChrPr>\(pr)</m:groupChrPr>" + arg("m:e", body, ctx) + "</m:groupChr>"90 case .matrix(let rows):91 let columns = max(1, rows.map(\.count).max() ?? 1)92 let pr = "<m:mPr><m:mcs><m:mc><m:mcPr><m:count m:val=\"\(columns)\"/><m:mcJc m:val=\"center\"/></m:mcPr></m:mc></m:mcs></m:mPr>"93 let body = rows.map { cells in94 "<m:mr>" + (0..<columns).map { arg("m:e", $0 < cells.count ? cells[$0] : nil, ctx) }.joined() + "</m:mr>"95 }.joined()96 return "<m:m>" + pr + body + "</m:m>"97 case .eqArray(let rows):98 let body = rows.map { cells -> String in99 var inner = ""100 for (k, cell) in cells.enumerated() {101 if k > 0 { inner += run("&") }102 inner += row(cell.items, ctx)103 }104 return inner.isEmpty ? "<m:e/>" : "<m:e>\(inner)</m:e>"105 }.joined()106 return "<m:eqArr>" + (body.isEmpty ? "<m:e/>" : body) + "</m:eqArr>"107 case .boxed(let body): return "<m:borderBox>" + arg("m:e", body, ctx) + "</m:borderBox>"108 case .phantom(let body): return "<m:phant><m:phantPr><m:show m:val=\"0\"/></m:phantPr>" + arg("m:e", body, ctx) + "</m:phant>"109 }110 }111}112113// MARK: - Reader114115struct MathOMMLReader {116 /// Names of the OMML elements that had no mapping (content kept best-effort).117 private(set) var unsupported: [String] = []118 private static let maxDepth = 300119120 private static func isOn(_ node: XMLNode?) -> Bool {121 guard let node else { return false }122 guard let v = node.attr("m:val")?.lowercased() else { return true }123 return !(v == "0" || v == "false" || v == "off")124 }125126 private static func chars(_ text: String) -> [MathNode] { text.map { .char(String($0)) } }127128 mutating func nodes(of parent: XMLNode, depth: Int, functionName: Bool = false) -> [MathNode] {129 var out: [MathNode] = []130 for child in parent.children {131 for n in convert(child, depth: depth + 1, functionName: functionName) {132 if case .row(let r) = n { out.append(contentsOf: r) } else { out.append(n) }133 }134 }135 return out136 }137138 private mutating func part(_ parent: XMLNode, _ name: String, depth: Int, functionName: Bool = false) -> MathNode {139 guard let child = parent.first(name) else { return .empty }140 return .make(nodes(of: child, depth: depth, functionName: functionName))141 }142143 private mutating func run(_ n: XMLNode, functionName: Bool) -> [MathNode] {144 var text = ""145 for t in n.children where t.name == "m:t" || t.name == "w:t" { text += t.text }146 guard !text.isEmpty else { return [] }147 let pr = n.first("m:rPr")148 if MathOMMLReader.isOn(pr?.first("m:nor")) { return [.text(text)] }149 let sty = pr?.val("m:sty", "m:val")150 let scr = pr?.val("m:scr", "m:val")151 if functionName {152 let trimmed = text.trimmingCharacters(in: .whitespaces)153 if let known = MathTables.functionName(display: trimmed) { return [.funcName(known)] }154 if sty == "p", scr == nil, !trimmed.isEmpty, trimmed.allSatisfy({ $0.isLetter || $0.isNumber || $0 == " " || $0 == "-" }) { return [.funcName(trimmed)] }155 }156 if let scr, let style = [MathStyle.bb, .cal, .frak, .sf, .tt].first(where: { $0.scr == scr }) {157 var node = MathNode.styled(style, .make(MathOMMLReader.chars(text)))158 if sty == "b" { node = .styled(.bf, node) } else if sty == "bi" { node = .styled(.bfit, node) }159 return [node]160 }161 switch sty {162 case "b": return [.styled(.bf, .make(MathOMMLReader.chars(text)))]163 case "bi": return [.styled(.bfit, .make(MathOMMLReader.chars(text)))]164 case "p":165 if let known = MathTables.functionName(display: text) { return [.funcName(known)] }166 // Upright applies to letters; pandoc also marks operators and symbols upright, which is their normal look.167 var out: [MathNode] = []168 var letters = ""169 func flush() {170 guard !letters.isEmpty else { return }171 if let known = MathTables.functionName(display: letters) { out.append(.funcName(known)) }172 else { out.append(.styled(.rm, .make(MathOMMLReader.chars(letters)))) }173 letters = ""174 }175 for c in text {176 if c.isLetter && MathTables.latexForChar[String(c)]?.contains("{") != true { letters.append(c) } else { flush(); out.append(.char(String(c))) }177 }178 flush()179 return out180 default: return MathOMMLReader.chars(text)181 }182 }183184 private mutating func convert(_ n: XMLNode, depth: Int, functionName: Bool) -> [MathNode] {185 if depth > MathOMMLReader.maxDepth { return n.deepText.isEmpty ? [] : [.text(n.deepText)] }186 switch n.name {187 case "m:r": return run(n, functionName: functionName)188 case "m:oMath", "m:e", "m:fName", "m:num", "m:den", "m:deg", "m:sub", "m:sup", "m:lim", "m:box", "m:oMathPara":189 return nodes(of: n, depth: depth, functionName: functionName)190 case "m:f":191 let type = MathFracType(rawValue: n.path("m:fPr", "m:type")?.attr("m:val") ?? "bar") ?? .bar192 return [.frac(part(n, "m:num", depth: depth), part(n, "m:den", depth: depth), type)]193 case "m:rad":194 let index = part(n, "m:deg", depth: depth)195 let hidden = MathOMMLReader.isOn(n.path("m:radPr", "m:degHide"))196 return [.sqrt(hidden || index.isEmptyRow ? nil : index, part(n, "m:e", depth: depth))]197 case "m:sSup":198 return [MathLatexParser.attach(base: part(n, "m:e", depth: depth, functionName: functionName), sub: nil, sup: part(n, "m:sup", depth: depth))]199 case "m:sSub":200 return [MathLatexParser.attach(base: part(n, "m:e", depth: depth, functionName: functionName), sub: part(n, "m:sub", depth: depth), sup: nil)]201 case "m:sSubSup":202 return [MathLatexParser.attach(base: part(n, "m:e", depth: depth, functionName: functionName), sub: part(n, "m:sub", depth: depth),203 sup: part(n, "m:sup", depth: depth))]204 case "m:sPre":205 let sub = part(n, "m:sub", depth: depth), sup = part(n, "m:sup", depth: depth)206 let pre = MathLatexParser.attach(base: .empty, sub: sub.isEmptyRow ? nil : sub, sup: sup.isEmptyRow ? nil : sup)207 return (pre.isEmptyRow ? [] : [pre]) + part(n, "m:e", depth: depth).items208 case "m:nary":209 let pr = n.first("m:naryPr")210 let op = pr?.first("m:chr").map { $0.attr("m:val") ?? "" } ?? "∫"211 let sub = part(n, "m:sub", depth: depth), sup = part(n, "m:sup", depth: depth)212 let noSub = MathOMMLReader.isOn(pr?.first("m:subHide")) || sub.isEmptyRow213 let noSup = MathOMMLReader.isOn(pr?.first("m:supHide")) || sup.isEmptyRow214 let body = part(n, "m:e", depth: depth)215 if op.isEmpty { return (noSub && noSup ? [] : [MathLatexParser.attach(base: .empty, sub: noSub ? nil : sub, sup: noSup ? nil : sup)]) + body.items }216 return [.nary(op, noSub ? nil : sub, noSup ? nil : sup, body)]217 case "m:d":218 let pr = n.first("m:dPr")219 let open = pr?.first("m:begChr").map { $0.attr("m:val") ?? "" } ?? "("220 let close = pr?.first("m:endChr").map { $0.attr("m:val") ?? "" } ?? ")"221 var sep = pr?.first("m:sepChr").map { $0.attr("m:val") ?? "" } ?? "|"222 var parts: [MathNode] = []223 for e in n.children where e.name == "m:e" { parts.append(.make(nodes(of: e, depth: depth))) }224 if parts.isEmpty { parts = [.empty] }225 if parts.count < 2 || sep.isEmpty { sep = "|" }226 return [.delim(open, close, sep, parts)]227 case "m:acc":228 let ch = n.path("m:accPr", "m:chr").map { $0.attr("m:val") ?? "" } ?? "\u{0302}"229 let body = part(n, "m:e", depth: depth)230 if let name = MathTables.accentName[ch] { return [.accent(name, body)] }231 return ch.isEmpty ? body.items : [.over(body, .char(ch))]232 case "m:bar":233 return [.bar(top: n.path("m:barPr", "m:pos")?.attr("m:val") == "top", part(n, "m:e", depth: depth))]234 case "m:func":235 let head = part(n, "m:fName", depth: depth, functionName: true)236 let arg = part(n, "m:e", depth: depth)237 if MathTables.isFunctionHead(head) { return [.function(head, arg)] }238 return head.items + arg.items239 case "m:limLow":240 let base = part(n, "m:e", depth: depth, functionName: functionName), lim = part(n, "m:lim", depth: depth)241 if case .char("⏟") = lim { return [.groupChr("⏟", top: false, base)] }242 return [.under(base, lim)]243 case "m:limUpp":244 let base = part(n, "m:e", depth: depth, functionName: functionName), lim = part(n, "m:lim", depth: depth)245 if case .char("⏞") = lim { return [.groupChr("⏞", top: true, base)] }246 return [.over(base, lim)]247 case "m:groupChr":248 let pr = n.first("m:groupChrPr")249 let ch = pr?.first("m:chr").map { $0.attr("m:val") ?? "" } ?? "⏟"250 let top = pr?.first("m:pos")?.attr("m:val") == "top"251 let body = part(n, "m:e", depth: depth)252 return ch.isEmpty ? body.items : [.groupChr(ch, top: top, body)]253 case "m:m":254 var rows: [[MathNode]] = []255 for mr in n.children where mr.name == "m:mr" {256 var cells: [MathNode] = []257 for e in mr.children where e.name == "m:e" { cells.append(.make(nodes(of: e, depth: depth))) }258 rows.append(cells)259 }260 return [.matrix(rows)]261 case "m:eqArr":262 var rows: [[MathNode]] = []263 for e in n.children where e.name == "m:e" {264 var cells: [[MathNode]] = [[]]265 for item in nodes(of: e, depth: depth) {266 if case .char("&") = item { cells.append([]) } else { cells[cells.count - 1].append(item) }267 }268 rows.append(cells.map { .make($0) })269 }270 return [.eqArray(rows)]271 case "m:borderBox": return [.boxed(part(n, "m:e", depth: depth))]272 case "m:phant":273 let body = part(n, "m:e", depth: depth)274 if let show = n.path("m:phantPr", "m:show"), !MathOMMLReader.isOn(show) { return [.phantom(body)] }275 return body.items276 case "w:r":277 let text = n.children.filter { $0.name == "w:t" }.map(\.text).joined()278 return text.isEmpty ? [] : [.text(text)]279 case "w:bookmarkStart", "w:bookmarkEnd", "w:proofErr", "w:rPr", "m:ctrlPr", "w:commentRangeStart", "w:commentRangeEnd":280 return []281 default:282 if n.name.hasSuffix("Pr") { return [] }283 if !unsupported.contains(n.name) { unsupported.append(n.name) }284 if !n.children.isEmpty { return nodes(of: n, depth: depth) }285 return MathOMMLReader.chars(n.text)286 }287 }288}289