oficina / docs Public

Docx: a bounded token walk replaces the paragraph/font reader.

Import reads a .docx into paragraphs, headings and text runs and returns
a report of codes, counts and paragraph numbers. It walks the nested
containers Google exports text in (hyperlink, tbl/tr/tc including nested
tables, ins/moveTo, sdt at block and run level, smartTag, customXml,
fldSimple), omits w:del/moveFrom text and reports it, honours w:val on
b/i, turns tabs into spaces and line/page breaks into paragraph breaks,
and reports lists and tables flattened, links kept as text, titles and
subtitles, unknown faces, off-ladder sizes, lost underline/strike/colour/
highlight/raise/caps, alignment, images and other objects, notes,
comments and headers/footers. Relationships are never read, so no link
target or external source reaches anything.

Bounds are counted here: 1000 entries, duplicate names refused, 32 MiB
per part and 64 MiB in all by bytes actually decompressed, depth 256 on
every element including skipped ones, DTDs refused, and 10,000 blocks,
40,000 runs and 2 MiB of text out (the builder's measured budget).

Run against the old Read, 11 of the 13 regression cases failed (link,
table, insertion, both content controls, smart tag, field, bold-off,
italic-off, tab, break). All fixtures are SYNTHESIZED in Google's shapes;
no real Google export has been supplied.

Pins estilo at main 7a19588 (googleimport, reviewed in oficina/estilo #31).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 25fc493a089025b47bf5b887ae57ac7ae6bd6da2 parent 056b94d
6 files changed, +1,433 −143
  • go.mod +1 −1
  • go.sum +6 −0
  • internal/docx/docx.go +6 −140
  • internal/docx/docx_test.go +17 −2
  • internal/docx/read.go +990 −0
  • internal/docx/read_test.go +413 −0

CI passed — run details

diff --git a/go.mod b/go.mod
index 31ed322..f94514d 100644
--- a/go.mod
+++ b/go.mod
@@ -3,7 +3,7 @@ module github.com/carlosframework/docs
go 1.26.5
require (
- amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796
+ amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f
amadan.net/oficina/home/dashboard v0.0.0-20261024235511-baa2503c7064
amadan.net/oficina/home/handoff v0.0.0-20260908102137-481d2d57f489
amadan.net/oficina/home/roster v0.0.0-20261030153823-602f5136f9af
diff --git a/go.sum b/go.sum
index 4f51c46..f94496d 100644
--- a/go.sum
+++ b/go.sum
@@ -1,5 +1,11 @@
amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796 h1:yj3d1pKgMbZ3e+7zTf+SWdGYux4E0hhnCOr4YJxH9VE=
amadan.net/oficina/estilo.git v0.0.0-20261026205409-aa90aaceb796/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/estilo.git v0.0.0-20261101213228-18723a1e6627 h1:Ho6CAPKOwo48o+xc8AuWwHPfsM+3HUDOo2QI7axWyx4=
+amadan.net/oficina/estilo.git v0.0.0-20261101213228-18723a1e6627/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/estilo.git v0.0.0-20261101213922-514481f1b646 h1:TPwSheQuCpIGy60LnjQhE1AxEqE1n5MmQY45hBBH2Eo=
+amadan.net/oficina/estilo.git v0.0.0-20261101213922-514481f1b646/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
+amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f h1:SxWyFCGQwmxhSQPUT2SN04p9dyzUhElb7yuHDMH7HuQ=
+amadan.net/oficina/estilo.git v0.0.0-20261101213957-7a19588e736f/go.mod h1:4u0jNBtIdMLOsJyrScfqoEuYDJF7BBM3qM9YWbzt6aw=
amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4 h1:WQ4irMKZerybbbccJblyukiloZZ9zfIxcay4vVyVowU=
amadan.net/oficina/home/connect v0.0.0-20261028165624-d942439ac4e4/go.mod h1:ix81eFV87yE9f2SXiRuxYCVM4lAgTRC5YoQMiH3+TDk=
amadan.net/oficina/home/connect v0.0.0-20261030153823-602f5136f9af h1:jAQ3F8iqqR+z3dnkzmcMmPadX6vZ82adqGlGQMh0GkM=
diff --git a/internal/docx/docx.go b/internal/docx/docx.go
index 680a24c..89a886e 100644
--- a/internal/docx/docx.go
+++ b/internal/docx/docx.go
@@ -8,13 +8,12 @@
// Carlito and Cambria Caladea. The names are internal/fonts' manifest
// (Docx.Name, and ByDocxName for the way back).
//
-// Docs has no DOCX import or export yet (spec §11.2/§11.3). This package
-// is deliberately only what the font rulings need, so that the feature
-// builds on it rather than re-deciding them: paragraphs and headings,
-// runs with their family, weight, slope and size, the document default
-// in w:docDefaults and every family named in fontTable.xml. Lists,
-// tables, images and links are not written yet, and Read reads only
-// paragraph text and run formatting. Nothing routes to it.
+// Write is deliberately only what the font rulings need: paragraphs and
+// headings, runs with their family, weight, slope and size, the document
+// default in w:docDefaults and every family named in fontTable.xml.
+// Lists, tables, images and links are not written yet, and nothing routes
+// to Write. Import (read.go) is the reading half, used by the import page
+// (spec §11.2 and implementation/google-drive-import.md).
package docx
import (
@@ -24,15 +23,12 @@ import (
"fmt"
"io"
"sort"
- "strconv"
"strings"
"github.com/carlosframework/docs/internal/export"
"github.com/carlosframework/docs/internal/fonts"
)
-const wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
-
// Write writes doc as a .docx.
func Write(doc export.Document) ([]byte, error) {
used := map[*fonts.Family]bool{fonts.Default: true}
@@ -195,133 +191,3 @@ const documentRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
`<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>` +
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/fontTable" Target="fontTable.xml"/>` +
`</Relationships>`
-
-// Read reads a .docx's paragraphs and their runs' formatting. Each run's
-// face comes from its own w:rFonts, else the document's w:docDefaults;
-// a Word face with a twin here becomes the twin (Calibri is Carlito,
-// Cambria is Caladea), and a run in Docs' own default carries no mark.
-// A face Docs does not have reads as the default and is reported in
-// unknown, for the import report spec §11.2 requires.
-func Read(data []byte) (doc export.Document, unknown []string, err error) {
- z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
- if err != nil {
- return doc, nil, fmt.Errorf("docx: %w", err)
- }
- part := func(name string) ([]byte, error) {
- for _, f := range z.File {
- if f.Name == name {
- r, err := f.Open()
- if err != nil {
- return nil, err
- }
- defer r.Close()
- return io.ReadAll(io.LimitReader(r, 64<<20))
- }
- }
- return nil, nil
- }
- missing := map[string]bool{}
- resolve := func(name string) *fonts.Family {
- if name == "" {
- return nil
- }
- f, ok := fonts.ByDocxName(name)
- if !ok {
- missing[name] = true
- return nil
- }
- return f
- }
-
- base := fonts.Default
- if s, err := part("word/styles.xml"); err != nil {
- return doc, nil, err
- } else if s != nil {
- var st struct {
- Fonts struct {
- ASCII string `xml:"ascii,attr"`
- } `xml:"docDefaults>rPrDefault>rPr>rFonts"`
- }
- if err := xml.Unmarshal(s, &st); err != nil {
- return doc, nil, fmt.Errorf("docx: styles.xml: %w", err)
- }
- if f := resolve(st.Fonts.ASCII); f != nil {
- base = f
- }
- }
-
- d, err := part("word/document.xml")
- if err != nil {
- return doc, nil, err
- }
- if d == nil {
- return doc, nil, fmt.Errorf("docx: no word/document.xml")
- }
- type val struct {
- Val string `xml:"val,attr"`
- }
- var parsed struct {
- Body struct {
- Paragraphs []struct {
- Style val `xml:"pPr>pStyle"`
- Runs []struct {
- Fonts struct {
- ASCII string `xml:"ascii,attr"`
- } `xml:"rPr>rFonts"`
- Bold *struct{} `xml:"rPr>b"`
- Italic *struct{} `xml:"rPr>i"`
- Size val `xml:"rPr>sz"`
- Text []string `xml:"t"`
- } `xml:"r"`
- } `xml:"p"`
- } `xml:"body"`
- }
- if err := xml.Unmarshal(d, &parsed); err != nil {
- return doc, nil, fmt.Errorf("docx: document.xml: %w", err)
- }
-
- doc.Root = export.Node{Type: "doc"}
- for _, p := range parsed.Body.Paragraphs {
- block := export.Node{Type: "paragraph"}
- if lvl, ok := strings.CutPrefix(p.Style.Val, "Heading"); ok {
- if n, err := strconv.Atoi(lvl); err == nil && n >= 1 && n <= 6 {
- block = export.Node{Type: "heading", Attrs: export.Attrs{Level: n}}
- }
- }
- for _, r := range p.Runs {
- text := strings.Join(r.Text, "")
- if text == "" {
- continue
- }
- run := export.Node{Type: "text", Text: text}
- family := base
- if f := resolve(r.Fonts.ASCII); f != nil {
- family = f
- }
- if family != fonts.Default {
- run.Marks = append(run.Marks, export.Mark{Type: family.Mark()})
- }
- if half, err := strconv.Atoi(r.Size.Val); err == nil {
- for _, mark := range export.SizeMarks() {
- if pt, ok := export.SizePt(mark); ok && int(pt*2) == half {
- run.Marks = append(run.Marks, export.Mark{Type: mark})
- break
- }
- }
- }
- if r.Bold != nil {
- run.Marks = append(run.Marks, export.Mark{Type: "strong"})
- }
- if r.Italic != nil {
- run.Marks = append(run.Marks, export.Mark{Type: "em"})
- }
- block.Content = append(block.Content, run)
- }
- doc.Root.Content = append(doc.Root.Content, block)
- }
- for name := range missing {
- unknown = append(unknown, name)
- }
- sort.Strings(unknown)
- return doc, unknown, nil
-}
diff --git a/internal/docx/docx_test.go b/internal/docx/docx_test.go
index b551df6..7c092eb 100644
--- a/internal/docx/docx_test.go
+++ b/internal/docx/docx_test.go
@@ -75,10 +75,14 @@ func TestCarlitoAndCaladeaRoundTripAsCalibriAndCambria(t *testing.T) {
t.Error("Inter does not tell Word what to fall back to")
}
- back, unknown, err := docx.Read(data)
+ res, err := docx.Import(data)
if err != nil {
t.Fatal(err)
}
+ back, unknown := res.Document, unknownFaces(res.Report)
+ if len(res.Report.Items) > 0 {
+ t.Errorf("a document Docs wrote imports with losses: %+v", res.Report.Items)
+ }
if len(unknown) > 0 {
t.Errorf("faces Docs ships came back unknown: %v", unknown)
}
@@ -127,10 +131,11 @@ func TestImportingWordsDefaults(t *testing.T) {
{"Calibri", "Wingdings", "", "Wingdings"},
} {
data := wordFile(t, c.defaultFace, c.runFace)
- doc, unknown, err := docx.Read(data)
+ res, err := docx.Import(data)
if err != nil {
t.Fatal(err)
}
+ doc, unknown := res.Document, unknownFaces(res.Report)
var marks []string
for _, m := range doc.Root.Content[0].Content[0].Marks {
marks = append(marks, m.Type)
@@ -161,3 +166,13 @@ func wordFile(t *testing.T, defaultFace, runFace string) []byte {
z.Close()
return buf.Bytes()
}
+
+// unknownFaces is the face names the report says were substituted.
+func unknownFaces(r docx.Report) []string {
+ for _, it := range r.Items {
+ if it.Code == docx.CodeFontSubstituted {
+ return it.Names
+ }
+ }
+ return nil
+}
diff --git a/internal/docx/read.go b/internal/docx/read.go
new file mode 100644
index 0000000..83d76c5
--- /dev/null
+++ b/internal/docx/read.go
@@ -0,0 +1,990 @@
+package docx
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/xml"
+ "errors"
+ "io"
+ "slices"
+ "sort"
+ "strconv"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ "github.com/carlosframework/docs/internal/export"
+ "github.com/carlosframework/docs/internal/fonts"
+)
+
+// Import reads a .docx into the paragraphs, headings and text runs Docs
+// can hold, and reports everything it could not bring in and where.
+//
+// It is a bounded token walk rather than an unmarshal into structs,
+// because the text that matters is nested: Google Docs exports a link
+// as w:p>w:hyperlink>w:r, a table as w:tbl>w:tr>w:tc>w:p, a suggestion
+// as w:ins or w:del around runs, and some content under w:sdt or
+// w:smartTag. The reader this replaced bound w:body>w:p>w:r>w:t alone
+// and dropped all of that without a word, and read <w:b w:val="0"/> as
+// bold. Every container below is walked for its text; what Docs cannot
+// represent is flattened or omitted and reported.
+//
+// The bounds are this package's, not the XML decoder's: encoding/xml
+// does not limit depth, and a ZIP header's sizes are claims, so entry
+// count, the bytes actually decompressed, element depth and the output's
+// blocks, runs and text are all counted here. Nothing is written to
+// disk and no relationship is followed, so a link's target, an image's
+// source or an external template is never even read. Errors carry no
+// source content.
+func Import(data []byte) (*Result, error) {
+ z, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
+ if err != nil {
+ return nil, ErrNotWord
+ }
+ if len(z.File) > maxEntries {
+ return nil, ErrTooLarge
+ }
+ parts := map[string]*zip.File{}
+ for _, f := range z.File {
+ if _, dup := parts[f.Name]; dup {
+ return nil, ErrMalformed
+ }
+ parts[f.Name] = f
+ }
+ doc := parts["word/document.xml"]
+ if doc == nil {
+ return nil, ErrNotWord
+ }
+
+ budget := maxTotalBytes
+ r := &reader{rep: newReporter()}
+ if f := parts["word/styles.xml"]; f != nil {
+ b, err := readPart(f, &budget)
+ if err != nil {
+ return nil, err
+ }
+ if err := r.readStyles(b); err != nil {
+ return nil, err
+ }
+ }
+ b, err := readPart(doc, &budget)
+ if err != nil {
+ return nil, err
+ }
+ if err := r.readDocument(b); err != nil {
+ return nil, err
+ }
+ // Comments are counted by their references in the text; a comments
+ // part with none (every anchor deleted, say) is still reported.
+ if parts["word/comments.xml"] != nil && r.rep.items[CodeCommentsOmitted] == nil {
+ r.rep.add(CodeCommentsOmitted, 0)
+ }
+ if r.text == 0 {
+ return nil, ErrEmpty
+ }
+ return &Result{Document: r.document(), Report: r.rep.report()}, nil
+}
+
+// The limits. The output's are what internal/core's builder test holds
+// to its call budget (TestBuildAtTheReadersLimitFitsTheCallTimeout).
+const (
+ maxEntries = 1000
+ maxPartBytes = 32 << 20
+ maxTotalBytes = 64 << 20
+ maxDepth = 256
+ maxBlocks = 10_000
+ maxRuns = 40_000
+ maxText = 2 << 20
+
+ // maxLocations is how many paragraph numbers one report item keeps;
+ // its Count is still exact.
+ maxLocations = 20
+ // maxFontNames bounds the face names the report quotes, and
+ // maxFontName each name's length in bytes.
+ maxFontNames = 20
+ maxFontName = 64
+)
+
+// Import's refusals. Each is a whole answer: none of them says anything
+// about the file's content.
+var (
+ // ErrNotWord: not a ZIP, or a ZIP with no word/document.xml.
+ ErrNotWord = errors.New("docx: not a Word document")
+ // ErrMalformed: a part is not well-formed XML, nests past maxDepth,
+ // declares a DTD, or the archive names one entry twice.
+ ErrMalformed = errors.New("docx: the document is damaged")
+ // ErrTooLarge: past one of the limits above.
+ ErrTooLarge = errors.New("docx: the document is too large to import")
+ // ErrEmpty: nothing Docs can hold has any text.
+ ErrEmpty = errors.New("docx: the document has no text to import")
+)
+
+// Result is what Import read: the document and its report.
+type Result struct {
+ Document export.Document
+ Report Report
+}
+
+// Report is everything Import could not bring in as it was, in Codes
+// order. An empty report still never means full fidelity: it means
+// nothing this reader knows to look for was found.
+type Report struct {
+ Items []Item `json:"items"`
+}
+
+// Item is one kind of loss: how many times it happened and, where it
+// has one, the first maxLocations paragraphs (1-based, in the imported
+// document) it happened at.
+type Item struct {
+ Code Code `json:"code"`
+ Count int `json:"count"`
+ Paragraphs []int `json:"paragraphs,omitempty"`
+ Names []string `json:"names,omitempty"`
+}
+
+// Code names one kind of loss. The set is closed: Codes lists it.
+type Code string
+
+const (
+ CodeListFlattened Code = "list_flattened"
+ CodeTableFlattened Code = "table_flattened"
+ CodeLinkTextKept Code = "link_text_kept"
+ CodeInsertionKept Code = "insertion_kept"
+ CodeDeletionOmitted Code = "deletion_omitted"
+ CodeTabAsSpace Code = "tab_as_space"
+ CodeLineBreakSplit Code = "line_break_split"
+ CodePageBreakSplit Code = "page_break_split"
+ CodeTitleAsHeading Code = "title_as_heading"
+ CodeSubtitleAsParagraph Code = "subtitle_as_paragraph"
+ CodeSizeDropped Code = "size_dropped"
+ CodeFontSubstituted Code = "font_substituted"
+ CodeFormattingLost Code = "formatting_lost"
+ CodeAlignmentLost Code = "alignment_lost"
+ CodeObjectOmitted Code = "object_omitted"
+ CodeNotesOmitted Code = "notes_omitted"
+ CodeCommentsOmitted Code = "comments_omitted"
+ CodeHeadersOmitted Code = "headers_footers_omitted"
+)
+
+// Codes is every Code, in the order a report lists them.
+var Codes = []Code{
+ CodeTableFlattened, CodeListFlattened, CodeLinkTextKept,
+ CodeInsertionKept, CodeDeletionOmitted, CodeObjectOmitted,
+ CodeNotesOmitted, CodeCommentsOmitted, CodeHeadersOmitted,
+ CodeTitleAsHeading, CodeSubtitleAsParagraph, CodeFontSubstituted,
+ CodeSizeDropped, CodeFormattingLost, CodeAlignmentLost,
+ CodeTabAsSpace, CodeLineBreakSplit, CodePageBreakSplit,
+}
+
+func readPart(f *zip.File, budget *int) ([]byte, error) {
+ rc, err := f.Open()
+ if err != nil {
+ return nil, ErrMalformed
+ }
+ defer rc.Close()
+ limit := min(maxPartBytes, *budget)
+ b, err := io.ReadAll(io.LimitReader(rc, int64(limit)+1))
+ if err != nil {
+ return nil, ErrMalformed
+ }
+ if len(b) > limit {
+ return nil, ErrTooLarge
+ }
+ *budget -= len(b)
+ return b, nil
+}
+
+// ---- the report
+
+type reporter struct {
+ items map[Code]*Item
+ fonts map[string]bool
+}
+
+func newReporter() *reporter {
+ return &reporter{items: map[Code]*Item{}, fonts: map[string]bool{}}
+}
+
+// add counts one occurrence of code at paragraph (1-based; 0 for none).
+func (r *reporter) add(code Code, paragraph int) {
+ it := r.items[code]
+ if it == nil {
+ it = &Item{Code: code}
+ r.items[code] = it
+ }
+ it.Count++
+ if paragraph > 0 && len(it.Paragraphs) < maxLocations && !slices.Contains(it.Paragraphs, paragraph) {
+ it.Paragraphs = append(it.Paragraphs, paragraph)
+ }
+}
+
+func (r *reporter) font(name string, paragraph int) {
+ r.add(CodeFontSubstituted, paragraph)
+ if len(r.fonts) < maxFontNames {
+ if len(name) > maxFontName {
+ name = truncate(name, maxFontName)
+ }
+ r.fonts[name] = true
+ }
+}
+
+func (r *reporter) report() Report {
+ var out Report
+ for _, c := range Codes {
+ if it := r.items[c]; it != nil {
+ if c == CodeFontSubstituted {
+ for n := range r.fonts {
+ it.Names = append(it.Names, n)
+ }
+ sort.Strings(it.Names)
+ }
+ sort.Ints(it.Paragraphs)
+ out.Items = append(out.Items, *it)
+ }
+ }
+ return out
+}
+
+func truncate(s string, n int) string {
+ for n > 0 && !utf8.RuneStart(s[n]) {
+ n--
+ }
+ return s[:n]
+}
+
+// ---- styles
+
+const (
+ wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
+ mcNS = "http://schemas.openxmlformats.org/markup-compatibility/2006"
+)
+
+type style struct {
+ name, basedOn string
+ font string
+ size int // half-points, 0 for unset
+ numbered bool
+}
+
+// styleKind is what a paragraph style makes of a block.
+type styleKind struct {
+ heading int
+ title bool
+ subtitle bool
+}
+
+// ---- the walk
+
+type block struct {
+ heading int
+ runs []export.Node
+}
+
+type props struct {
+ bold, italic bool
+ font string // a Word face name, "" for inherited
+ size int // half-points, 0 for inherited
+ lost bool // underline, strike, colour, highlight, raised, caps
+}
+
+type reader struct {
+ dec *xml.Decoder
+ depth int
+
+ styles map[string]*style
+ defaultStyle string
+ baseFont string
+ baseSize int
+ blocks []block
+ runs, text int
+ rep *reporter
+ tables int
+ headersCounted bool
+}
+
+// next is the one way the walk reads a token, so depth is counted for
+// every element, skipped ones included.
+func (r *reader) next() (xml.Token, error) {
+ t, err := r.dec.Token()
+ if err != nil {
+ if errors.Is(err, io.EOF) {
+ return nil, io.EOF
+ }
+ return nil, ErrMalformed
+ }
+ switch t.(type) {
+ case xml.StartElement:
+ r.depth++
+ if r.depth > maxDepth {
+ return nil, ErrMalformed
+ }
+ case xml.EndElement:
+ r.depth--
+ case xml.Directive:
+ // A DTD has no place in OOXML, and an entity declaration is the
+ // one way XML grows past the bytes it arrived as.
+ return nil, ErrMalformed
+ }
+ return t, nil
+}
+
+// children calls visit for each child element of the element just
+// opened and returns at its end. Character data between children is
+// passed to text, when it is not nil.
+func (r *reader) children(visit func(xml.StartElement) error, text func([]byte)) error {
+ for {
+ t, err := r.next()
+ if err != nil {
+ if err == io.EOF {
+ return ErrMalformed
+ }
+ return err
+ }
+ switch t := t.(type) {
+ case xml.StartElement:
+ if err := visit(t); err != nil {
+ return err
+ }
+ case xml.EndElement:
+ return nil
+ case xml.CharData:
+ if text != nil {
+ text(t)
+ }
+ }
+ }
+}
+
+// skip consumes the element just opened, counting depth as it goes.
+func (r *reader) skip() error {
+ return r.children(func(xml.StartElement) error { return r.skip() }, nil)
+}
+
+func isW(e xml.StartElement, local string) bool {
+ return e.Name.Space == wNS && e.Name.Local == local
+}
+
+func attr(e xml.StartElement, local string) (string, bool) {
+ for _, a := range e.Attr {
+ if a.Name.Space == wNS && a.Name.Local == local {
+ return a.Value, true
+ }
+ }
+ return "", false
+}
+
+// toggle reads an OOXML on/off property: present with no w:val, or with
+// one of the true spellings, is on; "0", "false" and "off" are off.
+func toggle(e xml.StartElement) bool {
+ v, ok := attr(e, "val")
+ if !ok {
+ return true
+ }
+ switch strings.ToLower(v) {
+ case "0", "false", "off", "none":
+ return false
+ }
+ return true
+}
+
+func newDecoder(b []byte) *xml.Decoder {
+ d := xml.NewDecoder(bytes.NewReader(b))
+ d.Strict = true
+ return d
+}
+
+// root opens the part's root element, refusing anything before it but
+// the XML declaration, whitespace and comments.
+func (r *reader) root(local string) error {
+ for {
+ t, err := r.next()
+ if err != nil {
+ return ErrMalformed
+ }
+ if e, ok := t.(xml.StartElement); ok {
+ if !isW(e, local) {
+ return ErrNotWord
+ }
+ return nil
+ }
+ }
+}
+
+func (r *reader) readStyles(b []byte) error {
+ r.dec = newDecoder(b)
+ r.depth = 0
+ r.styles = map[string]*style{}
+ if err := r.root("styles"); err != nil {
+ return err
+ }
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "docDefaults"):
+ return r.children(func(e xml.StartElement) error {
+ if !isW(e, "rPrDefault") {
+ return r.skip()
+ }
+ return r.children(func(e xml.StartElement) error {
+ if !isW(e, "rPr") {
+ return r.skip()
+ }
+ p := props{}
+ if err := r.runProps(&p); err != nil {
+ return err
+ }
+ r.baseFont, r.baseSize = p.font, p.size
+ return nil
+ }, nil)
+ }, nil)
+ case isW(e, "style"):
+ kind, _ := attr(e, "type")
+ id, _ := attr(e, "styleId")
+ def, _ := attr(e, "default")
+ s := &style{}
+ err := r.children(func(c xml.StartElement) error {
+ switch {
+ case isW(c, "name"):
+ s.name, _ = attr(c, "val")
+ case isW(c, "basedOn"):
+ s.basedOn, _ = attr(c, "val")
+ case isW(c, "rPr"):
+ p := props{}
+ if err := r.runProps(&p); err != nil {
+ return err
+ }
+ s.font, s.size = p.font, p.size
+ return nil
+ case isW(c, "pPr"):
+ return r.children(func(p xml.StartElement) error {
+ if isW(p, "numPr") {
+ s.numbered = true
+ }
+ return r.skip()
+ }, nil)
+ }
+ return r.skip()
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if kind == "paragraph" && id != "" {
+ r.styles[id] = s
+ if toggle1(def) {
+ r.defaultStyle = id
+ }
+ }
+ return nil
+ }
+ return r.skip()
+ }, nil)
+}
+
+func toggle1(v string) bool {
+ return v == "1" || strings.EqualFold(v, "true") || strings.EqualFold(v, "on")
+}
+
+// chain is a style and its ancestors, nearest first, at most ten deep and
+// never revisiting one (a basedOn loop is a damaged file, read as far as
+// it makes sense).
+func (r *reader) chain(id string) []*style {
+ var out []*style
+ seen := map[string]bool{}
+ for id != "" && !seen[id] && len(out) < 10 {
+ seen[id] = true
+ s := r.styles[id]
+ if s == nil {
+ break
+ }
+ out = append(out, s)
+ id = s.basedOn
+ }
+ return out
+}
+
+func (r *reader) kind(id string) styleKind {
+ names := []string{strings.ToLower(id)}
+ for _, s := range r.chain(id) {
+ names = append(names, strings.ToLower(strings.TrimSpace(s.name)))
+ }
+ for _, n := range names {
+ compact := strings.ReplaceAll(n, " ", "")
+ if lvl, ok := strings.CutPrefix(compact, "heading"); ok {
+ if n, err := strconv.Atoi(lvl); err == nil && n >= 1 && n <= 6 {
+ return styleKind{heading: n}
+ }
+ }
+ switch compact {
+ case "title":
+ return styleKind{heading: 1, title: true}
+ case "subtitle":
+ return styleKind{subtitle: true}
+ }
+ }
+ return styleKind{}
+}
+
+// inherited is the face and size a run in a paragraph of this style
+// inherits: the style chain's, then the document default's.
+func (r *reader) inherited(id string) (font string, size int) {
+ if id == "" {
+ id = r.defaultStyle
+ }
+ for _, s := range r.chain(id) {
+ if font == "" {
+ font = s.font
+ }
+ if size == 0 {
+ size = s.size
+ }
+ }
+ if font == "" {
+ font = r.baseFont
+ }
+ if size == 0 {
+ size = r.baseSize
+ }
+ return font, size
+}
+
+func (r *reader) numberedStyle(id string) bool {
+ for _, s := range r.chain(id) {
+ if s.numbered {
+ return true
+ }
+ }
+ return false
+}
+
+// ---- document.xml
+
+func (r *reader) readDocument(b []byte) error {
+ r.dec = newDecoder(b)
+ r.depth = 0
+ if err := r.root("document"); err != nil {
+ return err
+ }
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "body") {
+ return r.blockContent()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// blockContent walks the children of a body, a table cell, or a
+// block-level content control.
+func (r *reader) blockContent() error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "p"):
+ return r.paragraph()
+ case isW(e, "tbl"):
+ return r.table()
+ case isW(e, "sdt"):
+ return r.sdt(r.blockContent)
+ case isW(e, "customXml"), isW(e, "ins"), isW(e, "moveTo"):
+ return r.blockContent()
+ case isW(e, "del"), isW(e, "moveFrom"):
+ r.rep.add(CodeDeletionOmitted, len(r.blocks))
+ return r.skip()
+ case isW(e, "sectPr"):
+ return r.sectPr()
+ case isW(e, "altChunk"):
+ r.rep.add(CodeObjectOmitted, len(r.blocks))
+ return r.skip()
+ case e.Name.Space == mcNS && e.Name.Local == "AlternateContent":
+ r.rep.add(CodeObjectOmitted, len(r.blocks))
+ return r.skip()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// sdt walks a content control's w:sdtContent with content, ignoring its
+// properties.
+func (r *reader) sdt(content func() error) error {
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "sdtContent") {
+ return content()
+ }
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) sectPr() error {
+ return r.children(func(e xml.StartElement) error {
+ if (isW(e, "headerReference") || isW(e, "footerReference")) && !r.headersCounted {
+ r.headersCounted = true
+ r.rep.add(CodeHeadersOmitted, 0)
+ }
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) table() error {
+ r.tables++
+ first := len(r.blocks) + 1
+ err := r.children(func(e xml.StartElement) error {
+ if !isW(e, "tr") {
+ return r.skip()
+ }
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "tc"):
+ return r.blockContent()
+ case isW(e, "sdt"):
+ return r.sdt(func() error {
+ return r.children(func(e xml.StartElement) error {
+ if isW(e, "tc") {
+ return r.blockContent()
+ }
+ return r.skip()
+ }, nil)
+ })
+ }
+ return r.skip()
+ }, nil)
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if len(r.blocks) >= first {
+ r.rep.add(CodeTableFlattened, first)
+ } else {
+ r.rep.add(CodeTableFlattened, 0)
+ }
+ return nil
+}
+
+// para is the paragraph being read: its style, and the run properties
+// its runs inherit.
+type para struct {
+ style string
+ kind styleKind
+ font string
+ size int
+ listMarked bool
+}
+
+func (r *reader) newBlock(p *para) error {
+ if len(r.blocks) >= maxBlocks {
+ return ErrTooLarge
+ }
+ r.blocks = append(r.blocks, block{heading: p.kind.heading})
+ return nil
+}
+
+func (r *reader) here() int { return len(r.blocks) }
+
+func (r *reader) paragraph() error {
+ p := &para{}
+ // The block exists from the paragraph's start, so a report line
+ // about anything inside it can name it; pPr, which always comes
+ // first, then settles what kind of block it is.
+ if err := r.newBlock(p); err != nil {
+ return err
+ }
+ first := true
+ err := r.children(func(e xml.StartElement) error {
+ if first {
+ first = false
+ if isW(e, "pPr") {
+ if err := r.paragraphProps(p); err != nil {
+ return err
+ }
+ r.settle(p)
+ return nil
+ }
+ r.settle(p)
+ }
+ return r.inline(p, e)
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if first {
+ r.settle(p)
+ }
+ return nil
+}
+
+// settle applies the paragraph's style once pPr has been read.
+func (r *reader) settle(p *para) {
+ p.kind = r.kind(p.style)
+ p.font, p.size = r.inherited(p.style)
+ if p.kind.heading > 0 {
+ // A heading's size is its level's in Docs; only a size its runs
+ // state themselves is carried.
+ p.size = 0
+ }
+ r.blocks[len(r.blocks)-1].heading = p.kind.heading
+ switch {
+ case p.kind.title:
+ r.rep.add(CodeTitleAsHeading, r.here())
+ case p.kind.subtitle:
+ r.rep.add(CodeSubtitleAsParagraph, r.here())
+ }
+ if !p.listMarked && r.numberedStyle(p.style) {
+ r.rep.add(CodeListFlattened, r.here())
+ }
+}
+
+func (r *reader) paragraphProps(p *para) error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "pStyle"):
+ p.style, _ = attr(e, "val")
+ case isW(e, "numPr"):
+ numbered := true
+ err := r.children(func(c xml.StartElement) error {
+ if isW(c, "numId") {
+ if v, _ := attr(c, "val"); v == "0" {
+ numbered = false
+ }
+ }
+ return r.skip()
+ }, nil)
+ if err != nil {
+ return err
+ }
+ if numbered {
+ p.listMarked = true
+ r.rep.add(CodeListFlattened, r.here())
+ }
+ return nil
+ case isW(e, "jc"):
+ switch v, _ := attr(e, "val"); v {
+ case "", "left", "start", "both", "distribute":
+ default:
+ r.rep.add(CodeAlignmentLost, r.here())
+ }
+ case isW(e, "sectPr"):
+ return r.sectPr()
+ }
+ return r.skip()
+ }, nil)
+}
+
+// inline walks one child of a paragraph or of anything inside one that
+// holds runs: links, suggestions, content controls, smart tags, fields.
+func (r *reader) inline(p *para, e xml.StartElement) error {
+ walk := func() error {
+ return r.children(func(c xml.StartElement) error { return r.inline(p, c) }, nil)
+ }
+ switch {
+ case isW(e, "r"):
+ return r.run(p)
+ case isW(e, "hyperlink"):
+ // Only the visible text: r:id and w:anchor are never read, so no
+ // target from the file reaches anything.
+ r.rep.add(CodeLinkTextKept, r.here())
+ return walk()
+ case isW(e, "ins"), isW(e, "moveTo"):
+ r.rep.add(CodeInsertionKept, r.here())
+ return walk()
+ case isW(e, "del"), isW(e, "moveFrom"):
+ r.rep.add(CodeDeletionOmitted, r.here())
+ return r.skip()
+ case isW(e, "smartTag"), isW(e, "customXml"), isW(e, "fldSimple"), isW(e, "dir"), isW(e, "bdo"):
+ return walk()
+ case isW(e, "sdt"):
+ return r.sdt(walk)
+ case e.Name.Space == mcNS && e.Name.Local == "AlternateContent",
+ e.Name.Local == "oMath" || e.Name.Local == "oMathPara":
+ r.rep.add(CodeObjectOmitted, r.here())
+ return r.skip()
+ }
+ return r.skip()
+}
+
+func (r *reader) run(p *para) error {
+ rp := props{}
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "rPr"):
+ return r.runProps(&rp)
+ case isW(e, "t"):
+ var b strings.Builder
+ err := r.children(func(xml.StartElement) error { return r.skip() }, func(c []byte) { b.Write(c) })
+ if err != nil {
+ return err
+ }
+ return r.emit(p, rp, b.String())
+ case isW(e, "tab"), isW(e, "ptab"):
+ r.rep.add(CodeTabAsSpace, r.here())
+ if err := r.emit(p, rp, " "); err != nil {
+ return err
+ }
+ case isW(e, "br"), isW(e, "cr"):
+ code := CodeLineBreakSplit
+ if v, _ := attr(e, "type"); v == "page" || v == "column" {
+ code = CodePageBreakSplit
+ }
+ if err := r.newBlock(p); err != nil {
+ return err
+ }
+ r.rep.add(code, r.here())
+ case isW(e, "noBreakHyphen"):
+ if err := r.emit(p, rp, "‑"); err != nil {
+ return err
+ }
+ case isW(e, "drawing"), isW(e, "pict"), isW(e, "object"), isW(e, "sym"), isW(e, "ruby"),
+ e.Name.Space == mcNS && e.Name.Local == "AlternateContent":
+ r.rep.add(CodeObjectOmitted, r.here())
+ case isW(e, "footnoteReference"), isW(e, "endnoteReference"):
+ r.rep.add(CodeNotesOmitted, r.here())
+ case isW(e, "commentReference"):
+ r.rep.add(CodeCommentsOmitted, r.here())
+ }
+ // delText, instrText, fldChar, softHyphen, lastRenderedPageBreak
+ // and anything unknown carry no visible text of their own.
+ return r.skip()
+ }, nil)
+}
+
+func (r *reader) runProps(p *props) error {
+ return r.children(func(e xml.StartElement) error {
+ switch {
+ case isW(e, "b"):
+ p.bold = toggle(e)
+ case isW(e, "i"):
+ p.italic = toggle(e)
+ case isW(e, "rFonts"):
+ if v, ok := attr(e, "ascii"); ok && v != "" {
+ p.font = v
+ } else if v, ok := attr(e, "hAnsi"); ok && v != "" {
+ p.font = v
+ }
+ case isW(e, "sz"):
+ if v, ok := attr(e, "val"); ok {
+ if n, err := strconv.Atoi(v); err == nil && n > 0 {
+ p.size = n
+ }
+ }
+ case isW(e, "u"):
+ if v, _ := attr(e, "val"); v != "none" {
+ p.lost = true
+ }
+ case isW(e, "strike"), isW(e, "dstrike"), isW(e, "caps"), isW(e, "smallCaps"):
+ if toggle(e) {
+ p.lost = true
+ }
+ case isW(e, "color"):
+ if v, _ := attr(e, "val"); !strings.EqualFold(v, "auto") && v != "000000" && v != "" {
+ p.lost = true
+ }
+ case isW(e, "highlight"):
+ if v, _ := attr(e, "val"); v != "none" && v != "" {
+ p.lost = true
+ }
+ case isW(e, "vertAlign"):
+ if v, _ := attr(e, "val"); v == "superscript" || v == "subscript" {
+ p.lost = true
+ }
+ }
+ return r.skip()
+ }, nil)
+}
+
+// clean makes a run's text into what a run can hold: a tab or a line
+// ending inside w:t becomes a space, and any other control character
+// goes.
+func (r *reader) clean(s string) string {
+ if strings.IndexFunc(s, unicode.IsControl) < 0 {
+ return s
+ }
+ var b strings.Builder
+ for _, c := range s {
+ switch {
+ case c == '\t':
+ r.rep.add(CodeTabAsSpace, r.here())
+ b.WriteByte(' ')
+ case c == '\n' || c == '\r':
+ b.WriteByte(' ')
+ case unicode.IsControl(c):
+ default:
+ b.WriteRune(c)
+ }
+ }
+ return b.String()
+}
+
+func (r *reader) emit(p *para, rp props, s string) error {
+ s = r.clean(s)
+ if s == "" {
+ return nil
+ }
+ r.runs++
+ r.text += len(s)
+ if r.runs > maxRuns || r.text > maxText {
+ return ErrTooLarge
+ }
+ run := export.Node{Type: "text", Text: s}
+
+ face := rp.font
+ if face == "" {
+ face = p.font
+ }
+ if face != "" {
+ if f, ok := fonts.ByDocxName(face); ok {
+ if f != fonts.Default {
+ run.Marks = append(run.Marks, export.Mark{Type: f.Mark()})
+ }
+ } else {
+ r.rep.font(face, r.here())
+ }
+ }
+ size := rp.size
+ if size == 0 {
+ size = p.size
+ }
+ if size != 0 && size != export.BodySizePt*2 {
+ if mark, ok := sizeMark(size); ok {
+ run.Marks = append(run.Marks, export.Mark{Type: mark})
+ } else {
+ r.rep.add(CodeSizeDropped, r.here())
+ }
+ }
+ if rp.bold {
+ run.Marks = append(run.Marks, export.Mark{Type: "strong"})
+ }
+ if rp.italic {
+ run.Marks = append(run.Marks, export.Mark{Type: "em"})
+ }
+ if rp.lost {
+ r.rep.add(CodeFormattingLost, r.here())
+ }
+ b := &r.blocks[len(r.blocks)-1]
+ b.runs = append(b.runs, run)
+ return nil
+}
+
+// sizeMark is the point-ladder mark for a size in half-points. The ladder
+// alone: the retired four-step names are never written.
+func sizeMark(half int) (string, bool) {
+ for _, mark := range export.SizeMarks() {
+ if !strings.HasPrefix(mark, "size_") {
+ continue
+ }
+ if _, err := strconv.Atoi(strings.TrimPrefix(mark, "size_")); err != nil {
+ continue
+ }
+ if pt, ok := export.SizePt(mark); ok && float64(half) == pt*2 {
+ return mark, true
+ }
+ }
+ return "", false
+}
+
+func (r *reader) document() export.Document {
+ doc := export.Document{Root: export.Node{Type: "doc"}}
+ for _, b := range r.blocks {
+ n := export.Node{Type: "paragraph"}
+ if b.heading > 0 {
+ n = export.Node{Type: "heading", Attrs: export.Attrs{Level: b.heading}}
+ }
+ n.Content = b.runs
+ doc.Root.Content = append(doc.Root.Content, n)
+ }
+ return doc
+}
diff --git a/internal/docx/read_test.go b/internal/docx/read_test.go
new file mode 100644
index 0000000..ef45bb6
--- /dev/null
+++ b/internal/docx/read_test.go
@@ -0,0 +1,413 @@
+package docx_test
+
+import (
+ "archive/zip"
+ "bytes"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "strings"
+ "testing"
+ "unicode"
+
+ "github.com/carlosframework/docs/internal/docx"
+ "github.com/carlosframework/docs/internal/export"
+)
+
+// The fixtures in this file are SYNTHESIZED: OOXML written by hand in the
+// shapes Google Docs' DOCX export uses (its namespaces, its styles, a link
+// as w:hyperlink, a suggestion as w:ins/w:del, a table, a list paragraph).
+// None of them is a real Google export. A real export, with permission to
+// commit its contents, has not been supplied; until one is, this reader's
+// agreement with Google's actual output is unproven beyond these shapes,
+// and the gap is recorded in the branch discussion.
+
+const docNS = `xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" ` +
+ `xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" ` +
+ `xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" ` +
+ `xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" ` +
+ `xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" mc:Ignorable="w14"`
+
+// googleStyles is a styles part shaped like Google's: Arial 11pt as the
+// document default and on Normal, and the named heading, title and
+// subtitle styles.
+const googleStyles = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<w:styles ` + docNS + `>` +
+ `<w:docDefaults><w:rPrDefault><w:rPr><w:rFonts w:ascii="Arial" w:cs="Arial" w:eastAsia="Arial" w:hAnsi="Arial"/>` +
+ `<w:sz w:val="22"/><w:szCs w:val="22"/><w:lang w:val="en"/></w:rPr></w:rPrDefault>` +
+ `<w:pPrDefault><w:pPr><w:spacing w:line="276" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults>` +
+ `<w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="normal"/></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading1"><w:name w:val="heading 1"/><w:basedOn w:val="Normal"/>` +
+ `<w:pPr><w:keepNext w:val="1"/></w:pPr><w:rPr><w:sz w:val="40"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Heading2"><w:name w:val="heading 2"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:sz w:val="32"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Title"><w:name w:val="Title"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:sz w:val="52"/></w:rPr></w:style>` +
+ `<w:style w:type="paragraph" w:styleId="Subtitle"><w:name w:val="Subtitle"/><w:basedOn w:val="Normal"/>` +
+ `<w:rPr><w:color w:val="666666"/><w:sz w:val="30"/></w:rPr></w:style>` +
+ `</w:styles>`
+
+// The link targets are hostile on purpose. Import never reads the
+// relationships part, so none of them may appear anywhere in its output.
+const hostileRels = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>` +
+ `<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">` +
+ `<Relationship Id="rId9" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="javascript:alert(document.cookie)" TargetMode="External"/>` +
+ `<Relationship Id="rId10" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/hyperlink" Target="file:///etc/passwd" TargetMode="External"/>` +
+ `<Relationship Id="rId11" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="http://169.254.169.254/latest/meta-data/" TargetMode="External"/>` +
+ `</Relationships>`
+
+func run(props, text string) string {
+ if props != "" {
+ props = "<w:rPr>" + props + "</w:rPr>"
+ }
+ return `<w:r>` + props + `<w:t xml:space="preserve">` + text + `</w:t></w:r>`
+}
+
+func para(style, content string) string {
+ ppr := ""
+ if style != "" {
+ ppr = `<w:pPr><w:pStyle w:val="` + style + `"/></w:pPr>`
+ }
+ return `<w:p>` + ppr + content + `</w:p>`
+}
+
+// googleShaped is the synthesized fixture: every container whose text the
+// old reader lost, plus the omissions the report must name.
+func googleShaped(t *testing.T) []byte {
+ t.Helper()
+ body := para("Title", run("", "Quarterly plan")) +
+ para("Heading1", run("", "Summary")) +
+ // A link, inside a paragraph, with hostile targets in the rels.
+ para("", run("", "Visit ")+`<w:hyperlink r:id="rId9"><w:r><w:rPr><w:color w:val="1155CC"/><w:u w:val="single"/></w:rPr><w:t>our site</w:t></w:r></w:hyperlink>`+run("", ".")) +
+ // Explicit bold off, the true spellings of on, and italic.
+ para("", run(`<w:b w:val="0"/>`, "not bold, ")+run(`<w:b/>`, "bold, ")+run(`<w:b w:val="false"/>`, "off again, ")+run(`<w:b w:val="1"/><w:i w:val="true"/>`, "both")) +
+ // A list item.
+ `<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr>` + run("", "First item") + `</w:p>` +
+ // A table, with a nested table in one cell.
+ `<w:tbl><w:tblPr/><w:tr><w:tc><w:tcPr/>` + para("", run("", "A1")) + `</w:tc><w:tc>` + para("", run("", "B1")) + `</w:tc></w:tr>` +
+ `<w:tr><w:tc>` + para("", run("", "A2")) + `<w:tbl><w:tr><w:tc>` + para("", run("", "inner")) + `</w:tc></w:tr></w:tbl></w:tc><w:tc>` + para("", run("", "B2")) + `</w:tc></w:tr></w:tbl>` +
+ // A suggestion: an insertion is kept, a deletion is not.
+ para("", run("", "Kept ")+`<w:ins w:id="1" w:author="Someone" w:date="2026-10-01T00:00:00Z">`+run("", "added")+`</w:ins>`+
+ `<w:del w:id="2" w:author="Someone" w:date="2026-10-01T00:00:00Z"><w:r><w:delText>removed</w:delText></w:r></w:del>`+run("", " text")) +
+ // A block content control and a smart tag.
+ `<w:sdt><w:sdtPr><w:alias w:val="x"/></w:sdtPr><w:sdtContent>` + para("", run("", "in a control")) + `</w:sdtContent></w:sdt>` +
+ para("", `<w:smartTag w:uri="urn:x" w:element="place">`+run("", "Smart")+`</w:smartTag>`+` <w:sdt><w:sdtContent>`+run("", " inline")+`</w:sdtContent></w:sdt>`) +
+ // A tab, a line break and a page break.
+ para("", `<w:r><w:t>before</w:t><w:tab/><w:t>after</w:t><w:br/><w:t>next line</w:t><w:br w:type="page"/><w:t>next page</w:t></w:r>`) +
+ // An image, a footnote, a comment, a size off the ladder, an
+ // unknown face, a centred paragraph, a heading level.
+ para("", `<w:r><w:drawing><wp:inline/></w:drawing></w:r>`+run("", "Caption")+`<w:r><w:footnoteReference w:id="1"/></w:r>`+
+ `<w:commentRangeStart w:id="0"/>`+run(`<w:sz w:val="30"/>`, "fifteen")+`<w:commentRangeEnd w:id="0"/><w:r><w:commentReference w:id="0"/></w:r>`+
+ run(`<w:rFonts w:ascii="Comic Sans MS" w:hAnsi="Comic Sans MS"/>`, " comic")+run(`<w:sz w:val="28"/>`, " fourteen")) +
+ `<w:p><w:pPr><w:jc w:val="center"/></w:pPr>` + run("", "Centred") + `</w:p>` +
+ para("Subtitle", run("", "A subtitle")) +
+ para("Heading2", run(`<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman"/>`, "Serif heading")) +
+ para("", "") +
+ `<w:sectPr><w:headerReference w:type="default" r:id="rId12"/><w:pgSz w:w="12240" w:h="15840"/></w:sectPr>`
+ return zipOf(t, map[string]string{
+ "[Content_Types].xml": `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"/>`,
+ "word/document.xml": `<?xml version="1.0" encoding="UTF-8" standalone="yes"?><w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`,
+ "word/styles.xml": googleStyles,
+ "word/_rels/document.xml.rels": hostileRels,
+ "word/comments.xml": `<w:comments ` + docNS + `/>`,
+ })
+}
+
+func zipOf(t *testing.T, parts map[string]string) []byte {
+ t.Helper()
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ for name, body := range parts {
+ w, err := z.Create(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ io.WriteString(w, body)
+ }
+ if err := z.Close(); err != nil {
+ t.Fatal(err)
+ }
+ return buf.Bytes()
+}
+
+// shape renders a document as one line per block: its type, then each
+// run as text{marks}.
+func shape(d export.Document) []string {
+ var out []string
+ for _, b := range d.Root.Content {
+ line := b.Type
+ if b.Type == "heading" {
+ line += fmt.Sprint(b.Attrs.Level)
+ }
+ line += ":"
+ for _, r := range b.Content {
+ var marks []string
+ for _, m := range r.Marks {
+ marks = append(marks, m.Type)
+ }
+ line += r.Text
+ if len(marks) > 0 {
+ line += "{" + strings.Join(marks, ",") + "}"
+ }
+ line += "|"
+ }
+ out = append(out, line)
+ }
+ return out
+}
+
+func TestImportReadsEveryContainerGoogleExportsTextIn(t *testing.T) {
+ res, err := docx.Import(googleShaped(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ // Arial is Liberation Sans (font_sans) and 11pt is size_11, Google's
+ // default, so ordinary runs carry both; headings carry no inherited
+ // size, because a heading's size is its level's here.
+ const body = "font_sans,size_11"
+ want := []string{
+ "heading1:Quarterly plan{font_sans}|",
+ "heading1:Summary{font_sans}|",
+ "paragraph:Visit {" + body + "}|our site{" + body + "}|.{" + body + "}|",
+ "paragraph:not bold, {" + body + "}|bold, {" + body + ",strong}|off again, {" + body + "}|both{" + body + ",strong,em}|",
+ "paragraph:First item{" + body + "}|",
+ "paragraph:A1{" + body + "}|",
+ "paragraph:B1{" + body + "}|",
+ "paragraph:A2{" + body + "}|",
+ "paragraph:inner{" + body + "}|",
+ "paragraph:B2{" + body + "}|",
+ "paragraph:Kept {" + body + "}|added{" + body + "}| text{" + body + "}|",
+ "paragraph:in a control{" + body + "}|",
+ "paragraph:Smart{" + body + "}| inline{" + body + "}|",
+ "paragraph:before{" + body + "}| {" + body + "}|after{" + body + "}|",
+ "paragraph:next line{" + body + "}|",
+ "paragraph:next page{" + body + "}|",
+ "paragraph:Caption{" + body + "}|fifteen{font_sans}| comic{size_11}| fourteen{font_sans,size_14}|",
+ "paragraph:Centred{" + body + "}|",
+ "paragraph:A subtitle{font_sans}|",
+ "heading2:Serif heading{font_serif}|",
+ "paragraph:",
+ }
+ got := shape(res.Document)
+ if strings.Join(got, "\n") != strings.Join(want, "\n") {
+ t.Errorf("document\n got:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
+ }
+
+ type line struct {
+ count int
+ where string
+ names string
+ }
+ wantReport := map[docx.Code]line{
+ docx.CodeTableFlattened: {2, "6,9", ""},
+ docx.CodeListFlattened: {1, "5", ""},
+ docx.CodeLinkTextKept: {1, "3", ""},
+ docx.CodeInsertionKept: {1, "11", ""},
+ docx.CodeDeletionOmitted: {1, "11", ""},
+ docx.CodeObjectOmitted: {1, "17", ""},
+ docx.CodeNotesOmitted: {1, "17", ""},
+ docx.CodeCommentsOmitted: {1, "17", ""},
+ docx.CodeHeadersOmitted: {1, "", ""},
+ docx.CodeTitleAsHeading: {1, "1", ""},
+ docx.CodeSubtitleAsParagraph: {1, "19", ""},
+ docx.CodeFontSubstituted: {1, "17", "Comic Sans MS"},
+ docx.CodeSizeDropped: {2, "17,19", ""},
+ docx.CodeFormattingLost: {1, "3", ""},
+ docx.CodeAlignmentLost: {1, "18", ""},
+ docx.CodeTabAsSpace: {1, "14", ""},
+ docx.CodeLineBreakSplit: {1, "15", ""},
+ docx.CodePageBreakSplit: {1, "16", ""},
+ }
+ gotReport := map[docx.Code]line{}
+ for _, it := range res.Report.Items {
+ var where []string
+ for _, p := range it.Paragraphs {
+ where = append(where, fmt.Sprint(p))
+ }
+ gotReport[it.Code] = line{it.Count, strings.Join(where, ","), strings.Join(it.Names, ",")}
+ }
+ for code, w := range wantReport {
+ if g, ok := gotReport[code]; !ok {
+ t.Errorf("report has no %s", code)
+ } else if g != w {
+ t.Errorf("report %s: got %+v, want %+v", code, g, w)
+ }
+ }
+ for code := range gotReport {
+ if _, ok := wantReport[code]; !ok {
+ t.Errorf("report has an unexpected %s: %+v", code, gotReport[code])
+ }
+ }
+ // The report lists in Codes order.
+ at := map[docx.Code]int{}
+ for i, c := range docx.Codes {
+ at[c] = i
+ }
+ for i := 1; i < len(res.Report.Items); i++ {
+ if at[res.Report.Items[i-1].Code] > at[res.Report.Items[i].Code] {
+ t.Errorf("report out of order at %d", i)
+ }
+ }
+}
+
+// The reader this replaced bound w:body>w:p>w:r>w:t alone and read w:b
+// by presence, with no error and no report. Run against it (its Read at
+// 056b94d), the first eleven cases below failed: link, table, insertion,
+// both content controls, smart tag and field text came back missing,
+// bold-off and italic-off came back on, and a tab or break joined its
+// neighbours. The last two passed there too; they are here because a
+// walk that descends into everything could get them wrong where an
+// unmarshal into fixed paths could not.
+func TestImportKeepsWhatTheOldReaderLost(t *testing.T) {
+ for _, c := range []struct {
+ name, body, want string
+ }{
+ {"link", para("", `<w:hyperlink r:id="rId9">`+run("", "linked")+`</w:hyperlink>`), "paragraph:linked|"},
+ {"table", `<w:tbl><w:tr><w:tc>` + para("", run("", "cell")) + `</w:tc></w:tr></w:tbl>`, "paragraph:cell|"},
+ {"insertion", para("", `<w:ins w:id="1" w:author="a">`+run("", "inserted")+`</w:ins>`), "paragraph:inserted|"},
+ {"block content control", `<w:sdt><w:sdtContent>` + para("", run("", "controlled")) + `</w:sdtContent></w:sdt>`, "paragraph:controlled|"},
+ {"inline content control", para("", `<w:sdt><w:sdtContent>`+run("", "inline")+`</w:sdtContent></w:sdt>`), "paragraph:inline|"},
+ {"smart tag", para("", `<w:smartTag w:element="x">`+run("", "tagged")+`</w:smartTag>`), "paragraph:tagged|"},
+ {"simple field", para("", `<w:fldSimple w:instr="PAGE">`+run("", "7")+`</w:fldSimple>`), "paragraph:7|"},
+ {"bold off", para("", run(`<w:b w:val="0"/>`, "plain")), "paragraph:plain|"},
+ {"italic off", para("", run(`<w:i w:val="false"/>`, "plain")), "paragraph:plain|"},
+ {"tab", para("", `<w:r><w:t>a</w:t><w:tab/><w:t>b</w:t></w:r>`), "paragraph:a| |b|"},
+ {"break", para("", `<w:r><w:t>a</w:t><w:br/><w:t>b</w:t></w:r>`), "paragraph:a|\nparagraph:b|"},
+ {"deletion is not text", para("", run("", "kept")+`<w:del w:id="1" w:author="a"><w:r><w:delText>gone</w:delText></w:r></w:del>`), "paragraph:kept|"},
+ {"paragraph mark properties are not the run's", `<w:p><w:pPr><w:rPr><w:b/></w:rPr></w:pPr>` + run("", "plain") + `</w:p>`, "paragraph:plain|"},
+ } {
+ data := zipOf(t, map[string]string{
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + c.body + `</w:body></w:document>`,
+ })
+ res, err := docx.Import(data)
+ if err != nil {
+ t.Errorf("%s: %v", c.name, err)
+ continue
+ }
+ if got := strings.Join(shape(res.Document), "\n"); got != c.want {
+ t.Errorf("%s: got %q, want %q", c.name, got, c.want)
+ }
+ }
+}
+
+func TestImportNeverReadsALinkTarget(t *testing.T) {
+ res, err := docx.Import(googleShaped(t))
+ if err != nil {
+ t.Fatal(err)
+ }
+ out, _ := json.Marshal(res)
+ for _, s := range []string{"javascript", "alert", "/etc/passwd", "169.254", "rId9", "Someone"} {
+ if strings.Contains(string(out), s) {
+ t.Errorf("the result carries %q from the file's metadata", s)
+ }
+ }
+}
+
+func TestImportDropsControlCharacters(t *testing.T) {
+ data := zipOf(t, map[string]string{
+ "word/document.xml": `<w:document ` + docNS + `><w:body>` + para("", run("", "a\u0085b&#x9;c\nd")) + `</w:body></w:document>`,
+ })
+ res, err := docx.Import(data)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got := strings.Join(shape(res.Document), ""); got != "paragraph:ab c d|" {
+ t.Errorf("got %q", got)
+ }
+}
+
+func TestImportRefusals(t *testing.T) {
+ doc := func(body string) map[string]string {
+ return map[string]string{"word/document.xml": `<w:document ` + docNS + `><w:body>` + body + `</w:body></w:document>`}
+ }
+ deep := strings.Repeat(`<w:sdt><w:sdtContent>`, 300) + para("", run("", "x")) + strings.Repeat(`</w:sdtContent></w:sdt>`, 300)
+ many := map[string]string{"word/document.xml": doc(para("", run("", "x")))["word/document.xml"]}
+ for i := 0; i < 1001; i++ {
+ many[fmt.Sprintf("word/media/%d.bin", i)] = ""
+ }
+ cases := []struct {
+ name string
+ data []byte
+ want error
+ }{
+ {"not a zip", []byte("%PDF-1.7 not a word file"), docx.ErrNotWord},
+ {"no document part", zipOf(t, map[string]string{"word/styles.xml": googleStyles}), docx.ErrNotWord},
+ {"a spreadsheet", zipOf(t, map[string]string{"xl/workbook.xml": "<workbook/>"}), docx.ErrNotWord},
+ {"wrong root", zipOf(t, map[string]string{"word/document.xml": `<html/>`}), docx.ErrNotWord},
+ {"not well formed", zipOf(t, doc(`<w:p><w:r>`)), docx.ErrMalformed},
+ {"a DTD", zipOf(t, map[string]string{"word/document.xml": `<!DOCTYPE w:document [<!ENTITY a "aaaa">]><w:document ` + docNS + `/>`}), docx.ErrMalformed},
+ {"too deep", zipOf(t, doc(deep)), docx.ErrMalformed},
+ {"too many entries", zipOf(t, many), docx.ErrTooLarge},
+ {"nothing but empty paragraphs", zipOf(t, doc(para("", "")+para("", `<w:r><w:drawing/></w:r>`))), docx.ErrEmpty},
+ {"only deleted text", zipOf(t, doc(para("", `<w:del><w:r><w:delText>x</w:delText></w:r></w:del>`))), docx.ErrEmpty},
+ {"too many blocks", zipOf(t, doc(strings.Repeat(para("", run("", "x")), 10_001))), docx.ErrTooLarge},
+ {"too much text", zipOf(t, doc(para("", run("", strings.Repeat("x", 2<<20+1))))), docx.ErrTooLarge},
+ {"too many runs", zipOf(t, doc(para("", strings.Repeat(run("", "x"), 40_001)))), docx.ErrTooLarge},
+ }
+ for _, c := range cases {
+ if _, err := docx.Import(c.data); !errors.Is(err, c.want) {
+ t.Errorf("%s: got %v, want %v", c.name, err, c.want)
+ }
+ }
+}
+
+// A part whose decompressed size is far past its compressed one is
+// refused from the bytes actually read, not from the header's claim.
+func TestImportCountsDecompressedBytes(t *testing.T) {
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ w, _ := z.Create("word/document.xml")
+ io.WriteString(w, `<w:document `+docNS+`><w:body>`)
+ pad := bytes.Repeat([]byte(" "), 1<<20)
+ for i := 0; i < 33; i++ {
+ w.Write(pad)
+ }
+ io.WriteString(w, `</w:body></w:document>`)
+ z.Close()
+ if buf.Len() > 1<<20 {
+ t.Fatalf("the bomb is %d bytes compressed; the test means a small file", buf.Len())
+ }
+ if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrTooLarge) {
+ t.Errorf("got %v, want ErrTooLarge", err)
+ }
+}
+
+func TestImportRefusesADuplicatedPart(t *testing.T) {
+ var buf bytes.Buffer
+ z := zip.NewWriter(&buf)
+ for _, body := range []string{para("", run("", "one")), para("", run("", "two"))} {
+ w, _ := z.Create("word/document.xml")
+ io.WriteString(w, `<w:document `+docNS+`><w:body>`+body+`</w:body></w:document>`)
+ }
+ z.Close()
+ if _, err := docx.Import(buf.Bytes()); !errors.Is(err, docx.ErrMalformed) {
+ t.Errorf("got %v, want ErrMalformed", err)
+ }
+}
+
+// Whatever the bytes, Import either refuses with one of its own errors
+// or returns runs the builder accepts: non-empty, no control character.
+func FuzzImport(f *testing.F) {
+ var tb testing.T
+ f.Add(googleShaped(&tb))
+ f.Add([]byte("PK\x03\x04"))
+ f.Fuzz(func(t *testing.T, data []byte) {
+ res, err := docx.Import(data)
+ if err != nil {
+ for _, known := range []error{docx.ErrNotWord, docx.ErrMalformed, docx.ErrTooLarge, docx.ErrEmpty} {
+ if errors.Is(err, known) {
+ return
+ }
+ }
+ t.Fatalf("unexpected error %v", err)
+ }
+ for _, b := range res.Document.Root.Content {
+ for _, r := range b.Content {
+ if r.Text == "" || strings.IndexFunc(r.Text, unicode.IsControl) >= 0 {
+ t.Fatalf("a run the builder would refuse: %q", r.Text)
+ }
+ }
+ }
+ })
+}