Repository Public
1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocDOCX/DocxExportBody.swift3// Description: WordprocessingML export of content: run and paragraph properties, paragraphs, runs, tracked changes, comment ranges,4// hyperlinks, fields, equations, drawings, tables, generated blocks, notes and comments.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import DocModel10import DocContainer1112extension DocxExportContext {1314 // MARK: Property fragments1516 func borderXML(_ tag: String, _ line: BorderLine?, space: String = "0") -> String {17 guard let line else { return xmlTag(tag, [("w:val", "nil")]) }18 let val: String19 switch line.style {20 case .solid: val = "single"21 case .dashed: val = "dashed"22 case .dotted: val = "dotted"23 case .double: val = "double"24 }25 let sz = max(2, min(96, DocxUnit.safeInt(line.width * 8)))26 return xmlTag(tag, [("w:val", val), ("w:sz", String(sz)), ("w:space", space), ("w:color", line.color.hexString)])27 }2829 func shadingXML(_ fill: RGBA) -> String {30 xmlTag("w:shd", [("w:val", "clear"), ("w:color", "auto"), ("w:fill", fill.hexString)])31 }3233 func tableBordersXML(_ s: TableStyle) -> String {34 "<w:tblBorders>" + borderXML("w:top", s.outerBorder) + borderXML("w:left", s.outerBorder) + borderXML("w:bottom", s.outerBorder)35 + borderXML("w:right", s.outerBorder) + borderXML("w:insideH", s.innerHorizontal) + borderXML("w:insideV", s.innerVertical) + "</w:tblBorders>"36 }3738 func cellMarginsXML(_ p: Insets) -> String {39 func m(_ tag: String, _ v: Double) -> String { xmlTag(tag, [("w:w", DocxUnit.toTwips(v)), ("w:type", "dxa")]) }40 return "<w:tblCellMar>" + m("w:top", p.top) + m("w:left", p.left) + m("w:bottom", p.bottom) + m("w:right", p.right) + "</w:tblCellMar>"41 }4243 /// Children of `w:rPr` in schema order.44 func rPrInner(_ c: CharProps, style: String?, change: FormatRevision? = nil, noteMark: Bool = false) -> String {45 var s = ""46 if let style { s += xmlTag("w:rStyle", [("w:val", style)]) }47 if let f = c.fontFamily, !f.isEmpty { s += xmlTag("w:rFonts", [("w:ascii", f), ("w:hAnsi", f), ("w:eastAsia", f), ("w:cs", f)]) }48 var bold = c.bold49 if let w = c.weight {50 bold = w >= 60051 if w != 400 && w != 700 { warn(.approximated, "Font weights", "Word knows regular and bold only; other font weights are exported as the nearest of the two.") }52 }53 if let b = bold { s += b ? "<w:b/><w:bCs/>" : "<w:b w:val=\"0\"/><w:bCs w:val=\"0\"/>" }54 if let i = c.italic { s += i ? "<w:i/><w:iCs/>" : "<w:i w:val=\"0\"/><w:iCs w:val=\"0\"/>" }55 if let v = c.allCaps { s += v ? "<w:caps/>" : "<w:caps w:val=\"0\"/>" }56 if let v = c.smallCaps { s += v ? "<w:smallCaps/>" : "<w:smallCaps w:val=\"0\"/>" }57 if let v = c.strikethrough { s += v ? "<w:strike/>" : "<w:strike w:val=\"0\"/>" }58 if let col = c.color { s += xmlTag("w:color", [("w:val", col.hexString)]) }59 if let t = c.tracking { s += xmlTag("w:spacing", [("w:val", DocxUnit.toTwips(t))]) }60 if let k = c.kerning { s += xmlTag("w:kern", [("w:val", k ? "2" : "0")]) }61 if let p = c.baselineShift { s += xmlTag("w:position", [("w:val", DocxUnit.toHalfPoints(p))]) }62 if let size = c.fontSize {63 let hp = DocxUnit.toHalfPoints(size)64 if abs(size * 2 - (size * 2).rounded()) > 1e-6 { warn(.approximated, "Font sizes", "Word stores font sizes in half points; other sizes are rounded to the nearest half point.") }65 s += xmlTag("w:sz", [("w:val", hp)]) + xmlTag("w:szCs", [("w:val", hp)])66 }67 var shade = ""68 if let h = c.highlight {69 if let name = DocxColor.highlightName(h) { s += xmlTag("w:highlight", [("w:val", name)]) } else { shade = shadingXML(h) }70 }71 if let u = c.underline { s += xmlTag("w:u", [("w:val", u ? "single" : "none")]) }72 s += shade73 var vertical = c.vertical74 if noteMark, vertical == nil, style == nil { vertical = .superscript }75 if let v = vertical {76 s += xmlTag("w:vertAlign", [("w:val", v == .superscript ? "superscript" : v == .subscript ? "subscript" : "baseline")])77 }78 if let l = c.language, !l.isEmpty { s += xmlTag("w:lang", [("w:val", l)]) }79 if let lig = c.ligatures { s += xmlTag("w14:ligatures", [("w14:val", lig ? "standard" : "none")]) }80 if let ch = change {81 s += xmlTag("w:rPrChange", [("w:id", String(takeID())), ("w:author", ch.author), ("w:date", DocxDate.string(ch.date))],82 xmlTag("w:rPr", [], rPrInner(ch.previous, style: ch.previousCharStyle)))83 }84 return s85 }8687 func rPr(_ run: Run, noteMark: Bool = false) -> String {88 var props = run.props89 props.link = nil90 let inner = rPrInner(props, style: run.charStyle, change: run.formatRevision, noteMark: noteMark)91 return inner.isEmpty ? "" : "<w:rPr>" + inner + "</w:rPr>"92 }9394 /// Children of `w:pPr` in schema order.95 func pPrInner(style: String?, props p: ParaProps, numPr: String? = nil, markRPr: String? = nil, sectPr: String? = nil) -> String {96 var s = ""97 if let style { s += xmlTag("w:pStyle", [("w:val", style)]) }98 func onOff(_ tag: String, _ v: Bool?) { if let v { s += v ? "<\(tag)/>" : "<\(tag) w:val=\"0\"/>" } }99 onOff("w:keepNext", p.keepWithNext)100 onOff("w:keepLines", p.keepLinesTogether)101 onOff("w:pageBreakBefore", p.pageBreakBefore)102 onOff("w:widowControl", p.widowControl)103 if let numPr { s += numPr }104 if p.borderTop != nil || p.borderBottom != nil || p.borderLeft != nil {105 var b = ""106 if let l = p.borderTop { b += borderXML("w:top", l, space: "1") }107 if let l = p.borderLeft { b += borderXML("w:left", l, space: "4") }108 if let l = p.borderBottom { b += borderXML("w:bottom", l, space: "1") }109 s += "<w:pBdr>" + b + "</w:pBdr>"110 }111 if let f = p.shading { s += shadingXML(f) }112 if let tabs = p.tabs, !tabs.isEmpty {113 var t = ""114 for stop in tabs {115 let val: String116 switch stop.kind { case .left: val = "left"; case .center: val = "center"; case .right: val = "right"; case .decimal: val = "decimal" }117 var leader: String?118 switch stop.leader { case .none: leader = nil; case .dots: leader = "dot"; case .dashes: leader = "hyphen"; case .line: leader = "underscore" }119 t += xmlTag("w:tab", [("w:val", val), ("w:leader", leader), ("w:pos", DocxUnit.toTwips(stop.position))])120 }121 s += "<w:tabs>" + t + "</w:tabs>"122 }123 if let h = p.hyphenate { s += h ? "<w:suppressAutoHyphens w:val=\"0\"/>" : "<w:suppressAutoHyphens/>" }124 onOff("w:bidi", p.rightToLeft)125 if p.spaceBefore != nil || p.spaceAfter != nil || p.lineSpacing != nil {126 var attrs: [(String, String?)] = [("w:before", p.spaceBefore.map(DocxUnit.toTwips)), ("w:after", p.spaceAfter.map(DocxUnit.toTwips))]127 switch p.lineSpacing {128 case .multiple(let m)?: attrs += [("w:line", String(DocxUnit.safeInt(m * 240))), ("w:lineRule", "auto")]129 case .exact(let v)?: attrs += [("w:line", DocxUnit.toTwips(v)), ("w:lineRule", "exact")]130 case .atLeast(let v)?: attrs += [("w:line", DocxUnit.toTwips(v)), ("w:lineRule", "atLeast")]131 case nil: break132 }133 s += xmlTag("w:spacing", attrs)134 }135 if p.indentLeft != nil || p.indentRight != nil || p.firstLineIndent != nil {136 var attrs: [(String, String?)] = [("w:left", p.indentLeft.map(DocxUnit.toTwips)), ("w:right", p.indentRight.map(DocxUnit.toTwips))]137 if let f = p.firstLineIndent { attrs.append(f < 0 ? ("w:hanging", DocxUnit.toTwips(-f)) : ("w:firstLine", DocxUnit.toTwips(f))) }138 s += xmlTag("w:ind", attrs)139 }140 if let a = p.alignment {141 let v: String142 switch a { case .left: v = "left"; case .center: v = "center"; case .right: v = "right"; case .justified: v = "both" }143 s += xmlTag("w:jc", [("w:val", v)])144 }145 if let lvl = p.outlineLevel { s += xmlTag("w:outlineLvl", [("w:val", String((1...9).contains(lvl) ? lvl - 1 : 9))]) }146 if let d = p.dropCapLines, d > 0 { warn(.dropped, "Drop caps", "Drop caps are not exported; the paragraph keeps its text.") }147 if let markRPr { s += markRPr }148 if let sectPr { s += sectPr }149 return s150 }151152 // MARK: Body153154 func bodyXML(_ part: DocxPart) -> String {155 var out = ""156 var setup = doc.pageSetup157 var kind: SectionBreak.Kind?158 let blocks = doc.body159 var previousWasTable = false160 for (i, block) in blocks.enumerated() {161 var nextBreak: SectionBreak?162 if i + 1 < blocks.count, case .sectionBreak(let sb) = blocks[i + 1] { nextBreak = sb }163 let isTable: Bool164 switch block {165 case .paragraph(let p):166 // Word keeps a section's properties in its last paragraph.167 let sect = nextBreak != nil ? sectPrXML(setup, kind: kind, document: part) : nil168 out += paragraphXML(p, part: part, sectPr: sect)169 isTable = false170 case .table(let t):171 // Word merges two adjacent tables; a hidden empty paragraph keeps them apart.172 if previousWasTable { out += DocxExportContext.tableSeparator }173 out += tableXML(t, part: part)174 isTable = true175 case .pageBreak(let b):176 out += "<w:p><w:r>" + xmlTag("w:br", [("w:type", b.kind == .page ? "page" : "column")]) + "</w:r></w:p>"177 isTable = false178 case .sectionBreak(let sb):179 var carried = false180 if i > 0, case .paragraph = blocks[i - 1] { carried = true }181 if !carried { out += "<w:p><w:pPr>" + sectPrXML(setup, kind: kind, document: part) + "</w:pPr></w:p>" }182 setup = sb.setup183 kind = sb.kind184 isTable = false185 case .toc(let t):186 out += tocXML(t)187 isTable = false188 case .bibliography(let b):189 out += bibliographyXML(b, part: part)190 isTable = false191 }192 previousWasTable = isTable193 }194 // A document cannot end with a table: Word needs a final paragraph mark.195 if previousWasTable { out += DocxExportContext.tableSeparator }196 out += sectPrXML(setup, kind: kind, document: part)197 return out198 }199200 /// The hidden, one-point paragraph Word needs between two tables and after a table that ends the document.201 /// The importer recognises it (hidden paragraph mark, no content, next to a table) and does not turn it into content.202 static let tableSeparator = "<w:p><w:pPr><w:spacing w:before=\"0\" w:after=\"0\" w:line=\"20\" w:lineRule=\"exact\"/><w:rPr><w:vanish/><w:sz w:val=\"2\"/></w:rPr></w:pPr></w:p>"203204 // MARK: Paragraphs205206 func paragraphXML(_ p: Paragraph, part: DocxPart, sectPr: String? = nil, leading: String = "", formula: String? = nil, noteMark: NoteRef.Kind? = nil) -> String {207 var numPr: String?208 if let li = p.list {209 if let numID = listNumIDs[li.listID] {210 numPr = "<w:numPr><w:ilvl w:val=\"\(max(0, min(8, li.level)))\"/><w:numId w:val=\"\(numID)\"/></w:numPr>"211 } else {212 warn(.dropped, "Lists", "A paragraph refers to a list definition that does not exist; it is exported without numbering.")213 }214 }215 var markRPr: String?216 if let rev = p.markRevision {217 markRPr = "<w:rPr>" + xmlTag(rev.kind == .insertion ? "w:ins" : "w:del", [("w:id", String(takeID())), ("w:author", rev.author), ("w:date", DocxDate.string(rev.date))]) + "</w:rPr>"218 }219 let pPr = pPrInner(style: p.style == StyleID.normal ? nil : p.style, props: p.props, numPr: numPr, markRPr: markRPr, sectPr: sectPr)220 var content = pPr.isEmpty ? "" : "<w:pPr>" + pPr + "</w:pPr>"221 content += leading222223 if let kind = noteMark {224 content += "<w:r><w:rPr><w:vertAlign w:val=\"superscript\"/></w:rPr>" + (kind == .footnote ? "<w:footnoteRef/>" : "<w:endnoteRef/>") + "</w:r><w:r><w:t xml:space=\"preserve\"> </w:t></w:r>"225 }226 let tracked = part.kind == .body || part.kind == .note227 if part.kind == .body, !orphanComments.isEmpty {228 for id in orphanComments { content += commentMarkers(id, start: true) + commentMarkers(id, start: false) }229 orphanComments = []230 }231232 // Hidden bookmarks that make this paragraph a cross-reference target.233 let kinds = part.kind == .body ? (refKinds[p.id] ?? []) : []234 let seqIndex = p.runs.firstIndex { if case .field(.sequence)? = $0.inline { return !$0.isDeleted } else { return false } }235 var bookmarkIDs: [Character: Int] = [:]236 func open(_ k: Character) {237 let id = takeID()238 bookmarkIDs[k] = id239 content += xmlTag("w:bookmarkStart", [("w:id", String(id)), ("w:name", DocxConvention.refBookmark(kind: k, id: refSafeIDs[p.id] ?? p.id))])240 }241 func close(_ k: Character) { if let id = bookmarkIDs.removeValue(forKey: k) { content += xmlTag("w:bookmarkEnd", [("w:id", String(id))]) } }242 if kinds.contains("T") { open("T") }243 if kinds.contains("L") { open("L") }244 if kinds.contains("N"), seqIndex == nil { open("N") }245246 if let formula { content += fieldStart(" \(formula) ", rPr: "", deleted: false) }247248 var linkOpen: String?249 var revOpen: Revision?250 func closeRevision() {251 if let r = revOpen { content += r.kind == .insertion ? "</w:ins>" : "</w:del>"; revOpen = nil }252 }253 func closeLink() {254 closeRevision()255 if linkOpen != nil { content += "</w:hyperlink>"; linkOpen = nil }256 }257 var seqCounter = 0258 for (i, run) in p.runs.enumerated() {259 let link = run.props.link.flatMap { $0.isEmpty ? nil : $0 }260 if link != linkOpen {261 closeLink()262 if let link {263 if link.hasPrefix("#") {264 content += xmlTag("w:hyperlink", [("w:anchor", String(link.dropFirst())), ("w:history", "1")], "").replacingOccurrences(of: "</w:hyperlink>", with: "")265 } else {266 let rid = part.rels.add(type: RelType.hyperlink, target: link, external: true)267 content += xmlTag("w:hyperlink", [("r:id", rid), ("w:history", "1")], "").replacingOccurrences(of: "</w:hyperlink>", with: "")268 }269 linkOpen = link270 }271 }272 let key = "\(p.id)#\(i)"273 if tracked, let starts = commentStarts[key] {274 closeRevision()275 for id in starts { content += commentMarkers(id, start: true) }276 }277 if i == seqIndex, kinds.contains("N") { closeRevision(); open("N") }278 if run.revision != revOpen {279 closeRevision()280 if let r = run.revision {281 content += "<" + (r.kind == .insertion ? "w:ins" : "w:del") + " w:id=\"\(takeID())\" w:author=\"\(XMLEscape.attr(r.author))\" w:date=\"\(DocxDate.string(r.date))\">"282 revOpen = r283 }284 }285 content += runXML(run, paragraph: p, part: part, seqCounter: &seqCounter)286 if i == seqIndex, kinds.contains("N") || kinds.contains("L") { closeRevision(); close("N"); close("L") }287 if tracked, let ends = commentEnds[key] {288 closeRevision()289 for id in ends { content += commentMarkers(id, start: false) }290 }291 }292 closeLink()293 if formula != nil { content += "<w:r><w:fldChar w:fldCharType=\"end\"/></w:r>" }294 close("N"); close("L"); close("T")295 return "<w:p>" + content + "</w:p>"296 }297298 func commentMarkers(_ id: String, start: Bool) -> String {299 var s = ""300 for wid in commentWordIDs[id] ?? [] {301 if start { s += "<w:commentRangeStart w:id=\"\(wid)\"/>" }302 else { s += "<w:commentRangeEnd w:id=\"\(wid)\"/><w:r><w:commentReference w:id=\"\(wid)\"/></w:r>" }303 }304 return s305 }306307 // MARK: Runs308309 func textRunXML(_ text: String, rPr: String, deleted: Bool) -> String {310 var body = ""311 var buffer = ""312 let tag = deleted ? "w:delText" : "w:t"313 func flush() {314 if !buffer.isEmpty { body += "<\(tag) xml:space=\"preserve\">" + XMLEscape.text(buffer) + "</\(tag)>"; buffer = "" }315 }316 for u in text.unicodeScalars {317 switch u {318 case "\t": flush(); body += "<w:tab/>"319 case "\u{2028}", "\n", "\u{2029}": flush(); body += "<w:br/>"320 case "\u{AD}": flush(); body += "<w:softHyphen/>"321 case "\u{2011}": flush(); body += "<w:noBreakHyphen/>"322 case "\u{FFFC}": break323 default: buffer.unicodeScalars.append(u)324 }325 }326 flush()327 return body.isEmpty ? "" : "<w:r>" + rPr + body + "</w:r>"328 }329330 func fieldStart(_ instruction: String, rPr: String, deleted: Bool) -> String {331 let tag = deleted ? "w:delInstrText" : "w:instrText"332 return "<w:r>\(rPr)<w:fldChar w:fldCharType=\"begin\"/></w:r><w:r>\(rPr)<\(tag) xml:space=\"preserve\">" + XMLEscape.text(instruction)333 + "</\(tag)></w:r><w:r>\(rPr)<w:fldChar w:fldCharType=\"separate\"/></w:r>"334 }335336 func fieldXML(_ instruction: String, result: String, rPr: String, deleted: Bool) -> String {337 fieldStart(" \(instruction) ", rPr: rPr, deleted: deleted) + textRunXML(result, rPr: rPr, deleted: deleted) + "<w:r>\(rPr)<w:fldChar w:fldCharType=\"end\"/></w:r>"338 }339340 static func wordDatePicture(_ unicode: String) -> String {341 var out = ""342 var quoted = false343 var i = unicode.startIndex344 while i < unicode.endIndex {345 let rest = unicode[i...]346 if rest.hasPrefix("'") { quoted.toggle(); out.append("'"); i = unicode.index(after: i); continue }347 if !quoted {348 if rest.hasPrefix("EEEE") { out += "dddd"; i = unicode.index(i, offsetBy: 4); continue }349 if rest.hasPrefix("EEE") { out += "ddd"; i = unicode.index(i, offsetBy: 3); continue }350 if rest.hasPrefix("a") { out += "AM/PM"; i = unicode.index(after: i); continue }351 }352 out.append(unicode[i]); i = unicode.index(after: i)353 }354 return out355 }356357 func quoted(_ s: String) -> String { "\"" + s.replacingOccurrences(of: "\\", with: "\\\\").replacingOccurrences(of: "\"", with: "\\\"") + "\"" }358359 func runXML(_ run: Run, paragraph p: Paragraph, part: DocxPart, seqCounter: inout Int) -> String {360 let deleted = run.isDeleted361 guard let inline = run.inline else { return textRunXML(run.text, rPr: rPr(run), deleted: deleted) }362 let props = rPr(run)363 switch inline {364 case .image(let image):365 return imageXML(image, rPr: props, part: part)366 case .shape(let shape):367 return shapeXML(shape, rPr: props)368 case .equation(let e):369 var omml = MathConverter.omml(fromLatex: e.latex)370 if omml == nil {371 warn(.approximated, "Equations", "An equation uses LaTeX that cannot be converted to a Word equation; its source is exported as text inside the equation.")372 omml = "<m:oMath><m:r><m:rPr><m:nor/></m:rPr><m:t xml:space=\"preserve\">" + XMLEscape.text(e.latex) + "</m:t></m:r></m:oMath>"373 }374 return e.display ? "<m:oMathPara>" + omml! + "</m:oMathPara>" : omml!375 case .note(let ref):376 guard doc.notes[ref.id] != nil else {377 warn(.dropped, "Notes", "A note reference points to a note that does not exist; it is not exported.")378 return ""379 }380 let n = noteNumber(ref)381 let mark = rPrInner({ var c = run.props; c.link = nil; return c }(), style: run.charStyle, change: run.formatRevision, noteMark: true)382 return "<w:r><w:rPr>" + mark + "</w:rPr>" + xmlTag(ref.kind == .footnote ? "w:footnoteReference" : "w:endnoteReference", [("w:id", String(n))]) + "</w:r>"383 case .citation(let c):384 let enc = JSONEncoder()385 enc.outputFormatting = [.sortedKeys]386 let json = (try? enc.encode(c)).map { String(decoding: $0, as: UTF8.self) } ?? "{\"items\":[]}"387 let text: String388 if let f = options.citations {389 text = f.citationText(c, document: doc, numbering: numbering)390 } else {391 text = "(" + c.items.map(\.key).joined(separator: "; ") + ")"392 if !preflight { warn(.info, "Citations", "No citation formatter was supplied; citations show their keys as displayed text. The citation data itself is exported.") }393 }394 return fieldXML("\(DocxConvention.citationInstruction) \(json)", result: text, rPr: props, deleted: deleted)395 case .crossRef(let ref):396 let text = numbering.crossRefText(ref, pageOf: { id in self.options.pageOf?(id) })397 var name: String?398 var switches = ""399 if numbering.bookmarks[ref.target] != nil {400 name = ref.target401 } else if let kinds = refKinds[ref.target], let safe = refSafeIDs[ref.target] {402 let k: Character = ref.display == .labelAndNumber && kinds.contains("L") ? "L" : ref.display == .number && kinds.contains("N") ? "N" : "T"403 name = DocxConvention.refBookmark(kind: k, id: safe)404 if k != "T" { switches = "plain" }405 }406 guard let name else {407 warn(.approximated, "Cross-references", "A cross-reference whose target does not exist in the body is exported as plain text.")408 return textRunXML(text, rPr: props, deleted: deleted)409 }410 if ref.display == .page { return fieldXML("PAGEREF \(name) \\h", result: text, rPr: props, deleted: deleted) }411 var sw = ""412 if switches.isEmpty {413 if ref.display == .number { sw = " \\r" } else if ref.display == .labelAndNumber { sw = " \\w" }414 }415 return fieldXML("REF \(name)\(sw) \\h", result: text, rPr: props, deleted: deleted)416 case .field(let f):417 switch f {418 case .pageNumber: return fieldXML("PAGE", result: "1", rPr: props, deleted: deleted)419 case .pageCount: return fieldXML("NUMPAGES", result: String(options.pageCount ?? 1), rPr: props, deleted: deleted)420 case .date(let format):421 return fieldXML("DATE \\@ \(quoted(DocxExportContext.wordDatePicture(format)))", result: numbering.staticFieldText(f, document: doc) ?? "", rPr: props, deleted: deleted)422 case .title: return fieldXML("TITLE", result: doc.meta.title, rPr: props, deleted: deleted)423 case .author: return fieldXML("AUTHOR", result: doc.meta.author, rPr: props, deleted: deleted)424 case .sequence(let name):425 var value = "1"426 if !deleted {427 let values = numbering.sequences[p.id] ?? []428 if seqCounter < values.count { value = String(values[seqCounter]) }429 seqCounter += 1430 }431 let safe = name.contains(where: { $0.isWhitespace }) ? quoted(name) : name432 return fieldXML("SEQ \(safe) \\* ARABIC", result: value, rPr: props, deleted: deleted)433 case .headingText(let level):434 return fieldXML("STYLEREF \(quoted("heading \(max(1, min(9, level)))"))", result: "", rPr: props, deleted: deleted)435 }436 case .bookmark(let name):437 let id = takeID()438 return xmlTag("w:bookmarkStart", [("w:id", String(id)), ("w:name", name)]) + xmlTag("w:bookmarkEnd", [("w:id", String(id))])439 }440 }441442 func noteNumber(_ ref: NoteRef) -> Int {443 if ref.kind == .footnote {444 if let n = footnoteIDs[ref.id] { return n }445 footnoteOrder.append(ref.id)446 footnoteIDs[ref.id] = footnoteOrder.count447 return footnoteOrder.count448 }449 if let n = endnoteIDs[ref.id] { return n }450 endnoteOrder.append(ref.id)451 endnoteIDs[ref.id] = endnoteOrder.count452 return endnoteOrder.count453 }454455 // MARK: Drawings456457 func mediaTarget(_ assetID: String, part: DocxPart) -> String? {458 guard let asset = doc.assets[assetID] else {459 warn(.dropped, "Pictures", "A picture has no image data in the document and is not exported.")460 return nil461 }462 if media[assetID] == nil {463 let mime = DocxMedia.sniff(asset.data) ?? asset.mimeType464 let ext = DocxMedia.fileExtension(forMime: mime)465 if ["pdf", "heic", "webp", "svg", "bin"].contains(ext) {466 warn(.approximated, "Pictures", "A picture in \(ext.uppercased()) format is exported as it is; Word may not display this format.")467 }468 let name = "image\(media.count + 1).\(ext)"469 media[assetID] = name470 mediaOrder.append((name, assetID))471 }472 return part.rels.add(type: RelType.image, target: "media/" + media[assetID]!)473 }474475 /// The `wp:inline` or `wp:anchor` wrapper around a graphic.476 func drawingFrame(width: Double, height: Double, placement: Placement, name: String, alt: String, graphic: String) -> String {477 let id = nextDrawingID478 nextDrawingID += 1479 let extent = xmlTag("wp:extent", [("cx", DocxUnit.toEMU(width)), ("cy", DocxUnit.toEMU(height))]) + "<wp:effectExtent l=\"0\" t=\"0\" r=\"0\" b=\"0\"/>"480 let docPr = xmlTag("wp:docPr", [("id", String(id)), ("name", "\(name) \(id)"), ("descr", alt.isEmpty ? nil : alt)]) + "<wp:cNvGraphicFramePr/>"481 switch placement {482 case .inline:483 return "<w:drawing><wp:inline distT=\"0\" distB=\"0\" distL=\"0\" distR=\"0\">" + extent + docPr + graphic + "</wp:inline></w:drawing>"484 case .floating(let wrap, let align, let x, let y):485 var h: String486 if align == .left {487 h = "<wp:posOffset>" + DocxUnit.toEMU(x) + "</wp:posOffset>"488 } else {489 h = "<wp:align>" + (align == .center ? "center" : "right") + "</wp:align>"490 if x != 0 { warn(.approximated, "Floating object positions", "A horizontal offset combined with centred or right alignment is not exported; the alignment is.") }491 }492 let wrapXML: String493 switch wrap {494 case .square: wrapXML = "<wp:wrapSquare wrapText=\"bothSides\"/>"495 case .topAndBottom: wrapXML = "<wp:wrapTopAndBottom/>"496 case .behindText, .inFrontOfText: wrapXML = "<wp:wrapNone/>"497 }498 return "<w:drawing>" + xmlTag("wp:anchor", [("distT", "0"), ("distB", "0"), ("distL", "114300"), ("distR", "114300"), ("simplePos", "0"),499 ("relativeHeight", String(251658240 + id)), ("behindDoc", wrap == .behindText ? "1" : "0"), ("locked", "0"),500 ("layoutInCell", "1"), ("allowOverlap", "1")],501 "<wp:simplePos x=\"0\" y=\"0\"/><wp:positionH relativeFrom=\"column\">" + h + "</wp:positionH><wp:positionV relativeFrom=\"paragraph\"><wp:posOffset>"502 + DocxUnit.toEMU(y) + "</wp:posOffset></wp:positionV>" + extent + wrapXML + docPr + graphic) + "</w:drawing>"503 }504 }505506 func imageXML(_ image: ImageObject, rPr: String, part: DocxPart) -> String {507 guard let rid = mediaTarget(image.asset, part: part) else { return "" }508 func pct(_ v: Double) -> String { String(DocxUnit.safeInt(max(0, min(1, v.isFinite ? v : 0)) * 100_000)) }509 var blipFill = "<pic:blipFill>" + xmlTag("a:blip", [("r:embed", rid)])510 if image.crop != .zero { blipFill += xmlTag("a:srcRect", [("l", pct(image.crop.left)), ("t", pct(image.crop.top)), ("r", pct(image.crop.right)), ("b", pct(image.crop.bottom))]) }511 blipFill += "<a:stretch><a:fillRect/></a:stretch></pic:blipFill>"512 let rot = image.rotation != 0 ? String(DocxUnit.safeInt(image.rotation * 60_000)) : nil513 let spPr = "<pic:spPr>" + xmlTag("a:xfrm", [("rot", rot)], "<a:off x=\"0\" y=\"0\"/>" + xmlTag("a:ext", [("cx", DocxUnit.toEMU(image.width)), ("cy", DocxUnit.toEMU(image.height))]))514 + "<a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></pic:spPr>"515 let nv = "<pic:nvPicPr>" + xmlTag("pic:cNvPr", [("id", "0"), ("name", media[image.asset] ?? "image"), ("descr", image.altText.isEmpty ? nil : image.altText)]) + "<pic:cNvPicPr/></pic:nvPicPr>"516 let graphic = "<a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\"><pic:pic>" + nv + blipFill + spPr + "</pic:pic></a:graphicData></a:graphic>"517 return "<w:r>" + rPr + drawingFrame(width: image.width, height: image.height, placement: image.placement, name: "Picture", alt: image.altText, graphic: graphic) + "</w:r>"518 }519520 func shapeXML(_ shape: ShapeObject, rPr: String) -> String {521 let prst: String522 switch shape.kind {523 case .rectangle: prst = "rect"524 case .roundedRectangle: prst = "roundRect"525 case .ellipse: prst = "ellipse"526 case .line, .arrow: prst = "line"527 case .callout: prst = "wedgeRectCallout"528 }529 var spPr = "<a:xfrm><a:off x=\"0\" y=\"0\"/>" + xmlTag("a:ext", [("cx", DocxUnit.toEMU(shape.width)), ("cy", DocxUnit.toEMU(shape.height))]) + "</a:xfrm>"530 spPr += "<a:prstGeom prst=\"\(prst)\"><a:avLst/></a:prstGeom>"531 spPr += shape.fill.map { "<a:solidFill>" + xmlTag("a:srgbClr", [("val", $0.hexString)]) + "</a:solidFill>" } ?? "<a:noFill/>"532 if shape.strokeWidth <= 0 {533 spPr += "<a:ln><a:noFill/></a:ln>"534 } else {535 spPr += xmlTag("a:ln", [("w", DocxUnit.toEMU(shape.strokeWidth))], "<a:solidFill>" + xmlTag("a:srgbClr", [("val", shape.stroke.hexString)]) + "</a:solidFill>"536 + (shape.kind == .arrow ? "<a:tailEnd type=\"triangle\"/>" : ""))537 }538 var txbx = ""539 if !shape.text.isEmpty {540 let lines = shape.text.components(separatedBy: "\n")541 var runs = ""542 for (i, line) in lines.enumerated() {543 if i > 0 { runs += "<w:r><w:br/></w:r>" }544 runs += textRunXML(line, rPr: "", deleted: false)545 }546 txbx = "<wps:txbx><w:txbxContent><w:p><w:pPr><w:jc w:val=\"center\"/></w:pPr>" + runs + "</w:p></w:txbxContent></wps:txbx>"547 }548 let graphic = "<a:graphic><a:graphicData uri=\"http://schemas.microsoft.com/office/word/2010/wordprocessingShape\"><wps:wsp><wps:cNvSpPr/><wps:spPr>"549 + spPr + "</wps:spPr>" + txbx + "<wps:bodyPr anchor=\"ctr\"/></wps:wsp></a:graphicData></a:graphic>"550 return "<w:r>" + rPr + "<mc:AlternateContent><mc:Choice Requires=\"wps\">"551 + drawingFrame(width: shape.width, height: shape.height, placement: shape.placement, name: "Shape", alt: shape.altText, graphic: graphic)552 + "</mc:Choice></mc:AlternateContent></w:r>"553 }554555 // MARK: Tables556557 func tableXML(_ t: Table, part: DocxPart) -> String {558 let styleID = tableStyleID(t.style)559 let columns = max(1, t.columnCount)560 var s = "<w:tbl><w:tblPr>" + xmlTag("w:tblStyle", [("w:val", styleID)]) + xmlTag("w:tblW", [("w:w", DocxUnit.toTwips(t.totalWidth)), ("w:type", "dxa")])561 if t.alignment != .left { s += xmlTag("w:jc", [("w:val", t.alignment == .center ? "center" : "right")]) }562 s += tableBordersXML(t.style) + "<w:tblLayout w:type=\"fixed\"/>" + cellMarginsXML(t.style.cellPadding)563 s += xmlTag("w:tblLook", [("w:val", "04A0"), ("w:firstRow", t.rows.first?.isHeader == true ? "1" : "0"), ("w:lastRow", "0"), ("w:firstColumn", "0"),564 ("w:lastColumn", "0"), ("w:noHBand", t.style.bandedRowShading == nil ? "1" : "0"), ("w:noVBand", "1")])565 s += "</w:tblPr><w:tblGrid>"566 for w in t.columnWidths { s += xmlTag("w:gridCol", [("w:w", DocxUnit.toTwips(w))]) }567 if t.columnWidths.isEmpty { s += "<w:gridCol w:w=\"1440\"/>" }568 s += "</w:tblGrid>"569 for row in t.rows {570 var r = ""571 var trPr = ""572 if let h = row.minHeight { trPr += xmlTag("w:trHeight", [("w:val", DocxUnit.toTwips(h)), ("w:hRule", "atLeast")]) }573 if row.isHeader { trPr += "<w:tblHeader/>" }574 if !trPr.isEmpty { r += "<w:trPr>" + trPr + "</w:trPr>" }575 var col = 0576 for cell in row.cells {577 let span = max(1, min(cell.colSpan, max(1, columns - col)))578 let width = t.columnWidths.isEmpty ? 72 : t.columnWidths[min(col, columns - 1)..<min(col + span, columns)].reduce(0, +)579 col += span580 var tcPr = xmlTag("w:tcW", [("w:w", DocxUnit.toTwips(width)), ("w:type", "dxa")])581 if span > 1 { tcPr += xmlTag("w:gridSpan", [("w:val", String(span))]) }582 switch cell.vMerge {583 case .restart: tcPr += "<w:vMerge w:val=\"restart\"/>"584 case .continue: tcPr += "<w:vMerge/>"585 case .none: break586 }587 if cell.borderTop != nil || cell.borderBottom != nil || cell.borderLeft != nil || cell.borderRight != nil {588 var b = ""589 if let l = cell.borderTop { b += borderXML("w:top", l) }590 if let l = cell.borderLeft { b += borderXML("w:left", l) }591 if let l = cell.borderBottom { b += borderXML("w:bottom", l) }592 if let l = cell.borderRight { b += borderXML("w:right", l) }593 tcPr += "<w:tcBorders>" + b + "</w:tcBorders>"594 }595 if let f = cell.shading { tcPr += shadingXML(f) }596 if cell.vAlign != .top { tcPr += xmlTag("w:vAlign", [("w:val", cell.vAlign == .center ? "center" : "bottom")]) }597 var content = ""598 let paragraphs = cell.paragraphs.isEmpty ? [Paragraph()] : cell.paragraphs599 for (i, p) in paragraphs.enumerated() { content += paragraphXML(p, part: part, formula: i == 0 ? cell.formula : nil) }600 r += "<w:tc><w:tcPr>" + tcPr + "</w:tcPr>" + content + "</w:tc>"601 }602 if row.cells.isEmpty { r += "<w:tc><w:p/></w:tc>" }603 s += "<w:tr>" + r + "</w:tr>"604 }605 if t.rows.isEmpty { s += "<w:tr><w:tc><w:p/></w:tc></w:tr>" }606 return s + "</w:tbl>"607 }608609 // MARK: Generated blocks610611 func tocXML(_ toc: TOCBlock) -> String {612 var entries: [(style: String, text: String, id: String)] = []613 let instruction: String614 switch toc.kind {615 case .contents:616 let maxLevel = max(1, min(9, toc.maxLevel))617 instruction = "TOC \\o \"1-\(maxLevel)\" \\h \\z \\u"618 for e in numbering.outline where e.level <= maxLevel {619 entries.append((StyleID.toc(e.level), (e.number.map { $0 + " " } ?? "") + e.text, e.id))620 }621 case .figures, .tables:622 let label = toc.kind == .figures ? "Figure" : "Table"623 instruction = "TOC \\h \\z \\c \"\(label)\""624 for (id, c) in numbering.captions.filter({ $0.value.label == label }).sorted(by: { $0.value.blockIndex != $1.value.blockIndex ? $0.value.blockIndex < $1.value.blockIndex : $0.value.number < $1.value.number }) {625 entries.append((StyleID.toc(1), c.text, id))626 }627 }628 if options.pageOf == nil, !entries.isEmpty, !preflight {629 warn(.info, "Table of contents", "No page layout was supplied; the contents are exported without page numbers until Word updates the field.")630 }631 var inner = ""632 if let title = toc.title, !title.isEmpty {633 inner += "<w:p><w:pPr>" + xmlTag("w:pStyle", [("w:val", StyleID.tocHeading)]) + "</w:pPr>" + textRunXML(title, rPr: "", deleted: false) + "</w:p>"634 }635 let begin = fieldStart(" \(instruction) ", rPr: "", deleted: false)636 if entries.isEmpty {637 inner += "<w:p>" + begin + "</w:p>"638 } else {639 for (i, e) in entries.enumerated() {640 var runs = textRunXML(e.text, rPr: "", deleted: false)641 if let page = options.pageOf?(e.id) { runs += textRunXML("\t" + page, rPr: "", deleted: false) }642 inner += "<w:p><w:pPr>" + xmlTag("w:pStyle", [("w:val", e.style)]) + "</w:pPr>" + (i == 0 ? begin : "") + runs + "</w:p>"643 }644 }645 inner += "<w:p><w:r><w:fldChar w:fldCharType=\"end\"/></w:r></w:p>"646 return "<w:sdt><w:sdtPr><w:docPartObj><w:docPartGallery w:val=\"Table of Contents\"/><w:docPartUnique/></w:docPartObj></w:sdtPr><w:sdtContent>" + inner + "</w:sdtContent></w:sdt>"647 }648649 func bibliographyXML(_ block: BibliographyBlock, part: DocxPart) -> String {650 var paragraphs: [Paragraph]651 if let f = options.citations {652 paragraphs = f.bibliographyParagraphs(document: doc, numbering: numbering)653 } else {654 paragraphs = numbering.citedKeys.compactMap { key in655 guard let e = doc.bibEntry(key) else { return nil }656 let authors = e.authors.map { $0.literal ?? [$0.family, $0.given].filter { !$0.isEmpty }.joined(separator: ", ") }.joined(separator: "; ")657 let text = [authors, e.year.map { "(\($0))" } ?? "", e.title].filter { !$0.isEmpty }.joined(separator: " ")658 return Paragraph(text.isEmpty ? key : text + ".", style: StyleID.bibliography)659 }660 if !preflight, !numbering.citedKeys.isEmpty {661 warn(.info, "Bibliography", "No citation formatter was supplied; the bibliography is exported as a plain list. The reference data itself is exported.")662 }663 }664 var inner = ""665 var pr = ""666 if let title = block.title, !title.isEmpty {667 pr += xmlTag("w:alias", [("w:val", title)])668 inner += "<w:p><w:pPr>" + xmlTag("w:pStyle", [("w:val", StyleID.tocHeading)]) + "</w:pPr>" + textRunXML(title, rPr: "", deleted: false) + "</w:p>"669 }670 pr += xmlTag("w:tag", [("w:val", DocxConvention.bibliographyTag)])671 for p in paragraphs { inner += paragraphXML(p, part: part) }672 if inner.isEmpty { inner = "<w:p/>" }673 return "<w:sdt><w:sdtPr>" + pr + "</w:sdtPr><w:sdtContent>" + inner + "</w:sdtContent></w:sdt>"674 }675676 // MARK: Notes and comments677678 func notesXML(_ kind: NoteRef.Kind, part: DocxPart) -> String? {679 let root = kind == .footnote ? "w:footnotes" : "w:endnotes"680 let item = kind == .footnote ? "w:footnote" : "w:endnote"681 var inner = "<\(item) w:type=\"separator\" w:id=\"-1\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:separator/></w:r></w:p></\(item)>"682 inner += "<\(item) w:type=\"continuationSeparator\" w:id=\"0\"><w:p><w:pPr><w:spacing w:after=\"0\" w:line=\"240\" w:lineRule=\"auto\"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></\(item)>"683 // Notes can only be reached from the body, so the list is complete once the body is written.684 var index = 0685 while index < (kind == .footnote ? footnoteOrder : endnoteOrder).count {686 let id = (kind == .footnote ? footnoteOrder : endnoteOrder)[index]687 index += 1688 let paragraphs = doc.notes[id]?.paragraphs ?? []689 var body = ""690 for (i, p) in (paragraphs.isEmpty ? [Paragraph(style: StyleID.footnoteText)] : paragraphs).enumerated() {691 body += paragraphXML(p, part: part, noteMark: i == 0 ? kind : nil)692 }693 inner += xmlTag(item, [("w:id", String(index))], body)694 }695 let used = Set(kind == .footnote ? footnoteOrder : endnoteOrder)696 let unused = doc.notes.values.filter { $0.kind == kind && !used.contains($0.id) }.count697 if unused > 0 { warn(.dropped, "Notes", "\(unused) note(s) that no text refers to are not exported.") }698 if index == 0 { return nil }699 return xmlDeclaration + xmlTag(root, DocxExportContext.rootNamespaces, inner)700 }701702 func commentsXML() -> (comments: String, extended: String)? {703 guard !doc.comments.isEmpty else { return nil }704 var comments = "", extended = ""705 var para = 0706 func initials(_ author: String) -> String {707 String(author.split(separator: " ").compactMap(\.first).prefix(3)).uppercased()708 }709 func write(_ wid: Int, author: String, date: Date, text: String) -> String {710 var body = ""711 var lastPara = ""712 let lines = text.components(separatedBy: "\n")713 for (i, line) in lines.enumerated() {714 para += 1715 lastPara = String(format: "0C%06X", para)716 body += "<w:p w14:paraId=\"\(lastPara)\">" + (i == 0 ? "<w:r><w:annotationRef/></w:r>" : "") + textRunXML(line, rPr: "", deleted: false) + "</w:p>"717 }718 comments += xmlTag("w:comment", [("w:id", String(wid)), ("w:author", author), ("w:date", DocxDate.string(date)), ("w:initials", initials(author))], body)719 return lastPara720 }721 for c in doc.comments {722 guard let ids = commentWordIDs[c.id], ids.count == c.replies.count + 1 else { continue }723 let parent = write(ids[0], author: c.author, date: c.date, text: c.text)724 extended += xmlTag("w15:commentEx", [("w15:paraId", parent), ("w15:done", c.resolved ? "1" : "0")])725 for (k, r) in c.replies.enumerated() {726 let child = write(ids[k + 1], author: r.author, date: r.date, text: r.text)727 extended += xmlTag("w15:commentEx", [("w15:paraId", child), ("w15:paraIdParent", parent), ("w15:done", c.resolved ? "1" : "0")])728 }729 }730 return (xmlDeclaration + xmlTag("w:comments", DocxExportContext.rootNamespaces, comments),731 xmlDeclaration + xmlTag("w15:commentsEx", [("xmlns:w15", XMLNS.w15), ("xmlns:mc", XMLNS.mc), ("mc:Ignorable", "w15")], extended))732 }733}734