dxpdf 0.8.1

Fast DOCX-to-PDF converter powered by Skia
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
//! Parser for document body content: blocks (paragraphs, tables, section breaks)
//! and inline content (text runs, images, hyperlinks, fields, etc.).
//!
//! Single-pass serde over the full document. Drawings and VML picts are
//! serde-parsed inline via `DrawingXml` / `PictXml`; they produce their
//! model values (`Image` / `Pict`) during the `convert_container` walk via
//! the `ConvertCtx`.
//!
//! No style resolution or property merging — output is raw parsed data.

use crate::docx::error::Result;
use crate::docx::model::*;
use crate::docx::parse::body_schema::*;
use crate::docx::parse::serde_xml::from_xml;
use crate::model::Dup;

/// Parse `w:document > w:body`, returning blocks and final section properties.
pub fn parse_body(data: &[u8]) -> Result<(Vec<Block>, SectionProperties)> {
    if data.is_empty() {
        return Ok((Vec::new(), SectionProperties::default()));
    }
    let doc: DocXml = from_xml(data)?;
    let mut ctx = ConvertCtx::new();
    let (blocks, final_section) = convert_container(doc.body.children, &mut ctx);
    Ok((blocks, final_section.unwrap_or_default()))
}

/// Parse a body-level XML part (header, footer, footnote body, etc.) into blocks.
pub fn parse_blocks(data: &[u8]) -> Result<Vec<Block>> {
    if data.is_empty() {
        return Ok(Vec::new());
    }
    let container: BlockContainerXml = from_xml(data)?;
    let mut ctx = ConvertCtx::new();
    let (blocks, _) = convert_container(container.children, &mut ctx);
    Ok(blocks)
}

// ── Top-level document schema wrapper ────────────────────────────────────

use serde::Deserialize;

/// Thin wrapper for `<w:document>` — just extracts `<w:body>`.
#[derive(Deserialize)]
struct DocXml {
    body: BlockContainerXml,
}

// ── Conversion ────────────────────────────────────────────────────────────

/// Conversion context. Previously carried a pre-pass iterator of parsed
/// drawings/picts; now empty, since drawings and picts are serde-parsed
/// inline. Kept as a type for future extensibility (e.g., if a later phase
/// needs cross-node state during conversion).
pub(crate) struct ConvertCtx {
    _private: (),
}

impl ConvertCtx {
    pub(crate) fn new() -> Self {
        Self { _private: () }
    }
}

/// Convert a list of block-level children into `(Vec<Block>, Option<SectionProperties>)`.
/// The section properties, if returned, are for a trailing `<w:sectPr>` at
/// this level — the final section for `<w:body>`, or one that appears inside
/// a table cell (§17.6.17).
pub(crate) fn convert_container(
    children: Vec<BlockChildXml>,
    ctx: &mut ConvertCtx,
) -> (Vec<Block>, Option<SectionProperties>) {
    let mut blocks = Vec::new();
    let mut final_section = None;
    for child in children {
        match child {
            BlockChildXml::Paragraph(p) => {
                let (para, sect_after) = convert_paragraph(*p, ctx);
                blocks.push(Block::Paragraph(Box::new(para)));
                if let Some(sp) = sect_after {
                    blocks.push(Block::SectionBreak(Box::new(sp)));
                }
            }
            BlockChildXml::Table(t) => {
                blocks.push(Block::Table(Box::new(convert_table(*t, ctx))));
            }
            BlockChildXml::SectPr(sp) => {
                final_section = Some(SectionProperties::from(*sp));
            }
            BlockChildXml::Sdt(sdt) => {
                // Flatten SDT wrapper — treat its content as block-level.
                if let Some(content) = Dup::from(sdt.content).into_value() {
                    let (nested_blocks, nested_sect) = convert_container(content.children, ctx);
                    blocks.extend(nested_blocks);
                    if nested_sect.is_some() {
                        final_section = nested_sect;
                    }
                }
            }
            // Block-level markers and ignored elements — renderer doesn't use them.
            BlockChildXml::BookmarkStart(_)
            | BlockChildXml::BookmarkEnd(_)
            | BlockChildXml::CommentRangeStart(_)
            | BlockChildXml::CommentRangeEnd(_)
            | BlockChildXml::ProofErr(_)
            | BlockChildXml::Other => {}
        }
    }
    (blocks, final_section)
}

fn convert_paragraph(p: ParaXml, ctx: &mut ConvertCtx) -> (Paragraph, Option<SectionProperties>) {
    let rsids = ParagraphRevisionIds {
        r: hex_rsid(p.rsid_r.as_deref()),
        r_default: hex_rsid(p.rsid_r_default.as_deref()),
        p: hex_rsid(p.rsid_p.as_deref()),
        r_pr: hex_rsid(p.rsid_r_pr.as_deref()),
        del: hex_rsid(p.rsid_del.as_deref()),
    };

    // pPr may appear as either the dedicated field OR inside $value (serde
    // collects all matching children; since `pPr` is named on the struct
    // *and* in the enum, serde prefers the dedicated field — but just in
    // case, we merge from both sources).
    let p_pr = Dup::from(p.p_pr).into_value().or_else(|| {
        p.content.iter().find_map(|c| {
            if let ParaChildXml::PPr(pp) = c {
                Some((**pp).clone())
            } else {
                None
            }
        })
    });

    let parsed_p_pr = p_pr.map(|pp| pp.split());
    let (style_id, properties, mark_run_properties, section_properties) = match parsed_p_pr {
        Some(pp) => (
            pp.style_id,
            pp.properties,
            pp.run_properties,
            pp.section_properties,
        ),
        None => (None, ParagraphProperties::default(), None, None),
    };

    let content = convert_para_children(p.content, ctx);

    (
        Paragraph {
            style_id,
            properties,
            mark_run_properties,
            content,
            rsids,
        },
        section_properties,
    )
}

/// Flatten a `RunXml`'s children into zero-or-more `Inline`s and append to
/// the parent content. Text / tab / br / cr / lastRenderedPageBreak are
/// accumulated into one `Inline::TextRun`; sibling inlines flush the accumulator
/// and append independently.
fn extend_from_run(r: RunXml, out: &mut Vec<Inline>, ctx: &mut ConvertCtx) {
    let rsids = RevisionIds {
        r: hex_rsid(r.rsid_r.as_deref()),
        r_pr: hex_rsid(r.rsid_r_pr.as_deref()),
        del: hex_rsid(r.rsid_del.as_deref()),
    };
    let (props, style_id) = Dup::from(r.r_pr)
        .into_value()
        .map(|rp| rp.split())
        .unwrap_or_default();

    let mut acc: Vec<RunElement> = Vec::new();
    let flush = |acc: &mut Vec<RunElement>, out: &mut Vec<Inline>| {
        if !acc.is_empty() {
            out.push(Inline::TextRun(Box::new(TextRun {
                style_id: style_id.clone(),
                properties: props.clone(),
                content: std::mem::take(acc),
                rsids,
            })));
        }
    };

    for child in r.content {
        match child {
            RunChildXml::Text(t) => acc.push(RunElement::Text(t.content)),
            RunChildXml::DelText(t) => acc.push(RunElement::Text(t.content)),
            RunChildXml::Tab => acc.push(RunElement::Tab),
            RunChildXml::PTab(p) => acc.push(RunElement::PositionTab(p.into())),
            RunChildXml::Br(br) => acc.push(run_break(br)),
            RunChildXml::Cr => acc.push(RunElement::LineBreak(BreakKind::TextWrapping)),
            RunChildXml::SoftHyphen => {} // optional hyphen — only visible if line breaks here; we don't hyphenate
            RunChildXml::NoBreakHyphen => acc.push(RunElement::Text("\u{2011}".to_string())),
            RunChildXml::LastRenderedPageBreak => acc.push(RunElement::LastRenderedPageBreak),
            RunChildXml::Drawing(d) => {
                flush(&mut acc, out);
                if let Some(img) = drawing_to_image(d, ctx) {
                    out.push(Inline::Image(Box::new(img)));
                }
            }
            RunChildXml::Pict(p) => {
                flush(&mut acc, out);
                out.push(Inline::Pict(p.into_model(ctx)));
            }
            RunChildXml::Sym(s) => {
                flush(&mut acc, out);
                let char_code = u16::from_str_radix(&s.char, 16).unwrap_or_else(|_| {
                    log::warn!("sym: invalid hex char code {:?}; using 0", s.char);
                    0
                });
                out.push(Inline::Symbol(Symbol {
                    font: s.font,
                    char_code,
                }));
            }
            RunChildXml::InstrText(t) => {
                flush(&mut acc, out);
                out.push(Inline::InstrText(t.content));
            }
            RunChildXml::FldChar(fc) => {
                flush(&mut acc, out);
                out.push(Inline::FieldChar(FieldChar {
                    field_char_type: FieldCharType::from(fc.fld_char_type),
                    dirty: fc.dirty.map(|b| b.0),
                    fld_lock: fc.fld_lock.map(|b| b.0),
                }));
            }
            RunChildXml::FootnoteRef(n) => {
                flush(&mut acc, out);
                out.push(Inline::FootnoteRef(NoteId::new(n.id)));
            }
            RunChildXml::EndnoteRef(n) => {
                flush(&mut acc, out);
                out.push(Inline::EndnoteRef(NoteId::new(n.id)));
            }
            RunChildXml::FootnoteRefMark => {
                flush(&mut acc, out);
                out.push(Inline::FootnoteRefMark);
            }
            RunChildXml::EndnoteRefMark => {
                flush(&mut acc, out);
                out.push(Inline::EndnoteRefMark);
            }
            RunChildXml::Separator => {
                flush(&mut acc, out);
                out.push(Inline::Separator);
            }
            RunChildXml::ContinuationSeparator => {
                flush(&mut acc, out);
                out.push(Inline::ContinuationSeparator);
            }
            RunChildXml::AlternateContent(ac) => {
                flush(&mut acc, out);
                out.push(Inline::AlternateContent(convert_alt_content(ac, ctx)));
            }
            RunChildXml::RPr(_) => {} // already captured via r.r_pr
            RunChildXml::CommentReference(_) => {} // comments are not rendered
        }
    }
    flush(&mut acc, out);
}

fn run_break(br: BrXml) -> RunElement {
    use crate::docx::parse::body_schema::StBrType;
    match br.ty {
        Some(StBrType::Page) => RunElement::PageBreak,
        Some(StBrType::Column) => RunElement::ColumnBreak,
        _ => {
            let clear = br.clear.map(BreakClear::from).unwrap_or(BreakClear::None);
            if clear != BreakClear::None {
                RunElement::LineBreak(BreakKind::Clear(clear))
            } else {
                RunElement::LineBreak(BreakKind::TextWrapping)
            }
        }
    }
}

/// Convert a sequence of paragraph-level children (`EG_PContent`) into inline
/// content. Shared by `<w:p>`, `<w:hyperlink>`, and `<w:fldSimple>`, and used
/// recursively to flatten revision/structural wrappers.
///
/// Revision handling is the "accept all changes" (final) view: insert-side
/// wrappers (`<w:ins>`, `<w:moveTo>`) and structural wrappers (`<w:smartTag>`,
/// `<w:customXml>`) are flattened in place and rendered; delete-side wrappers
/// (`<w:del>`, `<w:moveFrom>`) are dropped along with their content. Nested
/// wrappers re-apply the same rules — e.g. a `<w:del>` inside a `<w:ins>` is
/// still dropped.
fn convert_para_children(children: Vec<ParaChildXml>, ctx: &mut ConvertCtx) -> Vec<Inline> {
    let mut content = Vec::new();
    append_para_children(children, &mut content, ctx);
    content
}

fn append_para_children(
    children: Vec<ParaChildXml>,
    content: &mut Vec<Inline>,
    ctx: &mut ConvertCtx,
) {
    for child in children {
        match child {
            ParaChildXml::Run(r) => extend_from_run(r, content, ctx),
            ParaChildXml::Hyperlink(h) => {
                content.push(Inline::Hyperlink(convert_hyperlink(h, ctx)));
            }
            ParaChildXml::FldSimple(f) => {
                content.push(Inline::Field(convert_fld_simple(f, ctx)));
            }
            ParaChildXml::BookmarkStart(b) => content.push(Inline::BookmarkStart {
                id: BookmarkId::new(b.id),
                name: b.name,
            }),
            ParaChildXml::BookmarkEnd(b) => {
                content.push(Inline::BookmarkEnd(BookmarkId::new(b.id)));
            }
            // Insert-side revision + structural wrappers: flatten and render.
            ParaChildXml::Ins(w)
            | ParaChildXml::MoveTo(w)
            | ParaChildXml::SmartTag(w)
            | ParaChildXml::CustomXml(w) => append_para_children(w.content, content, ctx),
            // Delete-side revision wrappers: content is deleted — drop it.
            ParaChildXml::Del(_) | ParaChildXml::MoveFrom(_) => {}
            ParaChildXml::PPr(_) => {} // already captured on the parent
            // §22.1: math keeps its place in the inline flow.
            ParaChildXml::OMath(m) => content.push(Inline::Math(m.into())),
            ParaChildXml::OMathPara(mp) => {
                for m in mp.math {
                    content.push(Inline::Math(m.into()));
                }
            }
            ParaChildXml::Other => {}
        }
    }
}

fn convert_hyperlink(h: HyperlinkXml, ctx: &mut ConvertCtx) -> Hyperlink {
    let target = if let Some(id) = h.r_id {
        HyperlinkTarget::ExternalRel(RelId::new(id))
    } else {
        HyperlinkTarget::Internal {
            anchor: h.anchor.unwrap_or_default(),
        }
    };
    let content = convert_para_children(h.content, ctx);
    Hyperlink { target, content }
}

fn convert_fld_simple(f: FldSimpleXml, ctx: &mut ConvertCtx) -> Field {
    let instruction = match crate::field::parse(&f.instr) {
        Ok(i) => i,
        Err(e) => {
            log::warn!("failed to parse field instruction {:?}: {}", f.instr, e);
            crate::field::FieldInstruction::Unknown {
                field_type: String::new(),
                raw: f.instr.clone(),
            }
        }
    };
    let content = convert_para_children(f.content, ctx);
    Field {
        instruction,
        content,
    }
}

fn convert_alt_content(a: AltContentXml, ctx: &mut ConvertCtx) -> AlternateContent {
    let choices = a
        .choices
        .into_iter()
        .filter_map(|c| {
            // §M.2.2: @Requires is a space-separated list of namespace prefixes;
            // the choice is usable only if we understand *all* of them. A single
            // unknown token drops the whole choice (falling through to the next
            // choice or the fallback).
            let requires: Vec<McRequires> = c
                .requires
                .split_whitespace()
                .map(mc_requires)
                .collect::<Option<_>>()?;
            let content = convert_mc_content(c.content, ctx);
            Some(McChoice { requires, content })
        })
        .collect();
    let fallback = Dup::from(a.fallback)
        .into_value()
        .map(|f| convert_mc_content(f.content, ctx));
    AlternateContent { choices, fallback }
}

fn mc_requires(s: &str) -> Option<McRequires> {
    match s {
        "wps" => Some(McRequires::Wps),
        "wpg" => Some(McRequires::Wpg),
        "wpc" => Some(McRequires::Wpc),
        "wpi" => Some(McRequires::Wpi),
        "m" => Some(McRequires::Math),
        "a14" => Some(McRequires::A14),
        "w14" => Some(McRequires::W14),
        "w15" => Some(McRequires::W15),
        "w16" => Some(McRequires::W16),
        other => {
            log::warn!("mc:Choice: unsupported Requires {:?}", other);
            None
        }
    }
}

fn convert_mc_content(items: Vec<McContentXml>, ctx: &mut ConvertCtx) -> Vec<Inline> {
    let mut out = Vec::new();
    for i in items {
        match i {
            McContentXml::Drawing(d) => {
                if let Some(img) = drawing_to_image(d, ctx) {
                    out.push(Inline::Image(Box::new(img)));
                }
            }
            McContentXml::Pict(p) => {
                out.push(Inline::Pict(p.into_model(ctx)));
            }
        }
    }
    out
}

/// Convert a serde-parsed `<w:drawing>` into the model's `Image`. Returns
/// `None` when neither `<wp:inline>` nor `<wp:anchor>` is present.
fn drawing_to_image(
    d: crate::docx::parse::body_schema::DrawingXml,
    ctx: &mut ConvertCtx,
) -> Option<Image> {
    if let Some(inline) = Dup::from(d.inline).into_value() {
        return Some(inline.into_image(ctx));
    }
    Dup::from(d.anchor).into_value().map(|a| a.into_image(ctx))
}

fn convert_table(t: TableXml, ctx: &mut ConvertCtx) -> Table {
    let (properties, _style_id) = Dup::from(t.tbl_pr)
        .into_value()
        .map(|tp| tp.split())
        .unwrap_or_default();
    let grid = Dup::from(t.tbl_grid)
        .into_value()
        .map(|g| {
            g.cols
                .into_iter()
                .map(|c| GridColumn {
                    width: c.w.unwrap_or_default(),
                })
                .collect()
        })
        .unwrap_or_default();
    let rows = collect_table_rows(t.children)
        .into_iter()
        .map(|r| convert_table_row(r, ctx))
        .collect();
    Table {
        properties,
        grid,
        rows,
    }
}

/// Walk `<w:tbl>`'s direct children and flatten out every `<w:tr>`,
/// recursing through revision-tracking, custom-XML, and SDT row wrappers.
/// Range markers, proofreading errors, permission ranges, and the
/// `tblPr`/`tblGrid` duplicates produced by `$value` are dropped — they
/// have no rendered effect at table level. Document order is preserved.
///
/// Revision handling is the **final** view, the same rule
/// [`append_para_children`] applies to runs: insert-side wrappers (`<w:ins>`,
/// `<w:moveTo>`) contribute their rows and delete-side ones (`<w:del>`,
/// `<w:moveFrom>`) do not. Rows and runs must answer this the same way or a
/// single document renders half in each view.
///
/// A row is deleted in either of two spellings, and both are handled here: the
/// table-level wrapper above, and `<w:del>` inside the row's own `<w:trPr>` —
/// which is the one **Word** writes. The `trPr` form is the reason this cannot
/// be a wrapper-only rule: Word wraps the deleted row's runs in `<w:del>` too,
/// so ignoring the row marker left an empty row that belongs to neither view.
fn collect_table_rows(children: Vec<TableChildXml>) -> Vec<TableRowXml> {
    let mut rows = Vec::with_capacity(children.len());
    for child in children {
        match child {
            TableChildXml::Row(r) => rows.push(*r),
            TableChildXml::Sdt(s) => {
                if let Some(content) = Dup::from(s.content).into_value() {
                    rows.extend(collect_table_rows(content.children));
                }
            }
            // Insert side: the rows are in the final document.
            TableChildXml::Ins(rt) | TableChildXml::MoveTo(rt) => rows.extend(rt.rows),
            // Delete side: they are not.
            TableChildXml::Del(_) | TableChildXml::MoveFrom(_) => {}
            TableChildXml::CustomXml(cx) => {
                rows.extend(collect_table_rows(cx.children));
            }
            TableChildXml::BookmarkStart(_)
            | TableChildXml::BookmarkEnd(_)
            | TableChildXml::CommentRangeStart(_)
            | TableChildXml::CommentRangeEnd(_)
            | TableChildXml::ProofErr(_)
            | TableChildXml::PermStart(_)
            | TableChildXml::PermEnd(_)
            | TableChildXml::TblPr(_)
            | TableChildXml::TblGrid(_)
            | TableChildXml::Other => {}
        }
    }
    // Applied once over everything gathered above, so a row marked deleted in
    // its own `<w:trPr>` goes whether it sat bare in the table, inside an
    // `<w:ins>`, or inside an `<w:sdt>`. Idempotent, so the recursive calls
    // having already run it costs nothing.
    // `last()` is [`Dup`]'s §17.7.2 last-wins rule spelled out on a borrow —
    // the same occurrence `convert_table_row`'s `Dup::from(r.tr_pr)` resolves
    // to, so a document that repeats `<w:trPr>` cannot have the deletion read
    // off one copy and every other property off another.
    rows.retain(|r| !r.tr_pr.last().is_some_and(|pr| pr.marks_row_deleted()));
    rows
}

fn convert_table_row(r: TableRowXml, ctx: &mut ConvertCtx) -> TableRow {
    let rsids = TableRowRevisionIds {
        r: hex_rsid(r.rsid_r.as_deref()),
        r_pr: hex_rsid(r.rsid_r_pr.as_deref()),
        del: hex_rsid(r.rsid_del.as_deref()),
        tr: hex_rsid(r.rsid_tr.as_deref()),
    };
    let properties = Dup::from(r.tr_pr)
        .into_value()
        .map(TableRowProperties::from)
        .unwrap_or_default();
    let property_exceptions = Dup::from(r.tbl_pr_ex).into_value().map(Into::into);
    let cells = collect_row_cells(r.children)
        .into_iter()
        .map(|c| convert_table_cell(c, ctx))
        .collect();
    TableRow {
        properties,
        cells,
        rsids,
        property_exceptions,
    }
}

/// Walk a `<w:tr>`'s direct children and flatten out every `<w:tc>`,
/// recursing through cell-level SDT (`<w:sdt>`) and custom-XML wrappers.
/// Range markers, proofreading errors, permission ranges, and the
/// `tblPrEx`/`trPr` duplicates produced by `$value` are dropped — they have
/// no rendered effect at cell level. Document order is preserved. Mirrors
/// `collect_table_rows` one level down.
fn collect_row_cells(children: Vec<RowChildXml>) -> Vec<TableCellXml> {
    let mut cells = Vec::with_capacity(children.len());
    for child in children {
        match child {
            RowChildXml::Cell(c) => cells.push(*c),
            RowChildXml::Sdt(s) => {
                if let Some(content) = Dup::from(s.content).into_value() {
                    cells.extend(collect_row_cells(content.children));
                }
            }
            RowChildXml::CustomXml(cx) => {
                cells.extend(collect_row_cells(cx.children));
            }
            RowChildXml::BookmarkStart(_)
            | RowChildXml::BookmarkEnd(_)
            | RowChildXml::CommentRangeStart(_)
            | RowChildXml::CommentRangeEnd(_)
            | RowChildXml::ProofErr(_)
            | RowChildXml::PermStart(_)
            | RowChildXml::PermEnd(_)
            | RowChildXml::TblPrEx(_)
            | RowChildXml::TrPr(_)
            | RowChildXml::Other => {}
        }
    }
    cells
}

fn convert_table_cell(c: TableCellXml, ctx: &mut ConvertCtx) -> TableCell {
    let properties = Dup::from(c.tc_pr)
        .into_value()
        .map(TableCellProperties::from)
        .unwrap_or_default();
    let (content, _final_sect) = convert_container(c.content, ctx);
    TableCell {
        properties,
        content,
    }
}

// ── helpers ──────────────────────────────────────────────────────────────

fn hex_rsid(s: Option<&str>) -> Option<RevisionSaveId> {
    s.and_then(RevisionSaveId::from_hex)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Collect all rendered text from a converted inline sequence, recursing
    /// into hyperlinks and fields.
    fn collect_text(inlines: &[Inline]) -> String {
        let mut s = String::new();
        for inl in inlines {
            match inl {
                Inline::TextRun(r) => {
                    for el in &r.content {
                        if let RunElement::Text(t) = el {
                            s.push_str(t);
                        }
                    }
                }
                Inline::Hyperlink(h) => s.push_str(&collect_text(&h.content)),
                Inline::Field(f) => s.push_str(&collect_text(&f.content)),
                _ => {}
            }
        }
        s
    }

    /// Parse a `<w:p>` and return the concatenated rendered text.
    fn para_text(xml: &str) -> String {
        let p: ParaXml = quick_xml::de::from_str(xml).unwrap();
        let mut ctx = ConvertCtx::new();
        let (para, _) = convert_paragraph(p, &mut ctx);
        collect_text(&para.content)
    }

    /// Parse a `<w:p>` and return the run-elements of its first `TextRun`.
    fn first_run_elements(xml: &str) -> Vec<RunElement> {
        let p: ParaXml = quick_xml::de::from_str(xml).unwrap();
        let mut ctx = ConvertCtx::new();
        let (para, _) = convert_paragraph(p, &mut ctx);
        para.content
            .into_iter()
            .find_map(|i| match i {
                Inline::TextRun(r) => Some(r.content),
                _ => None,
            })
            .unwrap_or_default()
    }

    // ── Revision & structural wrappers (accept-all-changes / final view) ──

    #[test]
    fn ins_content_is_rendered() {
        // Tracked insertions are part of the final document — their runs must
        // survive (previously `<w:ins>` hit the `Other` catch-all and vanished).
        assert_eq!(
            para_text(r#"<w:p xmlns:w="x"><w:ins><w:r><w:t>kept</w:t></w:r></w:ins></w:p>"#),
            "kept"
        );
    }

    #[test]
    fn del_content_is_dropped() {
        // Tracked deletions are not in the final document — drop them.
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:del><w:r><w:delText>gone</w:delText></w:r></w:del></w:p>"#
            ),
            ""
        );
    }

    #[test]
    fn del_nested_in_ins_is_still_dropped() {
        // Nested wrappers re-apply the rules: text inserted then deleted is
        // deleted; the surrounding insertion is kept.
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:ins>
                     <w:r><w:t>A</w:t></w:r>
                     <w:del><w:r><w:delText>B</w:delText></w:r></w:del>
                     <w:r><w:t>C</w:t></w:r>
                   </w:ins></w:p>"#
            ),
            "AC"
        );
    }

    #[test]
    fn move_to_rendered_move_from_dropped() {
        assert_eq!(
            para_text(r#"<w:p xmlns:w="x"><w:moveTo><w:r><w:t>here</w:t></w:r></w:moveTo></w:p>"#),
            "here"
        );
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:moveFrom><w:r><w:t>away</w:t></w:r></w:moveFrom></w:p>"#
            ),
            ""
        );
    }

    #[test]
    fn smart_tag_and_inline_custom_xml_are_flattened() {
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:smartTag><w:r><w:t>date</w:t></w:r></w:smartTag></w:p>"#
            ),
            "date"
        );
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:customXml><w:r><w:t>tagged</w:t></w:r></w:customXml></w:p>"#
            ),
            "tagged"
        );
    }

    #[test]
    fn ins_wrapping_a_hyperlink_keeps_the_link_text() {
        assert_eq!(
            para_text(
                r#"<w:p xmlns:w="x"><w:ins>
                     <w:hyperlink w:anchor="a"><w:r><w:t>link</w:t></w:r></w:hyperlink>
                   </w:ins></w:p>"#
            ),
            "link"
        );
    }

    // ── Revision-tracked *rows* (same final view as revision-tracked runs) ──

    /// The concatenated text of each surviving row of a `<w:tbl>`, in document
    /// order. Reads the converted model rather than the schema, so it measures
    /// what a renderer would be handed.
    fn table_row_texts(xml: &str) -> Vec<String> {
        let t: TableXml = quick_xml::de::from_str(xml).unwrap();
        let mut ctx = ConvertCtx::new();
        convert_table(t, &mut ctx)
            .rows
            .into_iter()
            .map(|r| {
                r.cells
                    .into_iter()
                    .flat_map(|c| c.content)
                    .filter_map(|b| match b {
                        Block::Paragraph(p) => Some(collect_text(&p.content)),
                        _ => None,
                    })
                    .collect::<String>()
            })
            .collect()
    }

    /// A `<w:tbl>` of three rows, the middle one wrapped in `wrapper`.
    fn table_with_wrapped_row(wrapper: &str) -> String {
        format!(
            r#"<w:tbl xmlns:w="x">
                 <w:tblPr/>
                 <w:tblGrid><w:gridCol w:w="100"/></w:tblGrid>
                 <w:tr><w:tc><w:p><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr>
                 <w:{wrapper} w:id="1" w:author="a" w:date="d">
                   <w:tr><w:tc><w:p><w:r><w:t>B</w:t></w:r></w:p></w:tc></w:tr>
                 </w:{wrapper}>
                 <w:tr><w:tc><w:p><w:r><w:t>C</w:t></w:r></w:p></w:tc></w:tr>
               </w:tbl>"#
        )
    }

    /// A `<w:tbl>` of three rows, the middle one carrying `marker` in its
    /// `<w:trPr>` — the form Word writes when a row is deleted or inserted with
    /// change tracking on.
    fn table_with_marked_row(marker: &str) -> String {
        format!(
            r#"<w:tbl xmlns:w="x">
                 <w:tblPr/>
                 <w:tblGrid><w:gridCol w:w="100"/></w:tblGrid>
                 <w:tr><w:tc><w:p><w:r><w:t>A</w:t></w:r></w:p></w:tc></w:tr>
                 <w:tr>
                   <w:trPr>{marker}</w:trPr>
                   <w:tc><w:p><w:r><w:t>B</w:t></w:r></w:p></w:tc>
                 </w:tr>
                 <w:tr><w:tc><w:p><w:r><w:t>C</w:t></w:r></w:p></w:tc></w:tr>
               </w:tbl>"#
        )
    }

    /// A table-level `<w:del>` is the delete side of a tracked change, exactly
    /// as `<w:del>` around a run is — and this parser renders the *final* view,
    /// so both go. Keeping deleted rows while dropping deleted runs left the
    /// engine rendering the final view for text and the original view for
    /// rows, in the same document.
    #[test]
    fn del_wrapped_rows_are_dropped() {
        assert_eq!(table_row_texts(&table_with_wrapped_row("del")), ["A", "C"]);
    }

    /// The move-away side goes with it (`move_to_rendered_move_from_dropped`
    /// is the run-level twin).
    #[test]
    fn move_from_wrapped_rows_are_dropped() {
        assert_eq!(
            table_row_texts(&table_with_wrapped_row("moveFrom")),
            ["A", "C"]
        );
    }

    /// The insert side is part of the final document and must survive — the
    /// control that a "drop tracked rows" fix would break.
    #[test]
    fn ins_and_move_to_wrapped_rows_are_kept() {
        assert_eq!(
            table_row_texts(&table_with_wrapped_row("ins")),
            ["A", "B", "C"]
        );
        assert_eq!(
            table_row_texts(&table_with_wrapped_row("moveTo")),
            ["A", "B", "C"]
        );
    }

    /// `<w:del>` inside `<w:trPr>` is how **Word** marks a deleted row — the
    /// table-level wrapper above is the other spelling, and the one Word does
    /// not use. Unmodelled, it left the row in place; its runs are separately
    /// wrapped in `<w:del>` and already dropped, so the row rendered as an
    /// empty ghost belonging to neither view of the document.
    #[test]
    fn a_row_deleted_in_its_tr_pr_is_dropped() {
        assert_eq!(
            table_row_texts(&table_with_marked_row(
                r#"<w:del w:id="1" w:author="a" w:date="d"/>"#
            )),
            ["A", "C"]
        );
    }

    /// `<w:ins>` in the same position marks an *inserted* row, which the final
    /// view keeps. Pins that the two markers are told apart rather than the
    /// row being dropped for carrying any revision mark at all.
    #[test]
    fn a_row_inserted_in_its_tr_pr_is_kept() {
        assert_eq!(
            table_row_texts(&table_with_marked_row(
                r#"<w:ins w:id="1" w:author="a" w:date="d"/>"#
            )),
            ["A", "B", "C"]
        );
    }

    /// A row whose `<w:trPr>` carries ordinary properties is untouched — the
    /// new field must not turn every `trPr` into a deletion.
    #[test]
    fn a_row_with_an_unrelated_tr_pr_is_kept() {
        assert_eq!(
            table_row_texts(&table_with_marked_row(r#"<w:cantSplit/>"#)),
            ["A", "B", "C"]
        );
    }

    // ── run_break ────────────────────────────────────────────────────────

    #[test]
    fn br_type_page_and_column() {
        assert!(matches!(
            first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br type="page"/></w:r></w:p>"#)
                .as_slice(),
            [RunElement::PageBreak]
        ));
        assert!(matches!(
            first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br type="column"/></w:r></w:p>"#)
                .as_slice(),
            [RunElement::ColumnBreak]
        ));
    }

    #[test]
    fn br_plain_is_text_wrapping_line_break() {
        assert!(matches!(
            first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br/></w:r></w:p>"#).as_slice(),
            [RunElement::LineBreak(BreakKind::TextWrapping)]
        ));
    }

    #[test]
    fn br_clear_all_is_clearing_line_break() {
        assert!(matches!(
            first_run_elements(r#"<w:p xmlns:w="x"><w:r><w:br clear="all"/></w:r></w:p>"#)
                .as_slice(),
            [RunElement::LineBreak(BreakKind::Clear(BreakClear::All))]
        ));
    }

    // ── mc:Choice Requires ───────────────────────────────────────────────

    #[test]
    fn mc_requires_known_and_unknown() {
        assert_eq!(mc_requires("wps"), Some(McRequires::Wps));
        assert_eq!(mc_requires("w14"), Some(McRequires::W14));
        // Unknown / unsupported token → None (choice is dropped, fallback used).
        assert_eq!(mc_requires("nope"), None);
        // `mc_requires` maps a *single* token; a space-separated list is split by
        // `convert_alt_content` (see `alt_content_requires_*` below), so a raw
        // multi-token string is not a valid single token.
        assert_eq!(mc_requires("wps w14"), None);
    }

    #[test]
    fn alt_content_multi_token_requires_is_kept_when_all_known() {
        // §M.2.2: a space-separated Requires with every token understood keeps
        // the choice (previously the whole choice was dropped).
        let xml = r#"<w:r xmlns:w="x" xmlns:mc="m">
              <mc:AlternateContent>
                <mc:Choice Requires="wps w14"><w:drawing/></mc:Choice>
                <mc:Fallback/>
              </mc:AlternateContent>
            </w:r>"#;
        let r: RunXml = quick_xml::de::from_str(xml).unwrap();
        let mut out = Vec::new();
        let mut ctx = ConvertCtx::new();
        extend_from_run(r, &mut out, &mut ctx);
        let Some(Inline::AlternateContent(ac)) = out.into_iter().next() else {
            panic!("expected AlternateContent");
        };
        assert_eq!(ac.choices.len(), 1, "multi-token choice kept");
        assert_eq!(
            ac.choices[0].requires,
            vec![McRequires::Wps, McRequires::W14]
        );
    }

    #[test]
    fn alt_content_choice_with_unknown_token_is_dropped() {
        let xml = r#"<w:r xmlns:w="x" xmlns:mc="m">
              <mc:AlternateContent>
                <mc:Choice Requires="wps nope"><w:drawing/></mc:Choice>
                <mc:Fallback/>
              </mc:AlternateContent>
            </w:r>"#;
        let r: RunXml = quick_xml::de::from_str(xml).unwrap();
        let mut out = Vec::new();
        let mut ctx = ConvertCtx::new();
        extend_from_run(r, &mut out, &mut ctx);
        let Some(Inline::AlternateContent(ac)) = out.into_iter().next() else {
            panic!("expected AlternateContent");
        };
        assert!(
            ac.choices.is_empty(),
            "choice with an unknown token dropped"
        );
    }

    /// Regression: a `<w:tr>` whose `<w:tc>` cells are interleaved with
    /// cell-level `<w:sdt>` (CT_SdtCell) wrappers must (a) parse — the old
    /// `Vec<TableCellXml>` field reported a duplicate `tc` when cells were
    /// non-contiguous — and (b) recover every cell, including the ones nested
    /// inside `<w:sdtContent>`.
    #[test]
    fn row_with_interspersed_sdt_cells_recovers_all_cells() {
        let xml = r#"
            <w:tr xmlns:w="x">
              <w:trPr/>
              <w:tc><w:p/></w:tc>
              <w:tc><w:p/></w:tc>
              <w:sdt>
                <w:sdtPr/>
                <w:sdtContent><w:tc><w:p/></w:tc></w:sdtContent>
              </w:sdt>
              <w:sdt>
                <w:sdtContent><w:tc><w:p/></w:tc></w:sdtContent>
              </w:sdt>
              <w:tc><w:p/></w:tc>
            </w:tr>
        "#;
        let row: TableRowXml = quick_xml::de::from_str(xml).expect("row must parse");
        assert!(!row.tr_pr.is_empty(), "trPr still captured on the parent");
        let cells = collect_row_cells(row.children);
        assert_eq!(cells.len(), 5, "3 bare + 2 sdt-wrapped cells recovered");
    }

    /// Nested `<w:customXml>` cell wrapper (CT_CustomXmlCell) also flattens.
    #[test]
    fn row_with_custom_xml_cell_wrapper_recovers_cells() {
        let xml = r#"
            <w:tr xmlns:w="x">
              <w:tc><w:p/></w:tc>
              <w:customXml>
                <w:tc><w:p/></w:tc>
                <w:tc><w:p/></w:tc>
              </w:customXml>
            </w:tr>
        "#;
        let row: TableRowXml = quick_xml::de::from_str(xml).expect("row must parse");
        assert_eq!(collect_row_cells(row.children).len(), 3);
    }

    /// A `<w:customXml>` row wrapper (CT_CustomXmlRow) inside `<w:tbl>` must
    /// have its nested `<w:tr>` rows recovered — the element is `customXml`,
    /// not `customXmlIns`/etc., so the wrong rename previously dropped them.
    #[test]
    fn table_with_custom_xml_row_wrapper_recovers_rows() {
        let xml = r#"
            <w:tbl xmlns:w="x">
              <w:tblPr/>
              <w:tblGrid><w:gridCol w:w="100"/></w:tblGrid>
              <w:tr><w:tc><w:p/></w:tc></w:tr>
              <w:customXml>
                <w:tr><w:tc><w:p/></w:tc></w:tr>
              </w:customXml>
            </w:tbl>
        "#;
        let tbl: TableXml = quick_xml::de::from_str(xml).expect("table must parse");
        assert_eq!(collect_table_rows(tbl.children).len(), 2);
    }

    // ── §22.1 Office Math ────────────────────────────────────────────────

    /// `m:oMath` as a direct child of `w:p`: the superscript and run
    /// structure must survive into `Inline::Math`, in flow order.
    #[test]
    fn omath_inline_parses_to_math_block() {
        let xml = r#"<w:p xmlns:w="x" xmlns:m="mm">
              <m:oMath>
                <m:sSup>
                  <m:e><m:r><m:t>x</m:t></m:r></m:e>
                  <m:sup><m:r><m:t>2</m:t></m:r></m:sup>
                </m:sSup>
                <m:r><m:t>+</m:t></m:r>
              </m:oMath>
            </w:p>"#;
        let p: ParaXml = quick_xml::de::from_str(xml).unwrap();
        let mut ctx = ConvertCtx::new();
        let content = convert_para_children(p.content, &mut ctx);

        let [Inline::Math(math)] = content.as_slice() else {
            panic!("expected one Inline::Math, got {content:?}");
        };
        let [MathElement::Superscript { base, sup }, MathElement::Run(plus)] =
            math.content.as_slice()
        else {
            panic!("expected sSup then run, got {:?}", math.content);
        };
        assert_eq!(base, &[MathElement::Run(MathRun { text: "x".into() })]);
        assert_eq!(sup, &[MathElement::Run(MathRun { text: "2".into() })]);
        assert_eq!(plus.text, "+");
    }

    /// `m:f` keeps numerator and denominator; `m:oMathPara` flattens to its
    /// `m:oMath` children; an unknown construct is dropped without taking
    /// the rest of the equation with it.
    #[test]
    fn omath_fraction_math_para_and_unknown_construct() {
        let xml = r#"<w:p xmlns:w="x" xmlns:m="mm">
              <m:oMathPara>
                <m:oMathParaPr/>
                <m:oMath>
                  <m:rad><m:e><m:r><m:t>y</m:t></m:r></m:e></m:rad>
                  <m:f>
                    <m:num><m:r><m:t>1</m:t></m:r></m:num>
                    <m:den><m:r><m:t>2</m:t></m:r></m:den>
                  </m:f>
                </m:oMath>
              </m:oMathPara>
            </w:p>"#;
        let p: ParaXml = quick_xml::de::from_str(xml).unwrap();
        let mut ctx = ConvertCtx::new();
        let content = convert_para_children(p.content, &mut ctx);

        let [Inline::Math(math)] = content.as_slice() else {
            panic!("expected one Inline::Math, got {content:?}");
        };
        // The unsupported m:rad is skipped; the fraction survives.
        let [MathElement::Fraction { num, den }] = math.content.as_slice() else {
            panic!("expected one fraction, got {:?}", math.content);
        };
        assert_eq!(num, &[MathElement::Run(MathRun { text: "1".into() })]);
        assert_eq!(den, &[MathElement::Run(MathRun { text: "2".into() })]);
    }
}