docxide-pdf 0.18.4

Library and CLI for converting DOCX files to PDF, matching Microsoft Word's output as closely as possible
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
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
mod alt_chunk;
mod charts;
mod color;
mod comments;
mod embedded_fonts;
pub(crate) mod emf;
mod group;
mod headers_footers;
mod images;
mod math_speech;
pub(crate) mod numbering;
mod paragraph;
mod runs;
mod sections;
mod settings;
pub(crate) mod smartart;
mod styles;
mod tables;
mod textbox;
mod wmf;
mod wordart;

use std::collections::HashMap;
use std::io::Read;

use crate::error::Error;
use crate::model::{
    Block, BorderStyle, CellBorder, DocGridType, Document, FrameProperties, HRelativeFrom,
    HorizontalPosition, LineSpacing, ParagraphBorder, ParagraphBorders, Section, SectionBreakType,
    SectionProperties, TabAlignment, TabStop, VRelativeFrom, VerticalPosition,
};

use styles::{ParagraphStyle, StyleDefaults, parse_line_spacing, parse_styles, parse_theme};

use embedded_fonts::parse_font_table;
use headers_footers::{parse_endnotes, parse_footnotes};
use numbering::parse_numbering;
use relationships::parse_relationships;
use sections::parse_section_properties;
use settings::parse_settings;
use tables::parse_table_node;

pub(super) const WML_NS: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
pub(super) const DML_NS: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
pub(super) const WPD_NS: &str =
    "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
pub(super) const WPS_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingShape";
pub(super) const REL_NS: &str =
    "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
pub(super) const MC_NS_TOP: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006";
pub(super) const CHART_NS: &str = "http://schemas.openxmlformats.org/drawingml/2006/chart";
pub(super) const DSP_NS: &str = "http://schemas.microsoft.com/office/drawing/2008/diagram";
pub(super) const W14_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordml";
pub(super) const VML_NS: &str = "urn:schemas-microsoft-com:vml";
pub(super) const W10_NS: &str = "urn:schemas-microsoft-com:office:word";
pub(super) const OFFICE_NS: &str = "urn:schemas-microsoft-com:office:office";
pub(super) const PIC_NS: &str = "http://schemas.openxmlformats.org/drawingml/2006/picture";
pub(super) const DIAGRAM_NS: &str = "http://schemas.openxmlformats.org/drawingml/2006/diagram";
pub(super) const MATH_NS: &str = "http://schemas.openxmlformats.org/officeDocument/2006/math";
pub(super) const WPC_NS: &str =
    "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas";
pub(super) const WPG_NS: &str = "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup";

pub(super) fn twips_to_pts(twips: f32) -> f32 {
    twips / 20.0
}

pub(super) fn emu_to_pts(emu: f32) -> f32 {
    emu / 12700.0
}

/// A numeric attribute; `None` when absent or unparsable.
pub(super) fn f32_attr<'n, 'm>(
    node: roxmltree::Node,
    attr: impl Into<roxmltree::ExpandedName<'n, 'm>>,
) -> Option<f32> {
    node.attribute(attr).and_then(|v| v.parse::<f32>().ok())
}

/// An EMU attribute in points; `None` when absent.
pub(super) fn emu_attr_opt<'n, 'm>(
    node: roxmltree::Node,
    attr: impl Into<roxmltree::ExpandedName<'n, 'm>>,
) -> Option<f32> {
    f32_attr(node, attr).map(emu_to_pts)
}

/// An EMU attribute in points; 0 when absent.
pub(super) fn emu_attr(node: roxmltree::Node, attr: &str) -> f32 {
    emu_attr_opt(node, attr).unwrap_or(0.0)
}

/// A DrawingML angle attribute (60000ths of a degree) in degrees.
pub(super) fn angle_attr<'n, 'm>(
    node: roxmltree::Node,
    attr: impl Into<roxmltree::ExpandedName<'n, 'm>>,
) -> Option<f32> {
    f32_attr(node, attr).map(|v| v / 60_000.0)
}

/// A DrawingML percentage attribute (`ST_Percentage` as 1/1000 of a percent)
/// as a fraction.
pub(super) fn frac_attr<'n, 'm>(
    node: roxmltree::Node,
    attr: impl Into<roxmltree::ExpandedName<'n, 'm>>,
) -> Option<f32> {
    f32_attr(node, attr).map(|v| v / 100_000.0)
}

/// ST_OnOff truthiness (§17.17.4): "1", "true", and "on" all mean on.
pub(super) fn parse_on_off(v: &str) -> bool {
    matches!(v, "1" | "true" | "on")
}

/// Parse a VML/CSS length like "12.5pt" — the "pt" suffix and surrounding
/// whitespace are optional.
pub(super) fn parse_pt(s: &str) -> Option<f32> {
    s.trim().trim_end_matches("pt").trim().parse::<f32>().ok()
}

/// Find a child element by name and namespace.
pub(super) fn find_child<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
    namespace: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    node.children().find(|n| n.has_tag_name((namespace, name)))
}

pub(super) fn dml<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, DML_NS)
}

/// All child elements with the given name and namespace.
pub(super) fn find_children<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
    namespace: &str,
) -> impl Iterator<Item = roxmltree::Node<'a, 'a>> {
    node.children()
        .filter(move |n| n.has_tag_name((namespace, name)))
}

pub(super) fn dml_children<'a>(
    parent: roxmltree::Node<'a, 'a>,
    name: &str,
) -> impl Iterator<Item = roxmltree::Node<'a, 'a>> {
    find_children(parent, name, DML_NS)
}

pub(super) fn wpd<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, WPD_NS)
}

pub(super) fn wps<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, WPS_NS)
}

pub(super) fn dsp<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, DSP_NS)
}

pub(super) fn chart_ns<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, CHART_NS)
}

pub(super) fn chart_ns_attr<'a>(node: roxmltree::Node<'a, 'a>, child: &str) -> Option<&'a str> {
    chart_ns(node, child).and_then(|n| n.attribute("val"))
}

pub(super) fn chart_ns_children<'a>(
    parent: roxmltree::Node<'a, 'a>,
    name: &str,
) -> impl Iterator<Item = roxmltree::Node<'a, 'a>> {
    find_children(parent, name, CHART_NS)
}

pub(in crate::docx) struct ParseContext<'a, R: std::io::Read + std::io::Seek> {
    pub(in crate::docx) styles: &'a styles::StylesInfo,
    pub(in crate::docx) theme: &'a styles::ThemeFonts,
    pub(in crate::docx) rels: &'a HashMap<String, String>,
    pub(in crate::docx) zip: &'a mut zip::ZipArchive<R>,
    pub(in crate::docx) numbering: &'a numbering::NumberingInfo,
}

pub(crate) fn is_east_asian_char(ch: char) -> bool {
    matches!(ch as u32,
        0x2E80..=0x2EFF   // CJK Radicals Supplement
        | 0x2F00..=0x2FDF // Kangxi Radicals
        | 0x2FF0..=0x2FFF // Ideographic Description Characters
        | 0x3000..=0x303F // CJK Symbols and Punctuation
        | 0x3040..=0x309F // Hiragana
        | 0x30A0..=0x30FF // Katakana
        | 0x3100..=0x312F // Bopomofo
        | 0x3130..=0x318F // Hangul Compatibility Jamo
        | 0x31A0..=0x31BF // Bopomofo Extended
        | 0x31F0..=0x31FF // Katakana Phonetic Extensions
        | 0x3200..=0x32FF // Enclosed CJK Letters and Months
        | 0x3300..=0x33FF // CJK Compatibility
        | 0x3400..=0x4DBF // CJK Unified Ideographs Extension A
        | 0x4E00..=0x9FFF // CJK Unified Ideographs
        | 0xAC00..=0xD7AF // Hangul Syllables
        | 0xF900..=0xFAFF // CJK Compatibility Ideographs
        | 0xFE30..=0xFE4F // CJK Compatibility Forms
        | 0xFF00..=0xFFEF // Halfwidth and Fullwidth Forms
        | 0x1100..=0x11FF // Hangul Jamo
        | 0x20000..=0x2A6DF // CJK Unified Ideographs Extension B
        | 0x2A700..=0x2B73F // CJK Unified Ideographs Extension C
        | 0x2B740..=0x2B81F // CJK Unified Ideographs Extension D
    )
}

/// Letters Word draws in the complex-script (`w:cs`) font.
// ponytail: right-to-left scripts only; Thai and Indic are complex script in
// Word too, add them with a fixture that shows their fallback font.
pub(crate) fn is_complex_script_char(ch: char) -> bool {
    matches!(ch as u32,
        0x0590..=0x07BF   // Hebrew, Arabic, Syriac, Arabic Supplement, Thaana
        | 0x08A0..=0x08FF // Arabic Extended-A
        | 0xFB1D..=0xFDFF // Hebrew and Arabic Presentation Forms-A
        | 0xFE70..=0xFEFE // Arabic Presentation Forms-B (U+FEFF is the BOM)
    )
}

pub(super) fn parse_hex_color(val: &str) -> Option<[u8; 3]> {
    if val == "auto" || val.len() != 6 {
        return None;
    }
    let r = u8::from_str_radix(&val[0..2], 16).ok()?;
    let g = u8::from_str_radix(&val[2..4], 16).ok()?;
    let b = u8::from_str_radix(&val[4..6], 16).ok()?;
    Some([r, g, b])
}

pub(super) fn parse_text_color(val: &str) -> Option<[u8; 3]> {
    if val == "auto" {
        return Some([0, 0, 0]);
    }
    parse_hex_color(val)
}

/// Parse a `w:shd` child element on a `w:rPr` (or similar) node.
/// Returns `Some(rgb)` when an explicit color is present, else `None`
/// (caller should inherit from style/basedOn). In Word, `w:val="nil"` and
/// `w:fill="auto"` are *not* treated as overrides that clear inherited
/// shading — they simply mean "no color specified here."
///
/// `w:themeFill` resolution is TODO.
pub(super) fn parse_run_shd(parent: roxmltree::Node) -> Option<[u8; 3]> {
    wml(parent, "shd").and_then(shd_color)
}

/// The solid color a `w:shd` paints: its `solid`/`pctNN` pattern of `w:color`
/// (auto = black) laid over `w:fill` (auto = white), §17.18.78. A `solid`
/// shd paints `w:color` alone (CC99FF over fill auto is CC99FF).
pub(super) fn shd_color(shd: roxmltree::Node) -> Option<[u8; 3]> {
    let fill = shd
        .attribute((WML_NS, "fill"))
        .filter(|f| *f != "auto" && *f != "none")
        .and_then(parse_hex_color);
    let coverage = match shd.attribute((WML_NS, "val")) {
        Some("nil") => return None,
        Some("solid") => 1.0,
        Some(v) => v
            .strip_prefix("pct")
            .and_then(|p| p.parse::<f32>().ok())
            .map_or(0.0, |p| (p / 100.0).clamp(0.0, 1.0)),
        None => 0.0,
    };
    if coverage == 0.0 {
        return fill;
    }
    let ink = shd
        .attribute((WML_NS, "color"))
        .and_then(parse_hex_color)
        .unwrap_or([0, 0, 0]);
    let bg = fill.unwrap_or([255, 255, 255]);
    Some(std::array::from_fn(|i| {
        (bg[i] as f32 * (1.0 - coverage) + ink[i] as f32 * coverage).round() as u8
    }))
}

pub(super) fn highlight_color(name: &str) -> Option<[u8; 3]> {
    match name {
        "yellow" => Some([255, 255, 0]),
        "green" => Some([0, 255, 0]),
        "cyan" => Some([0, 255, 255]),
        "magenta" => Some([255, 0, 255]),
        "red" => Some([255, 0, 0]),
        "blue" => Some([0, 0, 255]),
        "darkYellow" => Some([128, 128, 0]),
        "darkGreen" => Some([0, 128, 0]),
        "darkCyan" => Some([0, 128, 128]),
        "darkMagenta" => Some([128, 0, 128]),
        "darkRed" => Some([128, 0, 0]),
        "darkBlue" => Some([0, 0, 128]),
        "lightGray" => Some([192, 192, 192]),
        "darkGray" => Some([128, 128, 128]),
        "black" => Some([0, 0, 0]),
        "white" => Some([255, 255, 255]),
        _ => None,
    }
}

pub(super) fn wml_bool(parent: roxmltree::Node, name: &str) -> Option<bool> {
    wml(parent, name).map(|n| {
        n.attribute((WML_NS, "val"))
            .is_none_or(|v| v != "0" && v != "false")
    })
}

pub(super) fn wml<'a>(
    node: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(node, name, WML_NS)
}

pub(super) fn wml_attr<'a>(node: roxmltree::Node<'a, 'a>, child: &str) -> Option<&'a str> {
    wml(node, child).and_then(|n| n.attribute((WML_NS, "val")))
}

/// First math-namespace child element with the given local name.
pub(super) fn math_child<'a>(
    parent: roxmltree::Node<'a, 'a>,
    name: &str,
) -> Option<roxmltree::Node<'a, 'a>> {
    find_child(parent, name, MATH_NS)
}

/// A math property's `m:val`: `<pr><name m:val="…"/></pr>` under `node`.
pub(super) fn math_val<'a>(node: roxmltree::Node<'a, 'a>, pr: &str, name: &str) -> Option<&'a str> {
    math_child(math_child(node, pr)?, name)?.attribute((MATH_NS, "val"))
}

/// A math run's text (its `m:t` children).
pub(super) fn math_run_text(r: roxmltree::Node) -> String {
    find_children(r, "t", MATH_NS)
        .filter_map(|t| t.text())
        .collect()
}

/// A WordprocessingML twips attribute in points.
pub(super) fn twips_attr(node: roxmltree::Node, attr: &str) -> Option<f32> {
    f32_attr(node, (WML_NS, attr)).map(twips_to_pts)
}

pub(super) fn parse_one_border(node: roxmltree::Node) -> Option<ParagraphBorder> {
    let val = node.attribute((WML_NS, "val")).unwrap_or("none");
    if val == "none" || val == "nil" {
        return None;
    }
    let width_pt = node
        .attribute((WML_NS, "sz"))
        .and_then(|v| v.parse::<f32>().ok())
        .map(|v| v / 8.0)
        .unwrap_or(0.5);
    let space_pt = node
        .attribute((WML_NS, "space"))
        .and_then(|v| v.parse::<f32>().ok())
        .unwrap_or(0.0);
    let color = node
        .attribute((WML_NS, "color"))
        .and_then(parse_hex_color)
        .unwrap_or([0, 0, 0]);
    Some(ParagraphBorder {
        width_pt,
        space_pt,
        color,
    })
}

/// Returns `None` when the pBdr element is absent, `Some` when present
/// (even if all individual borders are none/nil).
pub(super) fn parse_paragraph_borders(ppr: roxmltree::Node) -> Option<ParagraphBorders> {
    let pbdr = wml(ppr, "pBdr")?;
    Some(ParagraphBorders {
        top: wml(pbdr, "top").and_then(parse_one_border),
        bottom: wml(pbdr, "bottom").and_then(parse_one_border),
        left: wml(pbdr, "left").and_then(parse_one_border),
        right: wml(pbdr, "right").and_then(parse_one_border),
        between: wml(pbdr, "between").and_then(parse_one_border),
    })
}

pub(super) fn parse_cell_border(parent: roxmltree::Node, name: &str) -> CellBorder {
    let Some(n) = wml(parent, name) else {
        return CellBorder::default();
    };
    let val = n.attribute((WML_NS, "val")).unwrap_or("none");
    if val == "nil" || val == "none" {
        return CellBorder {
            is_override: true,
            ..CellBorder::default()
        };
    }
    let width = n
        .attribute((WML_NS, "sz"))
        .and_then(|v| v.parse::<f32>().ok())
        .map(|v| v / 8.0)
        .unwrap_or(0.5);
    let color = n.attribute((WML_NS, "color")).and_then(parse_hex_color);
    let style = match val {
        "dotted" => BorderStyle::Dotted,
        "dashed" => BorderStyle::Dashed,
        "dashSmallGap" => BorderStyle::DashSmallGap,
        "dashDotStroked" | "dashDot" => BorderStyle::DashDot,
        "dashDotDot" => BorderStyle::DashDotDot,
        "double" => BorderStyle::Double,
        _ => BorderStyle::Single,
    };
    CellBorder::visible(color, width, style)
}

fn parse_cell_border_with_fallback(
    parent: roxmltree::Node,
    primary: &str,
    fallback: &str,
) -> CellBorder {
    let border = parse_cell_border(parent, primary);
    if border.present || border.is_override {
        border
    } else {
        parse_cell_border(parent, fallback)
    }
}

/// Parse left border with "start" fallback per OOXML bidi naming.
pub(super) fn parse_cell_border_left(parent: roxmltree::Node) -> CellBorder {
    parse_cell_border_with_fallback(parent, "left", "start")
}

/// Parse right border with "end" fallback per OOXML bidi naming.
pub(super) fn parse_cell_border_right(parent: roxmltree::Node) -> CellBorder {
    parse_cell_border_with_fallback(parent, "right", "end")
}

/// A framePr's attributes, kept so a paragraph can lay its own over its style's.
pub(super) type FrameAttrs = HashMap<String, String>;

pub(super) fn frame_attrs(fp: roxmltree::Node) -> FrameAttrs {
    fp.attributes()
        .filter(|a| a.namespace() == Some(WML_NS))
        .map(|a| (a.name().to_string(), a.value().to_string()))
        .collect()
}

/// The frame a paragraph sits in: its own framePr over its style's, attribute
/// by attribute (massachusetts' "Exec Office" lines leave hAnchor and hSpace to
/// their style and so share the title line's frame).
pub(super) fn parse_frame_props(
    ppr: Option<roxmltree::Node>,
    style_attrs: Option<&FrameAttrs>,
) -> Option<FrameProperties> {
    let direct = ppr.and_then(|p| wml(p, "framePr"));
    if direct.is_none() && style_attrs.is_none() {
        return None;
    }
    let mut attrs = style_attrs.cloned().unwrap_or_default();
    attrs.extend(direct.map(frame_attrs).unwrap_or_default());
    let attr = |name: &str| attrs.get(name).map(String::as_str);
    // An inline frame sits at its place in the flow and takes its height
    // there, like any paragraph (bulgarian_farmland's three header lines).
    // ponytail: every corpus one has no width or position; give a sized
    // inline frame its own path if one turns up.
    if attr("yAlign") == Some("inline") {
        return None;
    }
    let twips = |name| {
        attr(name)
            .and_then(|v| v.parse::<f32>().ok())
            .map_or(0.0, twips_to_pts)
    };
    let h_anchor = match attr("hAnchor").unwrap_or("text") {
        "margin" => HRelativeFrom::Margin,
        "page" => HRelativeFrom::Page,
        _ => HRelativeFrom::Column,
    };
    let h_position = if let Some(xa) = attr("xAlign") {
        match xa {
            "center" => HorizontalPosition::AlignCenter,
            "right" | "outside" => HorizontalPosition::AlignRight,
            _ => HorizontalPosition::AlignLeft,
        }
    } else {
        HorizontalPosition::Offset(twips("x"))
    };
    // Word probe: a frame without vAnchor sits w:y below the top margin, however
    // many paragraphs come before it.
    let v_anchor = match attr("vAnchor") {
        Some("page") => VRelativeFrom::Page,
        Some("text") => VRelativeFrom::Paragraph,
        _ => VRelativeFrom::Margin,
    };
    Some(FrameProperties {
        h_relative_from: h_anchor,
        h_position,
        v_relative_from: v_anchor,
        v_position: match attr("yAlign") {
            Some("top" | "inside") => VerticalPosition::AlignTop,
            Some("center") => VerticalPosition::AlignCenter,
            Some("bottom" | "outside") => VerticalPosition::AlignBottom,
            _ => VerticalPosition::Offset(twips("y")),
        },
        width: twips("w"),
        height: twips("h"),
        text_below: matches!(attr("wrap"), Some("none") | Some("notBeside")),
        h_space: twips("hSpace"),
        v_space: twips("vSpace"),
    })
}

/// A paragraph's tab stops: its style's, which its own `w:tabs` clear and
/// override, in order.
pub(in crate::docx) fn resolve_tab_stops(
    ppr: Option<roxmltree::Node>,
    para_style: Option<&ParagraphStyle>,
) -> Vec<TabStop> {
    let mut tab_stops = para_style.map(|s| s.tab_stops.clone()).unwrap_or_default();
    let (para_tabs, para_clears) = ppr.map(parse_tab_stops_with_clears).unwrap_or_default();
    if !para_tabs.is_empty() || !para_clears.is_empty() {
        merge_tab_stops(&mut tab_stops, &para_clears, para_tabs);
        tab_stops.sort_by(|a, b| a.position.total_cmp(&b.position));
    }
    tab_stops
}

/// Merge `incoming` tab stops into `dst`: clear positions remove matching stops
/// (0.5pt tolerance), then each incoming stop overrides one at the same position
/// or is appended. Caller is responsible for sorting.
pub(super) fn merge_tab_stops(dst: &mut Vec<TabStop>, clears: &[f32], incoming: Vec<TabStop>) {
    for &clear_pos in clears {
        dst.retain(|t| (t.position - clear_pos).abs() >= 0.5);
    }
    for ts in incoming {
        if let Some(existing) = dst
            .iter_mut()
            .find(|t| (t.position - ts.position).abs() < 0.5)
        {
            *existing = ts;
        } else {
            dst.push(ts);
        }
    }
}

pub(super) fn parse_tab_stops_with_clears(ppr: roxmltree::Node) -> (Vec<TabStop>, Vec<f32>) {
    let Some(tabs) = wml(ppr, "tabs") else {
        return (vec![], vec![]);
    };
    let mut stops = Vec::new();
    let mut clears = Vec::new();
    for n in tabs.children().filter(|n| n.has_tag_name((WML_NS, "tab"))) {
        let Some(pos) = twips_attr(n, "pos") else {
            continue;
        };
        let val = n.attribute((WML_NS, "val")).unwrap_or("left");
        if val == "clear" {
            clears.push(pos);
            continue;
        }
        let alignment = match val {
            "center" => TabAlignment::Center,
            "right" => TabAlignment::Right,
            "decimal" => TabAlignment::Decimal,
            _ => TabAlignment::Left,
        };
        let leader = n.attribute((WML_NS, "leader")).and_then(|l| match l {
            "dot" => Some('.'),
            "hyphen" => Some('-'),
            "underscore" => Some('_'),
            _ => None,
        });
        stops.push(TabStop {
            position: pos,
            alignment,
            leader,
        });
    }
    stops.sort_by(|a, b| a.position.total_cmp(&b.position));
    (stops, clears)
}

pub(super) fn resolve_theme_color_key(scheme_name: &str) -> &str {
    match scheme_name {
        "dk1" | "lt1" | "dk2" | "lt2" => scheme_name,
        "tx1" => "dk1",
        "tx2" => "dk2",
        "bg1" => "lt1",
        "bg2" => "lt2",
        other => other,
    }
}

/// HTML auto spacing (`w:beforeAutospacing` / `w:afterAutospacing`) on each
/// side: an inline value overrides the style's, so an inline "0" switches it off.
pub(in crate::docx) fn autospacing(
    ppr: Option<roxmltree::Node>,
    para_style: Option<&ParagraphStyle>,
    defaults: &StyleDefaults,
) -> (bool, bool) {
    let inline_spacing = ppr.and_then(|ppr| wml(ppr, "spacing"));
    let side = |attr: &str, style_val: Option<bool>, default: bool| {
        inline_spacing
            .and_then(|n| n.attribute((WML_NS, attr)).map(parse_on_off))
            .or(style_val)
            .unwrap_or(default)
    };
    (
        side(
            "beforeAutospacing",
            para_style.and_then(|s| s.space_before_autospacing),
            defaults.before_autospacing,
        ),
        side(
            "afterAutospacing",
            para_style.and_then(|s| s.space_after_autospacing),
            defaults.after_autospacing,
        ),
    )
}

/// Word's auto spacing: 14pt whatever the font, replacing w:before/w:after
/// (Normal (Web) paragraphs step 13.8 + 14 where their twips say 5pt).
const AUTO_SPACING: f32 = 14.0;

pub(in crate::docx) fn parse_paragraph_spacing(
    ppr: Option<roxmltree::Node>,
    para_style: Option<&ParagraphStyle>,
    defaults: &StyleDefaults,
) -> (Option<f32>, Option<f32>, Option<LineSpacing>) {
    let inline_spacing = ppr.and_then(|ppr| wml(ppr, "spacing"));
    let (before_auto, after_auto) = autospacing(ppr, para_style, defaults);
    let space_before = if before_auto {
        Some(AUTO_SPACING)
    } else {
        inline_spacing
            .and_then(|n| twips_attr(n, "before"))
            .or_else(|| para_style.and_then(|s| s.space_before))
    };
    let space_after = if after_auto {
        Some(AUTO_SPACING)
    } else {
        inline_spacing
            .and_then(|n| twips_attr(n, "after"))
            .or_else(|| para_style.and_then(|s| s.space_after))
    };

    let line_spacing = inline_spacing
        .and_then(parse_line_spacing)
        .or_else(|| para_style.and_then(|s| s.line_spacing));
    (space_before, space_after, line_spacing)
}

/// Convert a character-unit indent attribute (hundredths of character width) to points.
fn chars_to_pts(ind: roxmltree::Node, attr: &str, char_width: f32) -> Option<f32> {
    ind.attribute((WML_NS, attr))
        .and_then(|v| v.parse::<f32>().ok())
        .map(|hundredths| hundredths / 100.0 * char_width)
}

pub(super) fn extract_indents(
    ind: roxmltree::Node,
    char_width: Option<f32>,
) -> (Option<f32>, Option<f32>, Option<f32>, Option<f32>) {
    // Word always writes both twip and *Chars values consistently; when both
    // are present we prefer the twip value since it's Word's pre-resolved
    // measurement. Our char_width approximation (font_size/2) is correct for
    // Latin text but wrong for CJK text (where a character is a full em).
    let cw = char_width.unwrap_or(0.0);
    let has_cw = char_width.is_some();
    (
        twips_attr(ind, "start")
            .or_else(|| twips_attr(ind, "left"))
            .or_else(|| has_cw.then(|| chars_to_pts(ind, "leftChars", cw)).flatten()),
        twips_attr(ind, "end")
            .or_else(|| twips_attr(ind, "right"))
            .or_else(|| {
                has_cw
                    .then(|| chars_to_pts(ind, "rightChars", cw))
                    .flatten()
            }),
        twips_attr(ind, "hanging").or_else(|| {
            has_cw
                .then(|| chars_to_pts(ind, "hangingChars", cw))
                .flatten()
        }),
        twips_attr(ind, "firstLine").or_else(|| {
            has_cw
                .then(|| chars_to_pts(ind, "firstLineChars", cw))
                .flatten()
        }),
    )
}

pub(super) fn collect_block_nodes<'a>(
    parent: roxmltree::Node<'a, 'a>,
) -> Vec<roxmltree::Node<'a, 'a>> {
    let mut nodes = Vec::new();
    for child in parent.children() {
        if child.has_tag_name((WML_NS, "sdt")) {
            if let Some(content) = wml(child, "sdtContent") {
                nodes.extend(collect_block_nodes(content));
            }
        } else if child.has_tag_name((WML_NS, "customXml")) {
            // w:customXml is a transparent wrapper (block/row/cell): its children
            // ARE the content. Same descent drives tbl→tr and tr→tc unwrapping.
            nodes.extend(collect_block_nodes(child));
        } else if child.has_tag_name((MC_NS_TOP, "AlternateContent")) {
            // mc:AlternateContent wraps block-level content in mc:Choice/mc:Fallback.
            // Use mc:Fallback for compatibility (it avoids newer namespace requirements).
            let fallback = child
                .children()
                .find(|n| n.has_tag_name((MC_NS_TOP, "Fallback")));
            if let Some(fb) = fallback {
                nodes.extend(collect_block_nodes(fb));
            }
        } else {
            nodes.push(child);
        }
    }
    nodes
}

pub(super) fn read_zip_text<R: Read + std::io::Seek>(
    zip: &mut zip::ZipArchive<R>,
    name: &str,
) -> Option<String> {
    let mut content = String::new();
    zip.by_name(name).ok()?.read_to_string(&mut content).ok()?;
    Some(strict_to_transitional(content))
}

/// Strict OOXML (ISO/IEC 29500 Strict) names its namespaces and relationship
/// types `http://purl.oclc.org/ooxml/<area>/<name>` where Transitional uses
/// `http://schemas.openxmlformats.org/<area>/2006/<name>`. Rewriting them on
/// load lets one parser read both; the package namespaces are shared.
fn strict_to_transitional(xml: String) -> String {
    if !xml.contains("http://purl.oclc.org/ooxml/") {
        return xml;
    }
    ["wordprocessingml", "drawingml", "officeDocument"]
        .iter()
        .fold(xml, |acc, area| {
            acc.replace(
                &format!("http://purl.oclc.org/ooxml/{area}/"),
                &format!("http://schemas.openxmlformats.org/{area}/2006/"),
            )
        })
}

pub(super) fn read_zip_bytes<R: Read + std::io::Seek>(
    zip: &mut zip::ZipArchive<R>,
    name: &str,
) -> Option<Vec<u8>> {
    let mut data = Vec::new();
    zip.by_name(name).ok()?.read_to_end(&mut data).ok()?;
    Some(data)
}

/// Zip path of a relationship target: absolute (`/word/media/x.png`) as is,
/// otherwise relative to `word/`.
pub(super) fn part_path(target: &str) -> String {
    match target.strip_prefix('/') {
        Some(absolute) => absolute.to_string(),
        None => format!("word/{target}"),
    }
}

mod relationships {
    use std::collections::HashMap;
    use std::io::Read;

    use super::read_zip_text;

    fn parse_rels_xml(xml_content: &str) -> HashMap<String, String> {
        let Ok(xml) = roxmltree::Document::parse(xml_content) else {
            return HashMap::new();
        };
        xml.root_element()
            .children()
            .filter(|n| n.tag_name().name() == "Relationship")
            .filter_map(|n| {
                Some((
                    n.attribute("Id")?.to_string(),
                    n.attribute("Target")?.to_string(),
                ))
            })
            .collect()
    }

    pub(in crate::docx) fn parse_relationships<R: Read + std::io::Seek>(
        zip: &mut zip::ZipArchive<R>,
    ) -> HashMap<String, String> {
        let Some(xml_content) = read_zip_text(zip, "word/_rels/document.xml.rels") else {
            return HashMap::new();
        };
        parse_rels_xml(&xml_content)
    }

    pub(in crate::docx) fn parse_part_relationships<R: Read + std::io::Seek>(
        zip: &mut zip::ZipArchive<R>,
        part_path: &str,
    ) -> HashMap<String, String> {
        let (dir, file) = match part_path.rsplit_once('/') {
            Some((d, f)) => (d, f),
            None => ("", part_path),
        };
        let rels_path = if dir.is_empty() {
            format!("_rels/{}.rels", file)
        } else {
            format!("{}/_rels/{}.rels", dir, file)
        };
        let Some(xml_content) = read_zip_text(zip, &rels_path) else {
            return HashMap::new();
        };
        parse_rels_xml(&xml_content)
    }
}

pub fn parse(path: &std::path::Path) -> Result<Document, Error> {
    let file = std::fs::File::open(path).map_err(|e| match e.kind() {
        std::io::ErrorKind::NotFound | std::io::ErrorKind::PermissionDenied => Error::Io(
            std::io::Error::new(e.kind(), format!("{}: {}", e, path.display())),
        ),
        _ => Error::Io(e),
    })?;

    let mut zip = zip::ZipArchive::new(file)
        .map_err(|_| Error::InvalidDocx("file is not a ZIP archive".into()))?;

    parse_zip(&mut zip)
}

pub fn parse_bytes(bytes: &[u8]) -> Result<Document, Error> {
    let cursor = std::io::Cursor::new(bytes);
    let mut zip = zip::ZipArchive::new(cursor)
        .map_err(|_| Error::InvalidDocx("data is not a valid ZIP/DOCX archive".into()))?;

    parse_zip(&mut zip)
}

fn parse_core_props<R: Read + std::io::Seek>(
    zip: &mut zip::ZipArchive<R>,
) -> (
    Option<String>,
    Option<String>,
    Option<String>,
    Option<String>,
) {
    let Some(xml_content) = read_zip_text(zip, "docProps/core.xml") else {
        return (None, None, None, None);
    };
    let Ok(xml) = roxmltree::Document::parse(&xml_content) else {
        return (None, None, None, None);
    };

    const DC_NS: &str = "http://purl.org/dc/elements/1.1/";
    const CP_NS: &str = "http://schemas.openxmlformats.org/package/2006/metadata/core-properties";
    let root = xml.root_element();
    let prop = |ns, name| {
        find_children(root, name, ns)
            .filter_map(|n| n.text())
            .last()
            .map(str::to_string)
    };
    (
        prop(DC_NS, "title"),
        prop(DC_NS, "creator"),
        prop(DC_NS, "subject"),
        prop(CP_NS, "keywords"),
    )
}

fn parse_zip<R: Read + std::io::Seek>(zip: &mut zip::ZipArchive<R>) -> Result<Document, Error> {
    let settings = parse_settings(zip);
    let theme = parse_theme(
        zip,
        settings.east_asia_lang.as_deref(),
        settings.bidi_lang.as_deref(),
    );
    let styles = parse_styles(zip, &theme, settings.styles_from_normal_template);
    let numbering = parse_numbering(zip);
    let rels = parse_relationships(zip);
    let ft = parse_font_table(zip);
    let (embedded_fonts, font_table) = (ft.embedded_fonts, ft.font_table);
    let (footnotes, footnote_separator) = parse_footnotes(zip, &styles, &theme, &numbering);
    let endnotes = parse_endnotes(zip, &styles, &theme, &numbering);
    let comments = comments::parse_comments(zip);
    let (title, author, subject, keywords) = parse_core_props(zip);

    let mut xml_content = String::new();
    zip.by_name("word/document.xml")
        .map_err(|_| Error::InvalidDocx("missing word/document.xml (is this a DOCX file?)".into()))?
        .read_to_string(&mut xml_content)?;
    let xml_content = strict_to_transitional(xml_content);

    let xml = roxmltree::Document::parse(&xml_content)?;
    let root = xml.root_element();

    let body = wml(root, "body").ok_or_else(|| Error::InvalidDocx("Missing w:body".into()))?;

    let default_line_pitch = styles.defaults.font_size * 1.2;

    let mut ctx = ParseContext {
        styles: &styles,
        theme: &theme,
        rels: &rels,
        zip,
        numbering: &numbering,
    };

    let mut sections: Vec<Section> = Vec::new();
    let mut blocks = Vec::new();
    let mut lists = numbering::ListCounters::default();
    // numId of the previous body block when it was a list paragraph.
    let mut prev_list_num_id: Option<String> = None;

    for node in collect_block_nodes(body) {
        if node.tag_name().namespace() != Some(WML_NS) {
            continue;
        }
        match node.tag_name().name() {
            "tbl" => {
                let table = parse_table_node(node, &mut ctx, &mut lists);
                blocks.push(Block::Table(table));
                prev_list_num_id = None;
            }
            "p" => {
                let ppr = wml(node, "pPr");
                let para_style_id = ppr
                    .and_then(|ppr| wml_attr(ppr, "pStyle"))
                    .unwrap_or(&styles.default_paragraph_style_id);
                let para_style = styles.paragraph_styles.get(para_style_id);

                let opts = paragraph::ParagraphOptions {
                    resolve_bookmarks: true,
                    resolve_outline_level: true,
                    resolve_drawings: true,
                    collect_extra_textboxes: true,
                    style_num_id: para_style.and_then(|s| s.num_id.clone()),
                    style_num_ilvl: para_style.and_then(|s| s.num_ilvl),
                };
                let mut para = paragraph::build_paragraph(node, &mut ctx, &mut lists, &opts);

                // HTML auto spacing drops between items of one list:
                // russian_university's auto-spaced list items step a plain
                // line apart.
                let num_id = ppr
                    .and_then(|ppr| wml(ppr, "numPr"))
                    .and_then(|np| wml_attr(np, "numId"))
                    .map(str::to_string)
                    .or_else(|| para_style.and_then(|s| s.num_id.clone()))
                    .filter(|id| id != "0");
                if num_id.is_some() && num_id == prev_list_num_id {
                    if para.space_before_auto {
                        para.space_before = 0.0;
                    }
                    if let Some(Block::Paragraph(prev)) = blocks.last_mut()
                        && prev.space_after_auto
                    {
                        prev.space_after = 0.0;
                    }
                }
                prev_list_num_id = num_id;

                let continuation = paragraph::split_at_page_break(&mut para);
                blocks.push(Block::Paragraph(para));
                blocks.extend(continuation.map(Block::Paragraph));

                // Mid-document section break: sectPr inside pPr ends the current section
                if let Some(sect_node) = ppr.and_then(|ppr| wml(ppr, "sectPr")) {
                    if let Some(Block::Paragraph(last_para)) = blocks.last_mut() {
                        last_para.is_section_break = true;
                        // A page break ending the section's last paragraph is dropped:
                        // the section break alone decides (online export probes,
                        // 2026-10-03: no new page before a continuous section, one
                        // before a next-page section; stem_partnerships' cover).
                        last_para.page_break_after = false;
                    }
                    let props = parse_section_properties(
                        sect_node,
                        &mut ctx,
                        default_line_pitch,
                        settings.gutter_at_top,
                    );
                    sections.push(Section {
                        properties: props,
                        blocks: std::mem::take(&mut blocks),
                    });
                }
            }
            "altChunk" => {
                if let Some(id) = node.attribute((REL_NS, "id")) {
                    blocks.extend(alt_chunk::parse_alt_chunk(id, ctx.rels, ctx.zip));
                    prev_list_num_id = None;
                }
            }
            _ => {}
        }
    }

    // Word always lays out an implicit final paragraph mark after a
    // document-ending table; when it doesn't fit below the table it spills
    // onto a fresh (blank) page. Model it as a real empty paragraph.
    if matches!(blocks.last(), Some(Block::Table(_))) {
        blocks.push(Block::Paragraph(crate::model::Paragraph::default()));
    }

    // Final section: body-level sectPr
    let final_props = if let Some(sect_node) = wml(body, "sectPr") {
        parse_section_properties(
            sect_node,
            &mut ctx,
            default_line_pitch,
            settings.gutter_at_top,
        )
    } else {
        SectionProperties {
            page_width: 612.0,
            page_height: 792.0,
            margin_top: 72.0,
            margin_bottom: 72.0,
            margin_top_fixed: false,
            margin_bottom_fixed: false,
            margin_left: 72.0,
            margin_right: 72.0,
            header_margin: 36.0,
            footer_margin: 36.0,
            header_default: None,
            header_first: None,
            header_even: None,
            footer_default: None,
            footer_first: None,
            footer_even: None,
            different_first_page: false,
            line_pitch: default_line_pitch,
            grid_type: DocGridType::Default,
            break_type: SectionBreakType::NextPage,
            columns: None,
            page_num_start: None,
            page_num_format: None,
            page_borders: None,
            vertical_align: crate::model::PageVerticalAlign::Top,
            line_numbering: None,
            footnote_num_fmt: None,
            endnote_num_fmt: None,
        }
    };
    sections.push(Section {
        properties: final_props,
        blocks,
    });
    // HTML auto spacing never opens the document, from a w:p or an altChunk
    // alike: case42's first Normal (Web) paragraph sits at the top margin.
    if let Some(Block::Paragraph(first)) = sections[0].blocks.first_mut()
        && first.space_before_auto
    {
        first.space_before = 0.0;
    }
    // hideMark never hides the document's first paragraph mark: a table
    // opening the body keeps a line for an empty hideMark first cell, the
    // same row collapses after a page break or a paragraph (Word probes).
    // Nested layout tables put that mark in the innermost first cell.
    let mut first = sections[0].blocks.first_mut();
    while let Some(Block::Table(table)) = first {
        let Some(cell) = table.rows.first_mut().and_then(|r| r.cells.first_mut()) else {
            break;
        };
        if cell.content.len() == 1 {
            cell.hide_mark = false;
        }
        first = cell.content.first_mut();
    }
    // A continuous break can't change the paper mid-page: Word starts a new
    // page when the size or orientation changes (transition_to_work's
    // landscape Annexure B1, whose page would otherwise take the portrait
    // text above it off the top).
    for i in 1..sections.len() {
        let prev = &sections[i - 1].properties;
        let size = (prev.page_width, prev.page_height);
        let sp = &mut sections[i].properties;
        if sp.break_type == SectionBreakType::Continuous && (sp.page_width, sp.page_height) != size
        {
            sp.break_type = SectionBreakType::NextPage;
        }
    }

    // Word's PDF export scales the body content via a wrapping `cm` operator
    // when comments are present, so glyphs render at ~76% and a column opens
    // up on the right for the comment pane. We apply the same scaling at
    // content-stream assembly time; the body keeps its natural layout here.

    Ok(Document {
        sections,
        line_spacing: styles.defaults.line_spacing,
        embedded_fonts,
        footnotes,
        footnote_separator,
        endnotes,
        comments,
        font_table,
        even_and_odd_headers: settings.even_and_odd_headers,
        mirror_margins: settings.mirror_margins,
        default_tab_stop: settings.default_tab_stop,
        style_id_to_name: styles.style_id_to_name,
        theme_minor_font: theme.minor.clone(),
        title,
        author,
        subject,
        keywords,
        default_lang: styles.defaults.lang.clone().or(settings.default_lang),
        compress_punctuation: settings.compress_punctuation,
        compat_mode: settings.compat_mode,
        do_not_expand_shift_return: settings.do_not_expand_shift_return,
        adjust_line_height_in_table: settings.adjust_line_height_in_table,
    })
}

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

    #[test]
    fn strict_namespaces_read_as_transitional() {
        let strict = r#"<w:document xmlns:w="http://purl.oclc.org/ooxml/wordprocessingml/main" xmlns:r="http://purl.oclc.org/ooxml/officeDocument/relationships"><w:body/></w:document>"#;
        let xml = strict_to_transitional(strict.to_string());
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert!(wml(doc.root_element(), "body").is_some());
        assert!(
            xml.contains("http://schemas.openxmlformats.org/officeDocument/2006/relationships")
        );
    }

    #[test]
    fn frame_y_align_overrides_y_and_inline_stays_in_flow() {
        let parse = |fp: &str| {
            let xml = format!(r#"<w:pPr xmlns:w="{WML_NS}">{fp}</w:pPr>"#);
            let doc = roxmltree::Document::parse(&xml).unwrap();
            parse_frame_props(Some(doc.root_element()), None)
        };
        let bottom =
            parse(r#"<w:framePr w:w="2659" w:hAnchor="page" w:x="8971" w:yAlign="bottom"/>"#)
                .unwrap();
        assert_eq!(bottom.v_position, VerticalPosition::AlignBottom);
        assert_eq!(bottom.v_relative_from, VRelativeFrom::Margin);
        let y = parse(r#"<w:framePr w:vAnchor="page" w:y="3222"/>"#).unwrap();
        assert_eq!(y.v_position, VerticalPosition::Offset(161.1));
        assert!(parse(r#"<w:framePr w:yAlign="inline"/>"#).is_none());
    }

    // --- Pure math / conversion ---

    #[test]
    fn test_twips_to_pts() {
        assert_eq!(twips_to_pts(0.0), 0.0);
        assert_eq!(twips_to_pts(20.0), 1.0);
        assert_eq!(twips_to_pts(360.0), 18.0);
        assert_eq!(twips_to_pts(1440.0), 72.0); // 1 inch
    }

    #[test]
    fn test_emu_to_pts() {
        assert_eq!(emu_to_pts(0.0), 0.0);
        assert_eq!(emu_to_pts(12700.0), 1.0);
        assert_eq!(emu_to_pts(914400.0), 72.0); // 1 inch
    }

    // --- Color parsing ---

    #[test]
    fn test_parse_hex_color() {
        assert_eq!(parse_hex_color("FF0000"), Some([255, 0, 0]));
        assert_eq!(parse_hex_color("00FF00"), Some([0, 255, 0]));
        assert_eq!(parse_hex_color("0000FF"), Some([0, 0, 255]));
        assert_eq!(parse_hex_color("4472C4"), Some([68, 114, 196]));
        assert_eq!(parse_hex_color("auto"), None);
        assert_eq!(parse_hex_color("red"), None); // wrong length
        assert_eq!(parse_hex_color(""), None);
        assert_eq!(parse_hex_color("ZZZZZZ"), None); // invalid hex
    }

    #[test]
    fn test_parse_text_color() {
        assert_eq!(parse_text_color("auto"), Some([0, 0, 0])); // auto → black
        assert_eq!(parse_text_color("FF0000"), Some([255, 0, 0]));
        assert_eq!(parse_text_color("invalid"), None);
    }

    #[test]
    fn test_parse_run_shd() {
        let ns = WML_NS;

        // No w:shd child → None (inherit)
        let xml = format!(r#"<w:rPr xmlns:w="{ns}"><w:b/></w:rPr>"#);
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), None);

        // val="clear" fill="FFFF00" → Some(yellow)
        let xml = format!(
            r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="clear" w:color="auto" w:fill="FFFF00"/></w:rPr>"#
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), Some([0xFF, 0xFF, 0x00]));

        // val="nil" → None (not an override: inherit from style)
        let xml = format!(r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="nil"/></w:rPr>"#);
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), None);

        // fill="auto" → None (inherit)
        let xml = format!(r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="clear" w:fill="auto"/></w:rPr>"#);
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), None);

        // Missing fill → None (inherit)
        let xml = format!(r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="clear"/></w:rPr>"#);
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), None);

        // pct25 of auto (black) over CCCCCC
        let xml =
            format!(r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="pct25" w:fill="CCCCCC"/></w:rPr>"#);
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), Some([153, 153, 153]));

        // solid paints the pattern color over an auto fill
        let xml = format!(
            r#"<w:rPr xmlns:w="{ns}"><w:shd w:val="solid" w:color="CC99FF" w:fill="auto"/></w:rPr>"#
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        assert_eq!(parse_run_shd(doc.root_element()), Some([0xCC, 0x99, 0xFF]));
    }

    #[test]
    fn test_highlight_color() {
        assert_eq!(highlight_color("yellow"), Some([255, 255, 0]));
        assert_eq!(highlight_color("red"), Some([255, 0, 0]));
        assert_eq!(highlight_color("blue"), Some([0, 0, 255]));
        assert_eq!(highlight_color("darkGreen"), Some([0, 128, 0]));
        assert_eq!(highlight_color("lightGray"), Some([192, 192, 192]));
        assert_eq!(highlight_color("black"), Some([0, 0, 0]));
        assert_eq!(highlight_color("white"), Some([255, 255, 255]));
        assert_eq!(highlight_color("unknown"), None);
    }

    // --- East Asian character detection ---

    #[test]
    fn test_is_east_asian_char() {
        assert!(is_east_asian_char('漢')); // CJK Unified Ideograph
        assert!(is_east_asian_char('あ')); // Hiragana
        assert!(is_east_asian_char('ア')); // Katakana
        assert!(is_east_asian_char('한')); // Hangul
        assert!(is_east_asian_char('、')); // CJK Symbols
        assert!(is_east_asian_char('\u{FF01}')); // Fullwidth !
        assert!(!is_east_asian_char('A'));
        assert!(!is_east_asian_char('1'));
        assert!(!is_east_asian_char(' '));
        assert!(!is_east_asian_char('é'));
    }

    // --- XML-based utility tests ---

    #[test]
    fn test_wml_bool() {
        let xml = format!(
            r#"<w:pPr xmlns:w="{}">
                <w:b/>
                <w:i w:val="0"/>
                <w:caps w:val="true"/>
                <w:vanish w:val="false"/>
            </w:pPr>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        // Present with no val attribute → true
        assert_eq!(wml_bool(node, "b"), Some(true));
        // val="0" → false
        assert_eq!(wml_bool(node, "i"), Some(false));
        // val="true" → true
        assert_eq!(wml_bool(node, "caps"), Some(true));
        // val="false" → false
        assert_eq!(wml_bool(node, "vanish"), Some(false));
        // Missing element → None
        assert_eq!(wml_bool(node, "strike"), None);
    }

    #[test]
    fn test_wml_attr() {
        let xml = format!(
            r#"<w:pPr xmlns:w="{}">
                <w:jc w:val="center"/>
                <w:sz w:val="24"/>
            </w:pPr>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        assert_eq!(wml_attr(node, "jc"), Some("center"));
        assert_eq!(wml_attr(node, "sz"), Some("24"));
        assert_eq!(wml_attr(node, "missing"), None);
    }

    #[test]
    fn test_twips_attr() {
        let xml = format!(
            r#"<w:ind xmlns:w="{}" w:left="720" w:right="360"/>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        assert_eq!(twips_attr(node, "left"), Some(36.0)); // 720/20=36pt
        assert_eq!(twips_attr(node, "right"), Some(18.0)); // 360/20=18pt
        assert_eq!(twips_attr(node, "hanging"), None);
    }

    // --- Tab stops ---

    #[test]
    fn test_parse_tab_stops() {
        let xml = format!(
            r#"<w:pPr xmlns:w="{}">
                <w:tabs>
                    <w:tab w:val="center" w:pos="4320"/>
                    <w:tab w:val="right" w:pos="8640" w:leader="dot"/>
                    <w:tab w:val="left" w:pos="1440"/>
                </w:tabs>
            </w:pPr>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        let stops = parse_tab_stops_with_clears(node).0;
        assert_eq!(stops.len(), 3);
        // Sorted by position
        assert_eq!(stops[0].position, 72.0); // 1440/20
        assert_eq!(stops[0].alignment, TabAlignment::Left);
        assert_eq!(stops[0].leader, None);
        assert_eq!(stops[1].position, 216.0); // 4320/20
        assert_eq!(stops[1].alignment, TabAlignment::Center);
        assert_eq!(stops[2].position, 432.0); // 8640/20
        assert_eq!(stops[2].alignment, TabAlignment::Right);
        assert_eq!(stops[2].leader, Some('.'));
    }

    #[test]
    fn test_parse_tab_stops_with_clears() {
        let xml = format!(
            r#"<w:pPr xmlns:w="{}">
                <w:tabs>
                    <w:tab w:val="clear" w:pos="720"/>
                    <w:tab w:val="right" w:pos="9360"/>
                </w:tabs>
            </w:pPr>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        let (stops, clears) = parse_tab_stops_with_clears(node);
        assert_eq!(stops.len(), 1);
        assert_eq!(stops[0].alignment, TabAlignment::Right);
        assert_eq!(clears.len(), 1);
        assert_eq!(clears[0], 36.0); // 720/20
    }

    // --- Indents ---

    #[test]
    fn test_extract_indents() {
        let xml = format!(
            r#"<w:ind xmlns:w="{}" w:left="720" w:right="360" w:hanging="360" w:firstLine="0"/>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        let (left, right, hanging, first_line) = extract_indents(node, None);
        assert_eq!(left, Some(36.0)); // 720/20
        assert_eq!(right, Some(18.0)); // 360/20
        assert_eq!(hanging, Some(18.0)); // 360/20
        assert_eq!(first_line, Some(0.0));
    }

    #[test]
    fn test_extract_indents_start_end() {
        // w:start/w:end are the modern equivalents of w:left/w:right
        let xml = format!(
            r#"<w:ind xmlns:w="{}" w:start="1440" w:end="720"/>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        let (left, right, hanging, first_line) = extract_indents(node, None);
        assert_eq!(left, Some(72.0)); // 1440/20
        assert_eq!(right, Some(36.0)); // 720/20
        assert_eq!(hanging, None);
        assert_eq!(first_line, None);
    }

    #[test]
    fn test_extract_indents_left_chars() {
        // When both twips and *Chars are present, twips takes priority
        // (Word's pre-resolved value is authoritative).
        let xml = format!(
            r#"<w:ind xmlns:w="{}" w:leftChars="200" w:left="480"/>"#,
            WML_NS
        );
        let doc = roxmltree::Document::parse(&xml).unwrap();
        let node = doc.root_element();
        let (left, _right, _hanging, _first_line) = extract_indents(node, Some(5.5));
        assert_eq!(left, Some(24.0)); // w:left="480" twips → 24pt
        // When only *Chars is present, use it with char_width approximation
        let xml2 = format!(r#"<w:ind xmlns:w="{}" w:leftChars="200"/>"#, WML_NS);
        let doc2 = roxmltree::Document::parse(&xml2).unwrap();
        let node2 = doc2.root_element();
        let (left2, _, _, _) = extract_indents(node2, Some(5.5));
        assert_eq!(left2, Some(11.0)); // 200/100 * 5.5 = 11.0pt
    }

    // --- Theme color key resolution ---

    #[test]
    fn test_resolve_theme_color_key() {
        assert_eq!(resolve_theme_color_key("dk1"), "dk1");
        assert_eq!(resolve_theme_color_key("tx1"), "dk1");
        assert_eq!(resolve_theme_color_key("tx2"), "dk2");
        assert_eq!(resolve_theme_color_key("accent1"), "accent1");
        assert_eq!(resolve_theme_color_key("accent6"), "accent6");
        assert_eq!(resolve_theme_color_key("bg1"), "lt1");
        assert_eq!(resolve_theme_color_key("bg2"), "lt2");
    }
}