| 1 | package docx |
| 2 | |
| 3 | import ( |
| 4 | "archive/zip" |
| 5 | "bytes" |
| 6 | "encoding/xml" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "slices" |
| 10 | "sort" |
| 11 | "strconv" |
| 12 | "strings" |
| 13 | "unicode" |
| 14 | |
| 15 | "github.com/carlosframework/docs/internal/export" |
| 16 | "github.com/carlosframework/docs/internal/fonts" |
| 17 | ) |
| 18 | |
| 19 | // Import reads a .docx into the paragraphs, headings and text runs Docs |
| 20 | // can hold, and reports everything it could not bring in and where. |
| 21 | // |
| 22 | // It is a bounded token walk rather than an unmarshal into structs, |
| 23 | // because the text that matters is nested: Google Docs exports a link |
| 24 | // as w:p>w:hyperlink>w:r, a table as w:tbl>w:tr>w:tc>w:p, a suggestion |
| 25 | // as w:ins or w:del around runs, and some content under w:sdt or |
| 26 | // w:smartTag. The reader this replaced bound w:body>w:p>w:r>w:t alone |
| 27 | // and dropped all of that without a word, and read <w:b w:val="0"/> as |
| 28 | // bold. Every container below is walked for its text; what Docs cannot |
| 29 | // represent is flattened or omitted and reported. |
| 30 | // |
| 31 | // The bounds are this package's, not the XML decoder's: encoding/xml |
| 32 | // does not limit depth, and a ZIP header's sizes are claims, so entry |
| 33 | // count, the bytes actually decompressed, element depth and the output's |
| 34 | // blocks, runs and text are all counted here. Nothing is written to |
| 35 | // disk and no relationship is followed, so a link's target, an image's |
| 36 | // source or an external template is never even read. Errors carry no |
| 37 | // source content. |
| 38 | func Import(data []byte) (*Result, error) { |
| 39 | z, err := zip.NewReader(bytes.NewReader(data), int64(len(data))) |
| 40 | if err != nil { |
| 41 | return nil, ErrNotWord |
| 42 | } |
| 43 | if len(z.File) > maxEntries { |
| 44 | return nil, ErrTooLarge |
| 45 | } |
| 46 | parts := map[string]*zip.File{} |
| 47 | for _, f := range z.File { |
| 48 | if _, dup := parts[f.Name]; dup { |
| 49 | return nil, ErrMalformed |
| 50 | } |
| 51 | parts[f.Name] = f |
| 52 | } |
| 53 | doc := parts["word/document.xml"] |
| 54 | if doc == nil { |
| 55 | return nil, ErrNotWord |
| 56 | } |
| 57 | |
| 58 | budget := maxTotalBytes |
| 59 | r := &reader{rep: newReporter()} |
| 60 | if f := parts["word/styles.xml"]; f != nil { |
| 61 | b, err := readPart(f, &budget) |
| 62 | if err != nil { |
| 63 | return nil, err |
| 64 | } |
| 65 | if err := r.readStyles(b); err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | } |
| 69 | b, err := readPart(doc, &budget) |
| 70 | if err != nil { |
| 71 | return nil, err |
| 72 | } |
| 73 | if err := r.readDocument(b); err != nil { |
| 74 | return nil, err |
| 75 | } |
| 76 | // Comments are counted by their references in the text; a comments |
| 77 | // part with none (every anchor deleted, say) is still reported. |
| 78 | if parts["word/comments.xml"] != nil && r.rep.items[CodeCommentsOmitted] == nil { |
| 79 | r.rep.add(CodeCommentsOmitted, 0) |
| 80 | } |
| 81 | if r.text == 0 { |
| 82 | return nil, ErrEmpty |
| 83 | } |
| 84 | return &Result{Document: r.document(), Report: r.rep.report()}, nil |
| 85 | } |
| 86 | |
| 87 | // The limits. The output's are what internal/core's builder test holds |
| 88 | // to its call budget (TestBuildAtTheReadersLimitFitsTheCallTimeout). |
| 89 | const ( |
| 90 | maxEntries = 1000 |
| 91 | maxPartBytes = 32 << 20 |
| 92 | maxTotalBytes = 64 << 20 |
| 93 | maxDepth = 256 |
| 94 | maxBlocks = 5_000 |
| 95 | maxRuns = 10_000 |
| 96 | maxText = 512 << 10 |
| 97 | |
| 98 | // maxLocations is how many paragraph numbers one report item keeps; |
| 99 | // its Count is still exact. |
| 100 | maxLocations = 20 |
| 101 | ) |
| 102 | |
| 103 | // Import's refusals. Each is a whole answer: none of them says anything |
| 104 | // about the file's content. |
| 105 | var ( |
| 106 | // ErrNotWord: not a ZIP, or a ZIP with no word/document.xml. |
| 107 | ErrNotWord = errors.New("docx: not a Word document") |
| 108 | // ErrMalformed: a part is not well-formed XML, nests past maxDepth, |
| 109 | // declares a DTD, or the archive names one entry twice. |
| 110 | ErrMalformed = errors.New("docx: the document is damaged") |
| 111 | // ErrTooLarge: past one of the limits above. |
| 112 | ErrTooLarge = errors.New("docx: the document is too large to import") |
| 113 | // ErrEmpty: nothing Docs can hold has any text. |
| 114 | ErrEmpty = errors.New("docx: the document has no text to import") |
| 115 | ) |
| 116 | |
| 117 | // Result is what Import read: the document and its report. |
| 118 | type Result struct { |
| 119 | Document export.Document |
| 120 | Report Report |
| 121 | } |
| 122 | |
| 123 | // Report is everything Import could not bring in as it was, in Codes |
| 124 | // order. An empty report still never means full fidelity: it means |
| 125 | // nothing this reader knows to look for was found. |
| 126 | type Report struct { |
| 127 | Items []Item `json:"items"` |
| 128 | } |
| 129 | |
| 130 | // Item is one kind of loss: how many times it happened and, where it |
| 131 | // has one, the first maxLocations paragraphs (1-based, in the imported |
| 132 | // document) it happened at. Closed metadata only: nothing from the file |
| 133 | // is ever quoted, not even a face name, which is as arbitrary as text. |
| 134 | type Item struct { |
| 135 | Code Code `json:"code"` |
| 136 | Count int `json:"count"` |
| 137 | Paragraphs []int `json:"paragraphs,omitempty"` |
| 138 | } |
| 139 | |
| 140 | // Code names one kind of loss. The set is closed: Codes lists it. |
| 141 | type Code string |
| 142 | |
| 143 | const ( |
| 144 | CodeListFlattened Code = "list_flattened" |
| 145 | CodeTableFlattened Code = "table_flattened" |
| 146 | CodeLinkTextKept Code = "link_text_kept" |
| 147 | CodeInsertionKept Code = "insertion_kept" |
| 148 | CodeDeletionOmitted Code = "deletion_omitted" |
| 149 | CodeTabAsSpace Code = "tab_as_space" |
| 150 | CodeLineBreakSplit Code = "line_break_split" |
| 151 | CodePageBreakSplit Code = "page_break_split" |
| 152 | CodeTitleAsHeading Code = "title_as_heading" |
| 153 | CodeSubtitleAsParagraph Code = "subtitle_as_paragraph" |
| 154 | CodeSizeDropped Code = "size_dropped" |
| 155 | CodeFontSubstituted Code = "font_substituted" |
| 156 | CodeFormattingLost Code = "formatting_lost" |
| 157 | CodeAlignmentLost Code = "alignment_lost" |
| 158 | CodeObjectOmitted Code = "object_omitted" |
| 159 | CodeNotesOmitted Code = "notes_omitted" |
| 160 | CodeCommentsOmitted Code = "comments_omitted" |
| 161 | CodeHeadersOmitted Code = "headers_footers_omitted" |
| 162 | ) |
| 163 | |
| 164 | // Codes is every Code, in the order a report lists them. |
| 165 | var Codes = []Code{ |
| 166 | CodeTableFlattened, CodeListFlattened, CodeLinkTextKept, |
| 167 | CodeInsertionKept, CodeDeletionOmitted, CodeObjectOmitted, |
| 168 | CodeNotesOmitted, CodeCommentsOmitted, CodeHeadersOmitted, |
| 169 | CodeTitleAsHeading, CodeSubtitleAsParagraph, CodeFontSubstituted, |
| 170 | CodeSizeDropped, CodeFormattingLost, CodeAlignmentLost, |
| 171 | CodeTabAsSpace, CodeLineBreakSplit, CodePageBreakSplit, |
| 172 | } |
| 173 | |
| 174 | func readPart(f *zip.File, budget *int) ([]byte, error) { |
| 175 | rc, err := f.Open() |
| 176 | if err != nil { |
| 177 | return nil, ErrMalformed |
| 178 | } |
| 179 | defer rc.Close() |
| 180 | limit := min(maxPartBytes, *budget) |
| 181 | b, err := io.ReadAll(io.LimitReader(rc, int64(limit)+1)) |
| 182 | if err != nil { |
| 183 | return nil, ErrMalformed |
| 184 | } |
| 185 | if len(b) > limit { |
| 186 | return nil, ErrTooLarge |
| 187 | } |
| 188 | *budget -= len(b) |
| 189 | return b, nil |
| 190 | } |
| 191 | |
| 192 | // ---- the report |
| 193 | |
| 194 | type reporter struct { |
| 195 | items map[Code]*Item |
| 196 | } |
| 197 | |
| 198 | func newReporter() *reporter { |
| 199 | return &reporter{items: map[Code]*Item{}} |
| 200 | } |
| 201 | |
| 202 | // add counts one occurrence of code at paragraph (1-based; 0 for none). |
| 203 | func (r *reporter) add(code Code, paragraph int) { |
| 204 | it := r.items[code] |
| 205 | if it == nil { |
| 206 | it = &Item{Code: code} |
| 207 | r.items[code] = it |
| 208 | } |
| 209 | it.Count++ |
| 210 | if paragraph > 0 && len(it.Paragraphs) < maxLocations && !slices.Contains(it.Paragraphs, paragraph) { |
| 211 | it.Paragraphs = append(it.Paragraphs, paragraph) |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | func (r *reporter) report() Report { |
| 216 | var out Report |
| 217 | for _, c := range Codes { |
| 218 | if it := r.items[c]; it != nil { |
| 219 | sort.Ints(it.Paragraphs) |
| 220 | out.Items = append(out.Items, *it) |
| 221 | } |
| 222 | } |
| 223 | return out |
| 224 | } |
| 225 | |
| 226 | // ---- styles |
| 227 | |
| 228 | const ( |
| 229 | wNS = "http://schemas.openxmlformats.org/wordprocessingml/2006/main" |
| 230 | mcNS = "http://schemas.openxmlformats.org/markup-compatibility/2006" |
| 231 | ) |
| 232 | |
| 233 | type style struct { |
| 234 | name, basedOn string |
| 235 | rp props // the style's own run properties |
| 236 | numbered bool |
| 237 | aligned bool // centred or right-aligned |
| 238 | } |
| 239 | |
| 240 | // styleKind is what a paragraph style makes of a block. |
| 241 | type styleKind struct { |
| 242 | heading int |
| 243 | title bool |
| 244 | subtitle bool |
| 245 | } |
| 246 | |
| 247 | // ---- the walk |
| 248 | |
| 249 | type block struct { |
| 250 | heading int |
| 251 | runs []export.Node |
| 252 | } |
| 253 | |
| 254 | // tri is an OOXML toggle as stated somewhere in the cascade: unset, |
| 255 | // on, or explicitly off. An explicit off stops inheritance. |
| 256 | type tri int8 |
| 257 | |
| 258 | const ( |
| 259 | unset tri = iota |
| 260 | on |
| 261 | off |
| 262 | ) |
| 263 | |
| 264 | func triOf(b bool) tri { |
| 265 | if b { |
| 266 | return on |
| 267 | } |
| 268 | return off |
| 269 | } |
| 270 | |
| 271 | // props are run properties at one level of the cascade: a run's own |
| 272 | // w:rPr, a character style, a paragraph style, or the document default. |
| 273 | type props struct { |
| 274 | bold, italic tri |
| 275 | font string // a Word face name, "" for unset |
| 276 | size int // half-points, 0 for unset |
| 277 | lost bool // underline, strike, colour, highlight, raised, caps |
| 278 | rstyle string // a run's character style |
| 279 | } |
| 280 | |
| 281 | // over is p with every property p leaves unset taken from base. Lost |
| 282 | // formatting accumulates: a style's colour is as lost as a run's. |
| 283 | func (p props) over(base props) props { |
| 284 | if p.bold == unset { |
| 285 | p.bold = base.bold |
| 286 | } |
| 287 | if p.italic == unset { |
| 288 | p.italic = base.italic |
| 289 | } |
| 290 | if p.font == "" { |
| 291 | p.font = base.font |
| 292 | } |
| 293 | if p.size == 0 { |
| 294 | p.size = base.size |
| 295 | } |
| 296 | p.lost = p.lost || base.lost |
| 297 | return p |
| 298 | } |
| 299 | |
| 300 | type reader struct { |
| 301 | dec *xml.Decoder |
| 302 | depth int |
| 303 | |
| 304 | styles map[string]*style // paragraph styles |
| 305 | charStyles map[string]*style |
| 306 | defaultStyle string |
| 307 | base props // w:docDefaults' run properties |
| 308 | blocks []block |
| 309 | runs, text int |
| 310 | rep *reporter |
| 311 | tables int |
| 312 | headersCounted bool |
| 313 | } |
| 314 | |
| 315 | // next is the one way the walk reads a token, so depth is counted for |
| 316 | // every element, skipped ones included. |
| 317 | func (r *reader) next() (xml.Token, error) { |
| 318 | t, err := r.dec.Token() |
| 319 | if err != nil { |
| 320 | if errors.Is(err, io.EOF) { |
| 321 | return nil, io.EOF |
| 322 | } |
| 323 | return nil, ErrMalformed |
| 324 | } |
| 325 | switch t.(type) { |
| 326 | case xml.StartElement: |
| 327 | r.depth++ |
| 328 | if r.depth > maxDepth { |
| 329 | return nil, ErrMalformed |
| 330 | } |
| 331 | case xml.EndElement: |
| 332 | r.depth-- |
| 333 | case xml.Directive: |
| 334 | // A DTD has no place in OOXML, and an entity declaration is the |
| 335 | // one way XML grows past the bytes it arrived as. |
| 336 | return nil, ErrMalformed |
| 337 | } |
| 338 | return t, nil |
| 339 | } |
| 340 | |
| 341 | // children calls visit for each child element of the element just |
| 342 | // opened and returns at its end. Character data between children is |
| 343 | // passed to text, when it is not nil. |
| 344 | func (r *reader) children(visit func(xml.StartElement) error, text func([]byte)) error { |
| 345 | for { |
| 346 | t, err := r.next() |
| 347 | if err != nil { |
| 348 | if err == io.EOF { |
| 349 | return ErrMalformed |
| 350 | } |
| 351 | return err |
| 352 | } |
| 353 | switch t := t.(type) { |
| 354 | case xml.StartElement: |
| 355 | if err := visit(t); err != nil { |
| 356 | return err |
| 357 | } |
| 358 | case xml.EndElement: |
| 359 | return nil |
| 360 | case xml.CharData: |
| 361 | if text != nil { |
| 362 | text(t) |
| 363 | } |
| 364 | } |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | // skip consumes the element just opened, counting depth as it goes. |
| 369 | func (r *reader) skip() error { |
| 370 | return r.children(func(xml.StartElement) error { return r.skip() }, nil) |
| 371 | } |
| 372 | |
| 373 | func isW(e xml.StartElement, local string) bool { |
| 374 | return e.Name.Space == wNS && e.Name.Local == local |
| 375 | } |
| 376 | |
| 377 | func attr(e xml.StartElement, local string) (string, bool) { |
| 378 | for _, a := range e.Attr { |
| 379 | if a.Name.Space == wNS && a.Name.Local == local { |
| 380 | return a.Value, true |
| 381 | } |
| 382 | } |
| 383 | return "", false |
| 384 | } |
| 385 | |
| 386 | // toggle reads an OOXML on/off property: present with no w:val, or with |
| 387 | // one of the true spellings, is on; "0", "false" and "off" are off. |
| 388 | func toggle(e xml.StartElement) bool { |
| 389 | v, ok := attr(e, "val") |
| 390 | if !ok { |
| 391 | return true |
| 392 | } |
| 393 | switch strings.ToLower(v) { |
| 394 | case "0", "false", "off", "none": |
| 395 | return false |
| 396 | } |
| 397 | return true |
| 398 | } |
| 399 | |
| 400 | func newDecoder(b []byte) *xml.Decoder { |
| 401 | d := xml.NewDecoder(bytes.NewReader(b)) |
| 402 | d.Strict = true |
| 403 | return d |
| 404 | } |
| 405 | |
| 406 | // root opens the part's root element, refusing anything before it but |
| 407 | // the XML declaration, whitespace and comments. |
| 408 | func (r *reader) root(local string) error { |
| 409 | for { |
| 410 | t, err := r.next() |
| 411 | if err != nil { |
| 412 | return ErrMalformed |
| 413 | } |
| 414 | if e, ok := t.(xml.StartElement); ok { |
| 415 | if !isW(e, local) { |
| 416 | return ErrNotWord |
| 417 | } |
| 418 | return nil |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | func (r *reader) readStyles(b []byte) error { |
| 424 | r.dec = newDecoder(b) |
| 425 | r.depth = 0 |
| 426 | r.styles = map[string]*style{} |
| 427 | r.charStyles = map[string]*style{} |
| 428 | if err := r.root("styles"); err != nil { |
| 429 | return err |
| 430 | } |
| 431 | return r.children(func(e xml.StartElement) error { |
| 432 | switch { |
| 433 | case isW(e, "docDefaults"): |
| 434 | return r.children(func(e xml.StartElement) error { |
| 435 | if !isW(e, "rPrDefault") { |
| 436 | return r.skip() |
| 437 | } |
| 438 | return r.children(func(e xml.StartElement) error { |
| 439 | if !isW(e, "rPr") { |
| 440 | return r.skip() |
| 441 | } |
| 442 | return r.runProps(&r.base) |
| 443 | }, nil) |
| 444 | }, nil) |
| 445 | case isW(e, "style"): |
| 446 | kind, _ := attr(e, "type") |
| 447 | id, _ := attr(e, "styleId") |
| 448 | def, _ := attr(e, "default") |
| 449 | s := &style{} |
| 450 | err := r.children(func(c xml.StartElement) error { |
| 451 | switch { |
| 452 | case isW(c, "name"): |
| 453 | s.name, _ = attr(c, "val") |
| 454 | case isW(c, "basedOn"): |
| 455 | s.basedOn, _ = attr(c, "val") |
| 456 | case isW(c, "rPr"): |
| 457 | return r.runProps(&s.rp) |
| 458 | case isW(c, "pPr"): |
| 459 | return r.children(func(p xml.StartElement) error { |
| 460 | switch { |
| 461 | case isW(p, "numPr"): |
| 462 | s.numbered = true |
| 463 | case isW(p, "jc"): |
| 464 | s.aligned = alignedValue(p) |
| 465 | } |
| 466 | return r.skip() |
| 467 | }, nil) |
| 468 | } |
| 469 | return r.skip() |
| 470 | }, nil) |
| 471 | if err != nil { |
| 472 | return err |
| 473 | } |
| 474 | switch { |
| 475 | case id == "": |
| 476 | case kind == "paragraph": |
| 477 | r.styles[id] = s |
| 478 | if toggle1(def) { |
| 479 | r.defaultStyle = id |
| 480 | } |
| 481 | case kind == "character": |
| 482 | r.charStyles[id] = s |
| 483 | } |
| 484 | return nil |
| 485 | } |
| 486 | return r.skip() |
| 487 | }, nil) |
| 488 | } |
| 489 | |
| 490 | func toggle1(v string) bool { |
| 491 | return v == "1" || strings.EqualFold(v, "true") || strings.EqualFold(v, "on") |
| 492 | } |
| 493 | |
| 494 | // chain is a style and its ancestors, nearest first, at most ten deep and |
| 495 | // never revisiting one (a basedOn loop is a damaged file, read as far as |
| 496 | // it makes sense). |
| 497 | func (r *reader) chain(id string) []*style { |
| 498 | return chainIn(r.styles, id) |
| 499 | } |
| 500 | |
| 501 | func chainIn(styles map[string]*style, id string) []*style { |
| 502 | var out []*style |
| 503 | seen := map[string]bool{} |
| 504 | for id != "" && !seen[id] && len(out) < 10 { |
| 505 | seen[id] = true |
| 506 | s := styles[id] |
| 507 | if s == nil { |
| 508 | break |
| 509 | } |
| 510 | out = append(out, s) |
| 511 | id = s.basedOn |
| 512 | } |
| 513 | return out |
| 514 | } |
| 515 | |
| 516 | func (r *reader) kind(id string) styleKind { |
| 517 | names := []string{strings.ToLower(id)} |
| 518 | for _, s := range r.chain(id) { |
| 519 | names = append(names, strings.ToLower(strings.TrimSpace(s.name))) |
| 520 | } |
| 521 | for _, n := range names { |
| 522 | compact := strings.ReplaceAll(n, " ", "") |
| 523 | if lvl, ok := strings.CutPrefix(compact, "heading"); ok { |
| 524 | if n, err := strconv.Atoi(lvl); err == nil && n >= 1 && n <= 6 { |
| 525 | return styleKind{heading: n} |
| 526 | } |
| 527 | } |
| 528 | switch compact { |
| 529 | case "title": |
| 530 | return styleKind{heading: 1, title: true} |
| 531 | case "subtitle": |
| 532 | return styleKind{subtitle: true} |
| 533 | } |
| 534 | } |
| 535 | return styleKind{} |
| 536 | } |
| 537 | |
| 538 | // inherited is what a run in a paragraph of this style inherits: the |
| 539 | // style chain's run properties, nearest first, then the document |
| 540 | // default's. |
| 541 | func (r *reader) inherited(id string) props { |
| 542 | if id == "" { |
| 543 | id = r.defaultStyle |
| 544 | } |
| 545 | var p props |
| 546 | for _, s := range r.chain(id) { |
| 547 | p = p.over(s.rp) |
| 548 | } |
| 549 | return p.over(r.base) |
| 550 | } |
| 551 | |
| 552 | // charInherited is a character style chain's run properties. |
| 553 | func (r *reader) charInherited(id string) props { |
| 554 | var p props |
| 555 | for _, s := range chainIn(r.charStyles, id) { |
| 556 | p = p.over(s.rp) |
| 557 | } |
| 558 | return p |
| 559 | } |
| 560 | |
| 561 | func (r *reader) alignedStyle(id string) bool { |
| 562 | if id == "" { |
| 563 | id = r.defaultStyle |
| 564 | } |
| 565 | for _, s := range r.chain(id) { |
| 566 | if s.aligned { |
| 567 | return true |
| 568 | } |
| 569 | } |
| 570 | return false |
| 571 | } |
| 572 | |
| 573 | // alignedValue is whether a w:jc is an alignment Docs does not import: |
| 574 | // centred, right, or anything else that is not the start edge or |
| 575 | // justification. |
| 576 | func alignedValue(e xml.StartElement) bool { |
| 577 | switch v, _ := attr(e, "val"); v { |
| 578 | case "", "left", "start", "both", "distribute": |
| 579 | return false |
| 580 | } |
| 581 | return true |
| 582 | } |
| 583 | |
| 584 | func (r *reader) numberedStyle(id string) bool { |
| 585 | for _, s := range r.chain(id) { |
| 586 | if s.numbered { |
| 587 | return true |
| 588 | } |
| 589 | } |
| 590 | return false |
| 591 | } |
| 592 | |
| 593 | // ---- document.xml |
| 594 | |
| 595 | func (r *reader) readDocument(b []byte) error { |
| 596 | r.dec = newDecoder(b) |
| 597 | r.depth = 0 |
| 598 | if err := r.root("document"); err != nil { |
| 599 | return err |
| 600 | } |
| 601 | return r.children(func(e xml.StartElement) error { |
| 602 | if isW(e, "body") { |
| 603 | return r.blockContent() |
| 604 | } |
| 605 | return r.skip() |
| 606 | }, nil) |
| 607 | } |
| 608 | |
| 609 | // blockContent walks the children of a body, a table cell, or a |
| 610 | // block-level content control. |
| 611 | func (r *reader) blockContent() error { |
| 612 | return r.children(func(e xml.StartElement) error { |
| 613 | switch { |
| 614 | case isW(e, "p"): |
| 615 | return r.paragraph() |
| 616 | case isW(e, "tbl"): |
| 617 | return r.table() |
| 618 | case isW(e, "sdt"): |
| 619 | return r.sdt(r.blockContent) |
| 620 | case isW(e, "customXml"), isW(e, "ins"), isW(e, "moveTo"): |
| 621 | return r.blockContent() |
| 622 | case isW(e, "del"), isW(e, "moveFrom"): |
| 623 | r.rep.add(CodeDeletionOmitted, len(r.blocks)) |
| 624 | return r.skip() |
| 625 | case isW(e, "sectPr"): |
| 626 | return r.sectPr() |
| 627 | case isW(e, "altChunk"): |
| 628 | r.rep.add(CodeObjectOmitted, len(r.blocks)) |
| 629 | return r.skip() |
| 630 | case e.Name.Space == mcNS && e.Name.Local == "AlternateContent": |
| 631 | r.rep.add(CodeObjectOmitted, len(r.blocks)) |
| 632 | return r.skip() |
| 633 | } |
| 634 | return r.skip() |
| 635 | }, nil) |
| 636 | } |
| 637 | |
| 638 | // sdt walks a content control's w:sdtContent with content, ignoring its |
| 639 | // properties. |
| 640 | func (r *reader) sdt(content func() error) error { |
| 641 | return r.children(func(e xml.StartElement) error { |
| 642 | if isW(e, "sdtContent") { |
| 643 | return content() |
| 644 | } |
| 645 | return r.skip() |
| 646 | }, nil) |
| 647 | } |
| 648 | |
| 649 | func (r *reader) sectPr() error { |
| 650 | return r.children(func(e xml.StartElement) error { |
| 651 | if (isW(e, "headerReference") || isW(e, "footerReference")) && !r.headersCounted { |
| 652 | r.headersCounted = true |
| 653 | r.rep.add(CodeHeadersOmitted, 0) |
| 654 | } |
| 655 | return r.skip() |
| 656 | }, nil) |
| 657 | } |
| 658 | |
| 659 | func (r *reader) table() error { |
| 660 | r.tables++ |
| 661 | first := len(r.blocks) + 1 |
| 662 | err := r.children(func(e xml.StartElement) error { |
| 663 | if !isW(e, "tr") { |
| 664 | return r.skip() |
| 665 | } |
| 666 | return r.children(func(e xml.StartElement) error { |
| 667 | switch { |
| 668 | case isW(e, "tc"): |
| 669 | return r.blockContent() |
| 670 | case isW(e, "sdt"): |
| 671 | return r.sdt(func() error { |
| 672 | return r.children(func(e xml.StartElement) error { |
| 673 | if isW(e, "tc") { |
| 674 | return r.blockContent() |
| 675 | } |
| 676 | return r.skip() |
| 677 | }, nil) |
| 678 | }) |
| 679 | } |
| 680 | return r.skip() |
| 681 | }, nil) |
| 682 | }, nil) |
| 683 | if err != nil { |
| 684 | return err |
| 685 | } |
| 686 | if len(r.blocks) >= first { |
| 687 | r.rep.add(CodeTableFlattened, first) |
| 688 | } else { |
| 689 | r.rep.add(CodeTableFlattened, 0) |
| 690 | } |
| 691 | return nil |
| 692 | } |
| 693 | |
| 694 | // para is the paragraph being read: its style, and the run properties |
| 695 | // its runs inherit. |
| 696 | type para struct { |
| 697 | style string |
| 698 | kind styleKind |
| 699 | inh props // what its runs inherit |
| 700 | listMarked bool |
| 701 | jcSet bool // the paragraph states its own alignment |
| 702 | } |
| 703 | |
| 704 | func (r *reader) newBlock(p *para) error { |
| 705 | if len(r.blocks) >= maxBlocks { |
| 706 | return ErrTooLarge |
| 707 | } |
| 708 | r.blocks = append(r.blocks, block{heading: p.kind.heading}) |
| 709 | return nil |
| 710 | } |
| 711 | |
| 712 | func (r *reader) here() int { return len(r.blocks) } |
| 713 | |
| 714 | func (r *reader) paragraph() error { |
| 715 | p := ¶{} |
| 716 | // The block exists from the paragraph's start, so a report line |
| 717 | // about anything inside it can name it; pPr, which always comes |
| 718 | // first, then settles what kind of block it is. |
| 719 | if err := r.newBlock(p); err != nil { |
| 720 | return err |
| 721 | } |
| 722 | first := true |
| 723 | err := r.children(func(e xml.StartElement) error { |
| 724 | if first { |
| 725 | first = false |
| 726 | if isW(e, "pPr") { |
| 727 | if err := r.paragraphProps(p); err != nil { |
| 728 | return err |
| 729 | } |
| 730 | r.settle(p) |
| 731 | return nil |
| 732 | } |
| 733 | r.settle(p) |
| 734 | } |
| 735 | return r.inline(p, e) |
| 736 | }, nil) |
| 737 | if err != nil { |
| 738 | return err |
| 739 | } |
| 740 | if first { |
| 741 | r.settle(p) |
| 742 | } |
| 743 | return nil |
| 744 | } |
| 745 | |
| 746 | // settle applies the paragraph's style once pPr has been read. |
| 747 | func (r *reader) settle(p *para) { |
| 748 | p.kind = r.kind(p.style) |
| 749 | p.inh = r.inherited(p.style) |
| 750 | if p.kind.heading > 0 { |
| 751 | // A heading looks like its level in Docs: the heading style's |
| 752 | // own size, weight, slope and colour are the level's here, and |
| 753 | // the import page says so. Only its face, and what its runs |
| 754 | // state themselves, are carried. |
| 755 | p.inh = props{font: p.inh.font} |
| 756 | } else if !p.jcSet && r.alignedStyle(p.style) { |
| 757 | r.rep.add(CodeAlignmentLost, r.here()) |
| 758 | } |
| 759 | r.blocks[len(r.blocks)-1].heading = p.kind.heading |
| 760 | switch { |
| 761 | case p.kind.title: |
| 762 | r.rep.add(CodeTitleAsHeading, r.here()) |
| 763 | case p.kind.subtitle: |
| 764 | r.rep.add(CodeSubtitleAsParagraph, r.here()) |
| 765 | } |
| 766 | if !p.listMarked && r.numberedStyle(p.style) { |
| 767 | r.rep.add(CodeListFlattened, r.here()) |
| 768 | } |
| 769 | } |
| 770 | |
| 771 | func (r *reader) paragraphProps(p *para) error { |
| 772 | return r.children(func(e xml.StartElement) error { |
| 773 | switch { |
| 774 | case isW(e, "pStyle"): |
| 775 | p.style, _ = attr(e, "val") |
| 776 | case isW(e, "numPr"): |
| 777 | numbered := true |
| 778 | err := r.children(func(c xml.StartElement) error { |
| 779 | if isW(c, "numId") { |
| 780 | if v, _ := attr(c, "val"); v == "0" { |
| 781 | numbered = false |
| 782 | } |
| 783 | } |
| 784 | return r.skip() |
| 785 | }, nil) |
| 786 | if err != nil { |
| 787 | return err |
| 788 | } |
| 789 | if numbered { |
| 790 | p.listMarked = true |
| 791 | r.rep.add(CodeListFlattened, r.here()) |
| 792 | } |
| 793 | return nil |
| 794 | case isW(e, "jc"): |
| 795 | p.jcSet = true |
| 796 | if alignedValue(e) { |
| 797 | r.rep.add(CodeAlignmentLost, r.here()) |
| 798 | } |
| 799 | case isW(e, "sectPr"): |
| 800 | return r.sectPr() |
| 801 | } |
| 802 | return r.skip() |
| 803 | }, nil) |
| 804 | } |
| 805 | |
| 806 | // inline walks one child of a paragraph or of anything inside one that |
| 807 | // holds runs: links, suggestions, content controls, smart tags, fields. |
| 808 | func (r *reader) inline(p *para, e xml.StartElement) error { |
| 809 | walk := func() error { |
| 810 | return r.children(func(c xml.StartElement) error { return r.inline(p, c) }, nil) |
| 811 | } |
| 812 | switch { |
| 813 | case isW(e, "r"): |
| 814 | return r.run(p) |
| 815 | case isW(e, "hyperlink"): |
| 816 | // Only the visible text: r:id and w:anchor are never read, so no |
| 817 | // target from the file reaches anything. |
| 818 | r.rep.add(CodeLinkTextKept, r.here()) |
| 819 | return walk() |
| 820 | case isW(e, "ins"), isW(e, "moveTo"): |
| 821 | r.rep.add(CodeInsertionKept, r.here()) |
| 822 | return walk() |
| 823 | case isW(e, "del"), isW(e, "moveFrom"): |
| 824 | r.rep.add(CodeDeletionOmitted, r.here()) |
| 825 | return r.skip() |
| 826 | case isW(e, "smartTag"), isW(e, "customXml"), isW(e, "fldSimple"), isW(e, "dir"), isW(e, "bdo"): |
| 827 | return walk() |
| 828 | case isW(e, "sdt"): |
| 829 | return r.sdt(walk) |
| 830 | case e.Name.Space == mcNS && e.Name.Local == "AlternateContent", |
| 831 | e.Name.Local == "oMath" || e.Name.Local == "oMathPara": |
| 832 | r.rep.add(CodeObjectOmitted, r.here()) |
| 833 | return r.skip() |
| 834 | } |
| 835 | return r.skip() |
| 836 | } |
| 837 | |
| 838 | func (r *reader) run(p *para) error { |
| 839 | rp := props{} |
| 840 | return r.children(func(e xml.StartElement) error { |
| 841 | switch { |
| 842 | case isW(e, "rPr"): |
| 843 | return r.runProps(&rp) |
| 844 | case isW(e, "t"): |
| 845 | var b strings.Builder |
| 846 | err := r.children(func(xml.StartElement) error { return r.skip() }, func(c []byte) { b.Write(c) }) |
| 847 | if err != nil { |
| 848 | return err |
| 849 | } |
| 850 | return r.emit(p, rp, b.String()) |
| 851 | case isW(e, "tab"), isW(e, "ptab"): |
| 852 | r.rep.add(CodeTabAsSpace, r.here()) |
| 853 | if err := r.emit(p, rp, " "); err != nil { |
| 854 | return err |
| 855 | } |
| 856 | case isW(e, "br"), isW(e, "cr"): |
| 857 | code := CodeLineBreakSplit |
| 858 | if v, _ := attr(e, "type"); v == "page" || v == "column" { |
| 859 | code = CodePageBreakSplit |
| 860 | } |
| 861 | if err := r.newBlock(p); err != nil { |
| 862 | return err |
| 863 | } |
| 864 | r.rep.add(code, r.here()) |
| 865 | case isW(e, "noBreakHyphen"): |
| 866 | if err := r.emit(p, rp, "‑"); err != nil { |
| 867 | return err |
| 868 | } |
| 869 | case isW(e, "drawing"), isW(e, "pict"), isW(e, "object"), isW(e, "sym"), isW(e, "ruby"), |
| 870 | e.Name.Space == mcNS && e.Name.Local == "AlternateContent": |
| 871 | r.rep.add(CodeObjectOmitted, r.here()) |
| 872 | case isW(e, "footnoteReference"), isW(e, "endnoteReference"): |
| 873 | r.rep.add(CodeNotesOmitted, r.here()) |
| 874 | case isW(e, "commentReference"): |
| 875 | r.rep.add(CodeCommentsOmitted, r.here()) |
| 876 | } |
| 877 | // delText, instrText, fldChar, softHyphen, lastRenderedPageBreak |
| 878 | // and anything unknown carry no visible text of their own. |
| 879 | return r.skip() |
| 880 | }, nil) |
| 881 | } |
| 882 | |
| 883 | func (r *reader) runProps(p *props) error { |
| 884 | return r.children(func(e xml.StartElement) error { |
| 885 | switch { |
| 886 | case isW(e, "b"): |
| 887 | p.bold = triOf(toggle(e)) |
| 888 | case isW(e, "i"): |
| 889 | p.italic = triOf(toggle(e)) |
| 890 | case isW(e, "rStyle"): |
| 891 | p.rstyle, _ = attr(e, "val") |
| 892 | case isW(e, "rFonts"): |
| 893 | if v, ok := attr(e, "ascii"); ok && v != "" { |
| 894 | p.font = v |
| 895 | } else if v, ok := attr(e, "hAnsi"); ok && v != "" { |
| 896 | p.font = v |
| 897 | } |
| 898 | case isW(e, "sz"): |
| 899 | if v, ok := attr(e, "val"); ok { |
| 900 | if n, err := strconv.Atoi(v); err == nil && n > 0 { |
| 901 | p.size = n |
| 902 | } |
| 903 | } |
| 904 | case isW(e, "u"): |
| 905 | if v, _ := attr(e, "val"); v != "none" { |
| 906 | p.lost = true |
| 907 | } |
| 908 | case isW(e, "strike"), isW(e, "dstrike"), isW(e, "caps"), isW(e, "smallCaps"): |
| 909 | if toggle(e) { |
| 910 | p.lost = true |
| 911 | } |
| 912 | case isW(e, "color"): |
| 913 | if v, _ := attr(e, "val"); !strings.EqualFold(v, "auto") && v != "000000" && v != "" { |
| 914 | p.lost = true |
| 915 | } |
| 916 | case isW(e, "highlight"): |
| 917 | if v, _ := attr(e, "val"); v != "none" && v != "" { |
| 918 | p.lost = true |
| 919 | } |
| 920 | case isW(e, "vertAlign"): |
| 921 | if v, _ := attr(e, "val"); v == "superscript" || v == "subscript" { |
| 922 | p.lost = true |
| 923 | } |
| 924 | } |
| 925 | return r.skip() |
| 926 | }, nil) |
| 927 | } |
| 928 | |
| 929 | // clean makes a run's text into what a run can hold: a tab or a line |
| 930 | // ending inside w:t becomes a space, and any other control character |
| 931 | // goes. |
| 932 | func (r *reader) clean(s string) string { |
| 933 | if strings.IndexFunc(s, unicode.IsControl) < 0 { |
| 934 | return s |
| 935 | } |
| 936 | var b strings.Builder |
| 937 | for _, c := range s { |
| 938 | switch { |
| 939 | case c == '\t': |
| 940 | r.rep.add(CodeTabAsSpace, r.here()) |
| 941 | b.WriteByte(' ') |
| 942 | case c == '\n' || c == '\r': |
| 943 | b.WriteByte(' ') |
| 944 | case unicode.IsControl(c): |
| 945 | default: |
| 946 | b.WriteRune(c) |
| 947 | } |
| 948 | } |
| 949 | return b.String() |
| 950 | } |
| 951 | |
| 952 | func (r *reader) emit(p *para, rp props, s string) error { |
| 953 | s = r.clean(s) |
| 954 | if s == "" { |
| 955 | return nil |
| 956 | } |
| 957 | r.runs++ |
| 958 | r.text += len(s) |
| 959 | if r.runs > maxRuns || r.text > maxText { |
| 960 | return ErrTooLarge |
| 961 | } |
| 962 | run := export.Node{Type: "text", Text: s} |
| 963 | |
| 964 | // The cascade: the run's own properties, its character style, its |
| 965 | // paragraph's style, the document default. |
| 966 | rp = rp.over(r.charInherited(rp.rstyle)).over(p.inh) |
| 967 | face := rp.font |
| 968 | if face != "" { |
| 969 | if f, ok := fonts.ByDocxName(face); ok { |
| 970 | if f != fonts.Default { |
| 971 | run.Marks = append(run.Marks, export.Mark{Type: f.Mark()}) |
| 972 | } |
| 973 | } else { |
| 974 | r.rep.add(CodeFontSubstituted, r.here()) |
| 975 | } |
| 976 | } |
| 977 | size := rp.size |
| 978 | if size != 0 && size != export.BodySizePt*2 { |
| 979 | if mark, ok := sizeMark(size); ok { |
| 980 | run.Marks = append(run.Marks, export.Mark{Type: mark}) |
| 981 | } else { |
| 982 | r.rep.add(CodeSizeDropped, r.here()) |
| 983 | } |
| 984 | } |
| 985 | if rp.bold == on { |
| 986 | run.Marks = append(run.Marks, export.Mark{Type: "strong"}) |
| 987 | } |
| 988 | if rp.italic == on { |
| 989 | run.Marks = append(run.Marks, export.Mark{Type: "em"}) |
| 990 | } |
| 991 | if rp.lost { |
| 992 | r.rep.add(CodeFormattingLost, r.here()) |
| 993 | } |
| 994 | b := &r.blocks[len(r.blocks)-1] |
| 995 | b.runs = append(b.runs, run) |
| 996 | return nil |
| 997 | } |
| 998 | |
| 999 | // sizeMark is the point-ladder mark for a size in half-points. The ladder |
| 1000 | // alone: the retired four-step names are never written. |
| 1001 | func sizeMark(half int) (string, bool) { |
| 1002 | for _, mark := range export.SizeMarks() { |
| 1003 | if !strings.HasPrefix(mark, "size_") { |
| 1004 | continue |
| 1005 | } |
| 1006 | if _, err := strconv.Atoi(strings.TrimPrefix(mark, "size_")); err != nil { |
| 1007 | continue |
| 1008 | } |
| 1009 | if pt, ok := export.SizePt(mark); ok && float64(half) == pt*2 { |
| 1010 | return mark, true |
| 1011 | } |
| 1012 | } |
| 1013 | return "", false |
| 1014 | } |
| 1015 | |
| 1016 | func (r *reader) document() export.Document { |
| 1017 | doc := export.Document{Root: export.Node{Type: "doc"}} |
| 1018 | for _, b := range r.blocks { |
| 1019 | n := export.Node{Type: "paragraph"} |
| 1020 | if b.heading > 0 { |
| 1021 | n = export.Node{Type: "heading", Attrs: export.Attrs{Level: b.heading}} |
| 1022 | } |
| 1023 | n.Content = b.runs |
| 1024 | doc.Root.Content = append(doc.Root.Content, n) |
| 1025 | } |
| 1026 | return doc |
| 1027 | } |
| 1028 | |