DOCX engine (DocDOCX)
DocDOCX converts between a WordprocessingML package and DocumentModel. It depends on DocModel and DocContainer
(ZIP reader / writer, FormatWarning, ImportResult, ExportResult, FormatError) and on Foundation only.
Public API
public enum DocxImporter {
public static func importDocument(_ data: Data, limits: ZipLimits = .standard) throws -> ImportResult
}
public struct DocxExportOptions: Sendable {
public var citations: (any CitationFormatting)?
public var pageOf: (@Sendable (String) -> String?)?
public var pageCount: Int?
public init()
}
public enum DocxExporter {
public static func export(_ doc: DocumentModel, options: DocxExportOptions = .init()) throws -> ExportResult
public static func preflight(_ doc: DocumentModel) -> [FormatWarning]
}
public enum MathConverter {
public static func omml(fromLatex latex: String) -> String?
public static func latex(fromOMML xml: String) -> String?
public static func mathML(fromLatex latex: String, display: Bool) -> String?
}Errors are FormatError (unreadable, tooLarge, integrityCheckFailed); archive errors are mapped to it.
preflight runs the exporter without keeping its output and returns its warnings, most severe first, so what the user is
told before exporting is exactly what the export would report.
Files
| File | Role |
|---|---|
XML.swift |
XMLNode tree, XMLTree.parse (Foundation XMLParser, no DTD, size / depth / node limits, namespace prefixes canonicalised from their URI, strict namespaces included), XMLEscape, xmlTag |
DocxCommon.swift |
units, colours, dates, relationship and content types, OPC path resolution, media sniffing, shared conventions (DocxConvention), the ORIX extras payload, DocxStack |
DocxImporter.swift |
entry point, package level: main part, theme fonts, extras, settings, core properties, classification of every remaining part (preserved / dropped with a named warning) |
DocxImportStyles.swift |
rPr / pPr → CharProps / ParaProps, styles.xml, table styles, numbering.xml, sectPr → PageSetup |
DocxImportBody.swift |
stories, blocks, paragraphs, runs, tracked changes, comment ranges, bookmarks, hyperlinks, the field state machine, notes, comments, headers / footers |
DocxImportObjects.swift |
tables, DrawingML pictures and shapes, text boxes, VML |
DocxExporter.swift |
entry point, package assembly, styles, numbering, settings, core properties, sections, headers / footers |
DocxExportBody.swift |
rPr / pPr writers, paragraphs, runs, fields, drawings, tables, generated blocks, notes, comments |
MathConverter.swift, MathOMML.swift, MathMLWriter.swift |
LaTeX parser and tree, tree ↔ OMML, tree → presentation MathML |
Import
ZipReaderopens the archive under the caller'sZipLimits.[Content_Types].xmland the package relationships locate the main part (.docx,.docmand.dotxmain parts are all accepted; macros are reported and ignored).- Theme fonts are read from the theme part (which itself stays a preserved part). The ORIX extras part, if any, restores the bibliography database and document settings.
settings.xml,styles.xml,numbering.xml, notes and comments parts are parsed into lookup tables. Style ids are mapped to the model's built-in ids through the Word style name (heading 1→Heading1), so localised documents keep their semantics.- The body is walked once. A
DocxStoryholds the state that spans paragraphs (open comment ranges, the field stack, open bookmarks); aDocxParaBuilderholds one paragraph. Notes are imported when their reference is met; headers and footers when asectPrrefers to them. - Sections are resolved after the walk (see below), cross-reference displays are fixed up once all bookmarks are known, core properties are read, and every part that was not interpreted is either preserved or reported.
Fields
Complex fields (w:fldChar begin / separate / end) and w:fldSimple feed one state machine. At separate the instruction is
classified: fields the model knows become an inline object and their cached result is suppressed; HYPERLINK keeps its
result and marks it as a link; TOC becomes one TOCBlock and swallows its cached paragraphs; a table formula goes to the
cell; anything else keeps its displayed text and raises a warning. Nested fields are handled by the stack; a field that would
be replaced by an inline object is closed at the end of its paragraph even if its end mark is missing.
Sections
Word stores the properties of a section in the last paragraph of that section and the last section's at the end of the body.
The model stores pageSetup for the first section and, on each .sectionBreak, the setup of the section that starts there.
On import the sectPr elements are collected in order (S0 … Sn); pageSetup = S0, and the break placed after the paragraph
that carried Si receives S(i+1) together with its w:type (which says how section i+1 starts). Headers and footers a
section does not declare are copied from the previous section (new paragraph ids). On export the mapping is inverted: the
paragraph before a break carries the sectPr of the section it ends; when no paragraph is there, an empty one is written.
Export
DocxExportContext.prepare() computes what must be known before the first paragraph: numbering ids, the first and last run of
every comment (comment ranges), and which paragraphs are cross-reference targets. The body is written first because it decides
which notes, pictures, table styles and header parts exist; then notes, comments, styles, numbering, settings, properties,
preserved parts and the extras part. Element order follows the ECMA-376 schema sequences (pPr, rPr, tblPr, tcPr,
sectPr, settings, style, lvl). The ZIP writer uses a fixed timestamp, so the same model and options give the same bytes
(except for DATE fields, whose cached text is today's date).
Conventions that make the round trip exact
| Convention | Why |
|---|---|
Hidden bookmarks _ORIX_T_<id>, _ORIX_L_<id>, _ORIX_N_<id> |
A CrossRef targets a paragraph id. The bookmark covers the whole paragraph (T), the label and number of a caption (L) or the number alone (N), so Word's own REF field shows the right text, and the importer gives the paragraph its id back |
Field ADDIN ORIX_CITATION {json} |
Keeps the full Citation; Word shows the cached text and never rewrites an ADDIN field |
Custom XML data part, root orix:document |
Bibliography database, citation style, smart-typing settings, theme name |
Content control tagged ORIX_BIBLIOGRAPHY (title in w:alias) |
Marks the generated bibliography so it is not reimported as text |
Table styles ORIXTable<n> |
Carry TableStyle (borders, padding, header and band shading) as real Word table styles |
| Hidden one-point paragraph after a table | Word merges adjacent tables and needs a paragraph at the end of the document; the importer recognises and removes it |
w:aliases on built-in styles |
Word sees heading 1; the ORIX display name comes back |
| Superscript on note reference runs | The model draws note marks itself; the importer strips the superscript and the reference style Word puts there |
Identifiers of paragraphs, tables, lists, notes, comments and revisions are regenerated on import (DocID.make()); image
assets are identified by content (img<crc><size>), which also deduplicates them. Tests compare models with identifiers
normalised by order of appearance (normalized(_:) in TestSupport.swift).
Security model
- Input is hostile. Limits:
ZipLimitsfor the archive;XMLLimitsfor each part (96 MB, depth 256, 4 million elements); custom XML and extras payloads are size-capped before parsing. XMLTree.parserefuses any part that contains<!DOCTYPEor<!ENTITY(after transcoding UTF-16), and setsshouldResolveExternalEntities = false. OOXML never needs a DTD.OPC.resolvemaps a relationship target to a part name inside the archive, or to nil. Nothing is read from the file system or the network: external targets are strings.- Macro, OLE and ActiveX parts are never interpreted and never put in
preservedParts. Preservation is an allow-list of part names, each part must be well-formed XML, and its relationships must stay inside the preserved set. The exporter re-validatespreservedParts, because a model can also come from an untrusted.orixdoc. - Numbers read from XML are range-checked before conversion; numbers written from the model go through
DocxUnit.safeInt. - Recursion depth is bounded by the XML depth limit, and the work runs on a 32 MB stack (
DocxStack).
Testing
See docs/compatibility/docx.md for what is validated against which tool, and docs/reports/docx-compatibility.md for the
measured results. Scripts/docx-compat.sh regenerates the report.
cd Packages/ORIXDocsKit
ORIX_ONLY=DocModel,DocContainer,DocDOCX,DocDOCXTests swift test --scratch-path /tmp/orixdocs-docx
ORIX_SLOW_TESTS=1 ORIX_ONLY=DocModel,DocContainer,DocDOCX,DocDOCXTests swift test --scratch-path /tmp/orixdocs-docx # adds LibreOffice