rwml 0.1.0

Native Rust toolkit for Microsoft Word — read, write, edit, and render legacy .doc (Word 97-2003, [MS-DOC]) and modern .docx (OOXML): one document model, package-preserving edits, field evaluation, Markdown/HTML export, PDF preview
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
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
//! Modern `.docx` (OOXML WordprocessingML) reading — the second Word backend.
//!
//! A `.docx` is a ZIP of XML parts: `word/document.xml` (the body — paragraphs,
//! runs, tables), `word/styles.xml` (style → heading level / name),
//! `word/numbering.xml` (list levels → ordered/bullet),
//! `word/_rels/document.xml.rels` (relationship id → hyperlink target / media
//! path), and `word/media/*` (image bytes).
//!
//! Everything is parsed into the **same** [`crate::model::DocModel`] the legacy
//! `.doc` path produces, so [`crate::Document::to_markdown`] /
//! [`crate::Document::to_html`] / [`crate::Document::images`] are shared and
//! `.doc` and `.docx` render identically. This is a *unification* play (one Word
//! crate, no JVM, no external `.docx` dependency) — see the README on how it
//! relates to the mature `docx-rs` crate.

use std::collections::{BTreeMap, HashMap, HashSet};
use std::io::Read;

use quick_xml::events::{BytesStart, Event};
use quick_xml::Reader;

use crate::annotation::{
    document_property_key, Comment, Field, FieldKind, FloatingShape, HeaderFooter,
    HeaderFooterKind, Note, NoteKind, Revision, ShapeDistance, ShapeEffectExtent, ShapeExtent,
    ShapePoint, ShapePosition, ShapeWrapping, TextAnchor, TextBox,
};
use crate::assemble;
use crate::error::{Error, Result};
use crate::model::{Block, Color, CustomXmlItem, DocMeta, DocModel, Image};
use crate::text;
use crate::CoreProperties;

pub(crate) use self::xml_text::skip_subtree as skip_xml_subtree;
use self::xml_text::{inline_marker_text, read_i64_text, read_text, skip_subtree};

mod body;
mod comments;
pub(crate) mod fields;
mod numbering;
mod revisions;
mod styles;
mod xml_text;

pub(crate) fn parse_fields(xml: &str) -> Vec<Field> {
    let core_properties = CoreProperties::default();
    let custom_properties = HashMap::new();
    let document_variables = HashMap::new();
    let extended_properties = HashMap::new();
    fields::parse(
        xml,
        &styles::Styles::default(),
        &[],
        &numbering::Numbering::default(),
        fields::FieldDocumentProperties {
            core: &core_properties,
            custom: &custom_properties,
            variables: &document_variables,
            extended: &extended_properties,
            file_size_bytes: None,
        },
        false,
    )
}

pub(crate) fn header_footer_ref_ids(xml: &str) -> HashSet<String> {
    let mut ids = HashSet::new();
    for refs in body::scan_hf_ref_sections(xml) {
        ids.extend(refs.headers.into_iter().map(|r| r.rel_id));
        ids.extend(refs.footers.into_iter().map(|r| r.rel_id));
    }
    ids
}

pub(crate) fn supports_display_field_syntax(instruction: &str) -> bool {
    fields::supports_display_field_syntax(instruction)
}

pub(crate) fn supports_action_field_syntax(instruction: &str) -> bool {
    fields::supports_action_field_syntax(instruction)
}

pub(crate) fn supports_reference_index_marker_syntax(instruction: &str) -> bool {
    fields::supports_reference_index_marker_syntax(instruction)
}

pub(crate) fn supports_toc_entry_field_syntax(instruction: &str) -> bool {
    fields::supports_toc_entry_field_syntax(instruction)
}

pub(crate) fn supports_hyperlink_field_syntax(instruction: &str) -> bool {
    body::hyperlink_instr_url(instruction).is_some()
}

pub(crate) fn supports_filename_field_syntax(instruction: &str) -> bool {
    fields::supports_filename_field_syntax(instruction)
}

pub(crate) fn supports_page_field_syntax(instruction: &str) -> bool {
    fields::supports_page_field_syntax(instruction)
}

pub(crate) fn page_field_unsupported_display_formats(xml: &str) -> Vec<bool> {
    let ref_targets = fields::ref_targets(xml);
    fields::page_ref_context(xml, &ref_targets).page_field_unsupported_display_formats()
}

pub(crate) fn supports_section_field_syntax(instruction: &str) -> bool {
    fields::is_section_field_instruction(instruction)
}

pub(crate) fn supports_numbering_field_syntax(instruction: &str) -> bool {
    fields::supports_numbering_field_syntax(instruction)
}

pub(crate) fn supports_compare_field_syntax(instruction: &str) -> bool {
    fields::supports_compare_field_syntax(instruction)
}

pub(crate) fn supports_if_field_syntax(instruction: &str) -> bool {
    fields::supports_if_field_syntax(instruction)
}

pub(crate) fn supports_quote_field_syntax(instruction: &str) -> bool {
    fields::supports_quote_field_syntax(instruction)
}

pub(crate) fn supports_prompt_field_syntax(instruction: &str) -> bool {
    fields::supports_prompt_field_syntax(instruction)
}

pub(crate) fn supports_set_field_syntax(instruction: &str) -> bool {
    fields::supports_set_field_syntax(instruction)
}

pub(crate) fn update_field_bookmarks_from_instruction(
    instruction: &str,
    field_bookmarks: &mut HashMap<String, String>,
) -> bool {
    fields::computed_set_result(instruction, field_bookmarks)
        .or_else(|| fields::computed_ask_result(instruction, field_bookmarks))
        .is_some()
}

pub(crate) fn supports_merge_control_field_syntax(instruction: &str) -> bool {
    fields::supports_merge_control_field_syntax(instruction)
}

pub(crate) fn supports_document_info_field_syntax(instruction: &str) -> bool {
    fields::supports_document_info_field_syntax(instruction)
}

pub(crate) fn supports_revision_number_field_syntax(instruction: &str) -> bool {
    fields::supports_revision_number_field_syntax(instruction)
}

pub(crate) fn supports_formula_field_syntax(instruction: &str) -> bool {
    fields::supports_formula_field_syntax(instruction)
}

pub(crate) fn supports_sequence_field_syntax(instruction: &str) -> bool {
    fields::supports_sequence_field_syntax(instruction)
}

pub(crate) fn supports_style_ref_field_syntax(instruction: &str) -> bool {
    fields::supports_style_ref_field_syntax(instruction)
}

pub(crate) fn note_ref_target_names(xml: &str) -> HashSet<String> {
    fields::note_ref_target_names(xml)
}

/// Relationship table: `Id` → `(Target, is_external)`.
type Rels = HashMap<String, (String, bool)>;

/// Detect the ZIP / OOXML magic (`PK\x03\x04`).
pub(crate) fn is_zip(bytes: &[u8]) -> bool {
    bytes.starts_with(b"PK\x03\x04")
}

/// A parsed `.docx`: the rich model (built eagerly — XML parsing is cheap, so
/// there is no lazy split like the `.doc` path) plus the derived flat text.
pub(crate) struct DocxState {
    /// The **body-only** model (no footnote/endnote blocks). `Document::model()`
    /// re-appends `notes` for the read view; the lossy model is read/render only.
    pub model: DocModel,
    /// Footnote/endnote blocks, kept separate from `model.blocks` (their `.docx`
    /// parts are preserved on save, never inlined into the body).
    pub notes: Vec<Block>,
    /// Footnote/endnote side-table records parsed from `word/footnotes.xml` and
    /// `word/endnotes.xml`.
    pub note_records: Vec<Note>,
    /// Text-box side-table records parsed from body/note/header/footer
    /// `w:txbxContent` shapes.
    pub text_boxes: Vec<TextBox>,
    /// Floating shape geometry parsed from body/note/header/footer `wp:anchor` drawing markup.
    pub floating_shapes: Vec<FloatingShape>,
    /// Exact running header/footer records parsed from referenced `.docx` parts.
    pub header_footers: Vec<HeaderFooter>,
    /// Core metadata parsed from `docProps/core.xml`.
    pub core_properties: CoreProperties,
    /// Full flat text: body, then footnotes/endnotes, then headers and footers.
    pub text: String,
    /// Just the main body (excludes notes and headers/footers).
    pub main_text: String,
    /// The retained OPC package (every part verbatim) — the source of truth for
    /// package-preserving `save()`. Element-tree edits mutate its `document.xml` in
    /// place; the lossy `model` above is the read/render view.
    pub package: crate::opc::Package,
    /// Comments parsed from `word/comments.xml` and optional commentsExtended links.
    pub comments: Vec<Comment>,
    /// Fields parsed from body/note/header/footer content.
    pub fields: Vec<Field>,
    /// Tracked revisions parsed from body/note/header/footer content.
    pub revisions: Vec<Revision>,
}

impl std::fmt::Debug for DocxState {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("DocxState")
            .field("blocks", &self.model.blocks.len())
            .finish_non_exhaustive()
    }
}

/// Open and decode a `.docx` from its raw bytes.
pub(crate) fn open(bytes: &[u8]) -> Result<DocxState> {
    // Bound the entry count BEFORE `ZipArchive::new` (which eagerly collects the whole
    // central directory) — same authoritative limit the package layer enforces, so a
    // hostile archive can't amplify on the read path either.
    crate::opc::check_zip_entry_budget(bytes)?;
    let mut zip = zip::ZipArchive::new(std::io::Cursor::new(bytes))
        .map_err(|e| Error::Docx(format!("not a valid .docx (zip) container: {e}")))?;

    // All supplementary parts are best-effort: a missing styles/numbering/rels
    // part just means fewer headings/lists/links, never a failure.
    let rels = part(&mut zip, "word/_rels/document.xml.rels")
        .map(|s| parse_rels(&s))
        .unwrap_or_default();
    let styles = part(&mut zip, "word/styles.xml")
        .map(|s| styles::parse(&s))
        .unwrap_or_default();
    let numbering = part(&mut zip, "word/numbering.xml")
        .map(|s| numbering::parse(&s))
        .unwrap_or_default();
    let media = read_media(&mut zip, &rels);

    // The body is the one required part.
    let doc_xml = part(&mut zip, "word/document.xml")
        .ok_or_else(|| Error::Docx("missing word/document.xml".into()))?;
    let core_properties = part(&mut zip, "docProps/core.xml")
        .map(|s| parse_core_properties(&s))
        .unwrap_or_default();
    let custom_properties = part(&mut zip, "docProps/custom.xml")
        .map(|s| parse_custom_properties(&s))
        .unwrap_or_default();
    let custom_property_fields = custom_properties
        .iter()
        .map(|(key, value)| (document_property_key(key), value.clone()))
        .collect::<HashMap<_, _>>();
    let custom_xml_items = read_custom_xml_items(&mut zip);
    let extended_properties = part(&mut zip, "docProps/app.xml")
        .map(|s| parse_extended_properties(&s))
        .unwrap_or_default();
    let settings_xml = part(&mut zip, "word/settings.xml");
    let document_variables = settings_xml
        .as_deref()
        .map(parse_document_variables)
        .unwrap_or_default();
    let document_id = settings_xml.as_deref().and_then(parse_document_id);
    let preserve_legacy_form_cache = settings_xml
        .as_deref()
        .is_some_and(settings_preserves_legacy_form_cache);
    // Document-level footnote/endnote numbering (numStart/numFmt) applies to the
    // main body only; header/footer/note parts keep their own per-part local
    // numbering restarting at 1.
    let note_numbering = settings_xml
        .as_deref()
        .map(fields::note_numbering_from_settings)
        .unwrap_or_default();
    let document_properties = DocumentPropertyRefs {
        core: &core_properties,
        custom: &custom_property_fields,
        variables: &document_variables,
        extended: &extended_properties,
        file_size_bytes: Some(bytes.len()),
    };
    let field_properties = fields::FieldDocumentProperties {
        core: document_properties.core,
        custom: document_properties.custom,
        variables: document_properties.variables,
        extended: document_properties.extended,
        file_size_bytes: document_properties.file_size_bytes,
    };
    let raw_ref_targets =
        fields::ref_targets_with_properties(&doc_xml, field_properties, preserve_legacy_form_cache);
    let ref_position_context = fields::ref_position_context(&doc_xml, &numbering);
    let ref_number_context = fields::ref_number_context(&doc_xml, &numbering);
    let note_ref_context = fields::note_ref_context_with_numbering(
        &doc_xml,
        &raw_ref_targets,
        field_properties,
        preserve_legacy_form_cache,
        note_numbering,
    );
    let ref_targets = fields::ref_targets_with_note_context(
        &doc_xml,
        field_properties,
        preserve_legacy_form_cache,
        &note_ref_context,
    );
    let page_ref_context = fields::page_ref_context_with_properties(
        &doc_xml,
        &ref_targets,
        field_properties,
        preserve_legacy_form_cache,
    );
    let section_context = fields::section_context_with_properties(
        &doc_xml,
        &ref_targets,
        field_properties,
        preserve_legacy_form_cache,
    );
    let style_ref_context = fields::style_ref_context_with_properties(
        &doc_xml,
        &styles,
        &numbering,
        &fields::StyleRefResolutionSources {
            document_bookmarks: &ref_targets,
            note_refs: &note_ref_context,
            sections: &section_context,
        },
        field_properties,
        preserve_legacy_form_cache,
    );
    let legacy_form_context = fields::legacy_form_context(&doc_xml, preserve_legacy_form_cache);
    let table_formula_context = fields::table_formula_context_with_properties(
        &doc_xml,
        &ref_targets,
        &note_ref_context,
        &section_context,
        field_properties,
        preserve_legacy_form_cache,
    );
    let sequence_heading_context = fields::sequence_heading_context(&doc_xml, &styles);
    let toc_entries = fields::toc_entries_with_properties(
        &doc_xml,
        &styles,
        &ref_targets,
        &note_ref_context,
        &section_context,
        field_properties,
        preserve_legacy_form_cache,
    );
    let bookmark_names = fields::bookmark_names(&doc_xml);

    let ctx = body::Ctx {
        styles: &styles,
        numbering: &numbering,
        rels: &rels,
        media: &media,
        ref_targets: &ref_targets,
        ref_position_context: &ref_position_context,
        ref_number_context: &ref_number_context,
        page_ref_context: &page_ref_context,
        note_ref_context: &note_ref_context,
        section_context: &section_context,
        style_ref_context: &style_ref_context,
        legacy_form_context: &legacy_form_context,
        table_formula_context: &table_formula_context,
        toc_entries: &toc_entries,
        bookmark_names: &bookmark_names,
        core_properties: &core_properties,
        custom_properties: &custom_property_fields,
        document_variables: &document_variables,
        extended_properties: &extended_properties,
        file_size_bytes: Some(bytes.len()),
        ref_field_cursor: Default::default(),
        page_field_cursor: Default::default(),
        last_page_field_unsupported_display_format: Default::default(),
        page_ref_field_cursor: Default::default(),
        note_ref_field_cursor: Default::default(),
        section_field_cursor: Default::default(),
        style_ref_field_cursor: Default::default(),
        form_field_cursor: Default::default(),
        formula_field_cursor: Default::default(),
        sequence_counters: Default::default(),
        sequence_heading_counts: Default::default(),
        sequence_heading_scopes: Default::default(),
        autonum_counter: Default::default(),
        listnum_counter: Default::default(),
        field_bookmarks: Default::default(),
        counters: Default::default(),
    };
    let mut blocks = body::parse_document(&doc_xml, &ctx); // body only
                                                           // Footnotes/endnotes live in their own parts. Keep them SEPARATE from the body
                                                           // (not appended into `model.blocks`); their parts are preserved verbatim on save.
                                                           // They are re-joined for the read/text views below and in `Document::model()`.
    let part_env = PartParseEnv {
        styles: &styles,
        numbering: &numbering,
        properties: document_properties,
        preserve_legacy_form_cache,
    };
    let mut note_part = read_notes(
        &mut zip,
        "word/footnotes.xml",
        b"footnote",
        NoteKind::Footnote,
        part_env,
    );
    let mut endnote_part = read_notes(
        &mut zip,
        "word/endnotes.xml",
        b"endnote",
        NoteKind::Endnote,
        part_env,
    );
    note_part.blocks.extend(endnote_part.blocks);
    note_part.records.append(&mut endnote_part.records);
    note_part.revisions.extend(endnote_part.revisions);
    note_part
        .floating_shapes
        .extend(endnote_part.floating_shapes);
    note_part.text_boxes.extend(endnote_part.text_boxes);
    note_part.fields.extend(endnote_part.fields);
    extend_missing_comment_anchors(&mut note_part.comment_anchors, endnote_part.comment_anchors);
    attach_note_reference_anchors(
        &mut note_part.records,
        &doc_xml,
        &fields::FieldResolutionContext {
            properties: field_properties,
            document_bookmarks: &ref_targets,
            note_refs: &note_ref_context,
            sections: &section_context,
            style_refs: &style_ref_context,
            legacy_forms: &legacy_form_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
        },
    );
    let mut floating_shapes = read_floating_shapes(
        &doc_xml,
        ShapeFieldContext {
            properties: field_properties,
            document_bookmarks: &ref_targets,
            ref_positions: &ref_position_context,
            ref_numbers: &ref_number_context,
            page_refs: &page_ref_context,
            note_refs: &note_ref_context,
            sections: &section_context,
            legacy_forms: &legacy_form_context,
            table_formulas: &table_formula_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
            style_refs: &style_ref_context,
            sequence_headings: &sequence_heading_context,
        },
    );
    floating_shapes.extend(note_part.floating_shapes);
    let mut text_boxes = read_text_boxes(&doc_xml, &ctx, &floating_shapes);
    text_boxes.extend(note_part.text_boxes);
    // Running headers/footers referenced by the body's sectPr(s). `ctx` only holds
    // shared (&) borrows of rels/styles/numbering, so the &mut zip pass is fine.
    let HeaderFooterRead {
        sections: section_header_footers,
        final_section: final_header_footer,
        records: header_footers,
        comment_anchors: header_footer_comment_anchors,
        text_boxes: header_footer_text_boxes,
        revisions: header_footer_revisions,
        floating_shapes: header_footer_floating_shapes,
        fields: header_footer_fields,
    } = read_headers_footers(
        &mut zip,
        &doc_xml,
        &rels,
        &styles,
        &numbering,
        document_properties,
        preserve_legacy_form_cache,
    );
    floating_shapes.extend(header_footer_floating_shapes);
    text_boxes.extend(header_footer_text_boxes);
    apply_section_header_footers(&mut blocks, &section_header_footers);
    let comments_xml = part(&mut zip, "word/comments.xml");
    let comments_ext_xml = part(&mut zip, "word/commentsExtended.xml");
    let mut comments = if let Some(xml) = comments_xml.as_deref() {
        let comments_section_context = fields::section_context_with_properties(
            xml,
            &ref_targets,
            field_properties,
            preserve_legacy_form_cache,
        );
        let comments_style_ref_context = fields::style_ref_context_with_properties(
            xml,
            &styles,
            &numbering,
            &fields::StyleRefResolutionSources {
                document_bookmarks: &ref_targets,
                note_refs: &note_ref_context,
                sections: &comments_section_context,
            },
            field_properties,
            preserve_legacy_form_cache,
        );
        let comments_legacy_form_context =
            fields::legacy_form_context(xml, preserve_legacy_form_cache);
        comments::parse(
            xml,
            &fields::FieldResolutionContext {
                properties: field_properties,
                document_bookmarks: &ref_targets,
                note_refs: &note_ref_context,
                sections: &comments_section_context,
                style_refs: &comments_style_ref_context,
                legacy_forms: &comments_legacy_form_context,
                toc_entries: &toc_entries,
                bookmark_names: &bookmark_names,
            },
        )
    } else {
        Vec::new()
    };
    if let (Some(comments_xml), Some(comments_ext_xml)) =
        (comments_xml.as_deref(), comments_ext_xml.as_deref())
    {
        comments::apply_extended_parent_ids(&mut comments, comments_xml, comments_ext_xml);
    }
    let field_resolution_context = fields::FieldResolutionContext {
        properties: field_properties,
        document_bookmarks: &ref_targets,
        note_refs: &note_ref_context,
        sections: &section_context,
        style_refs: &style_ref_context,
        legacy_forms: &legacy_form_context,
        toc_entries: &toc_entries,
        bookmark_names: &bookmark_names,
    };
    let mut comment_anchors = comments::parse_anchors(&doc_xml, &field_resolution_context);
    extend_missing_comment_anchors(&mut comment_anchors, note_part.comment_anchors);
    extend_missing_comment_anchors(&mut comment_anchors, header_footer_comment_anchors);
    for comment in &mut comments {
        comment.anchor = comment_anchors.get(&comment.id).cloned();
    }
    let mut fields = fields::parse_with_note_numbering(
        &doc_xml,
        &styles,
        &toc_entries,
        &numbering,
        fields::FieldDocumentProperties {
            core: &core_properties,
            custom: &custom_property_fields,
            variables: &document_variables,
            extended: &extended_properties,
            file_size_bytes: Some(bytes.len()),
        },
        preserve_legacy_form_cache,
        note_numbering,
    );
    let mut revisions = revisions::parse(&doc_xml, &field_resolution_context);
    revisions.extend(note_part.revisions);
    revisions.extend(header_footer_revisions);
    // Stats reflect the full visible content (body + notes).
    let stats = {
        let mut all = blocks.clone();
        all.extend(note_part.blocks.iter().cloned());
        assemble::compute_stats(&all)
    };
    let model = DocModel {
        blocks, // body only
        regions: Vec::new(),
        // `.docx` text is Unicode (no ANSI codepage); these fields are not
        // meaningful here, unlike the `.doc` path's `lid`/codepage.
        meta: DocMeta {
            codepage: 0,
            lid: 0,
            stats,
        },
        custom_properties,
        custom_xml_items,
        setup: crate::model::DocSetup {
            page: body::scan_page_setup(&doc_xml),
            header: final_header_footer.header,
            first_header: final_header_footer.first_header,
            even_header: final_header_footer.even_header,
            footer: final_header_footer.footer,
            first_footer: final_header_footer.first_footer,
            even_footer: final_header_footer.even_footer,
            page_number_start: body::scan_page_number_start(&doc_xml),
            page_number_format: body::scan_page_number_format(&doc_xml),
            columns: body::scan_section_columns(&doc_xml),
            text_direction: body::scan_section_text_direction(&doc_xml),
            doc_grid: body::scan_section_doc_grid(&doc_xml),
            document_id,
            title_page: body::scan_section_title_page(&doc_xml),
            title: core_properties.title.clone(),
            creator: core_properties.creator.clone(),
            ..crate::model::DocSetup::default()
        },
    };
    fields.extend(note_part.fields);
    fields.extend(header_footer_fields);
    let main_text = body_text(&model); // body only
                                       // Full text: body, then notes, then section/final headers/footers.
    let text = {
        let mut raw = String::new();
        flatten(&model.blocks, &mut raw);
        flatten(&note_part.blocks, &mut raw);
        flatten_header_footer_surfaces(&model, &mut raw);
        text::finalize(&raw)
    };
    // Retain the whole package verbatim for package-preserving editing/save. The
    // reader above is unchanged; this is an independent second pass over `bytes`.
    let package = crate::opc::Package::from_zip(bytes)?;
    Ok(DocxState {
        model,
        notes: note_part.blocks,
        text,
        main_text,
        package,
        comments,
        note_records: note_part.records,
        text_boxes,
        floating_shapes,
        header_footers,
        core_properties,
        fields,
        revisions,
    })
}

/// The bundled blank template bytes — a valid package this crate ships and tests.
const BLANK_DOCX: &[u8] = include_bytes!("../../assets/blank.docx");

/// A blank `.docx` state from the bundled template — backs [`crate::Document::new`].
/// Cannot fail in practice (a corrupt asset is caught by `new_from_template`); see
/// [`try_blank`] for the non-panicking variant.
pub(crate) fn blank() -> DocxState {
    open(BLANK_DOCX).expect("bundled assets/blank.docx is a valid package")
}

/// Fallible blank-template open — backs [`crate::Document::try_new`].
pub(crate) fn try_blank() -> Result<DocxState> {
    open(BLANK_DOCX)
}

/// Resolve and parse the header/footer parts referenced by the body's sectPr(s).
#[derive(Clone, Default)]
struct SectionHeaderFooter {
    header: Vec<Block>,
    first_header: Vec<Block>,
    even_header: Vec<Block>,
    footer: Vec<Block>,
    first_footer: Vec<Block>,
    even_footer: Vec<Block>,
}

#[derive(Default)]
struct HeaderFooterBlocks {
    default: Vec<Block>,
    first: Vec<Block>,
    even: Vec<Block>,
}

struct HeaderFooterRead {
    sections: Vec<SectionHeaderFooter>,
    final_section: SectionHeaderFooter,
    records: Vec<HeaderFooter>,
    comment_anchors: HashMap<String, TextAnchor>,
    text_boxes: Vec<TextBox>,
    revisions: Vec<Revision>,
    floating_shapes: Vec<FloatingShape>,
    fields: Vec<Field>,
}

struct HeaderFooterPartRead {
    blocks: HeaderFooterBlocks,
    records: Vec<HeaderFooter>,
    comment_anchors: HashMap<String, TextAnchor>,
    text_boxes: Vec<TextBox>,
    revisions: Vec<Revision>,
    floating_shapes: Vec<FloatingShape>,
    fields: Vec<Field>,
}

#[derive(Clone, Copy)]
struct DocumentPropertyRefs<'a> {
    core: &'a CoreProperties,
    custom: &'a HashMap<String, String>,
    variables: &'a HashMap<String, String>,
    extended: &'a HashMap<String, String>,
    file_size_bytes: Option<usize>,
}

/// Shared environment for parsing a supplementary `.docx` part (header/footer or
/// notes): the stylesheet and numbering tables, the document property refs, and
/// whether cached legacy-form results should be preserved. Bundled so the part
/// readers take one value instead of four parallel parameters.
#[derive(Clone, Copy)]
struct PartParseEnv<'a> {
    styles: &'a styles::Styles,
    numbering: &'a numbering::Numbering,
    properties: DocumentPropertyRefs<'a>,
    preserve_legacy_form_cache: bool,
}

fn read_headers_footers(
    zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>,
    doc_xml: &str,
    rels: &Rels,
    styles: &styles::Styles,
    numbering: &numbering::Numbering,
    properties: DocumentPropertyRefs<'_>,
    preserve_legacy_form_cache: bool,
) -> HeaderFooterRead {
    let part_env = PartParseEnv {
        styles,
        numbering,
        properties,
        preserve_legacy_form_cache,
    };
    let section_refs = body::scan_hf_ref_sections(doc_xml);
    let mut sections = Vec::with_capacity(section_refs.len());
    let mut records = Vec::new();
    let mut comment_anchors = HashMap::new();
    let mut text_boxes = Vec::new();
    let mut revisions = Vec::new();
    let mut floating_shapes = Vec::new();
    let mut field_entries = Vec::new();
    let mut seen_records = std::collections::HashSet::new();
    let mut seen_text_boxes = std::collections::HashSet::new();
    let mut inherited_header = Vec::new();
    let mut inherited_footer = Vec::new();

    for refs in section_refs {
        let header_has_default = has_default_header_footer_ref(&refs.headers);
        let footer_has_default = has_default_header_footer_ref(&refs.footers);
        let HeaderFooterPartRead {
            blocks: header_blocks,
            records: header_records,
            comment_anchors: header_comment_anchors,
            text_boxes: header_text_boxes,
            revisions: header_revisions,
            floating_shapes: header_floating_shapes,
            fields: header_fields,
        } = read_hf_parts(
            zip,
            &refs.headers,
            HeaderFooterPartKind::Header,
            rels,
            part_env,
        );
        extend_unique_header_footer_records(&mut records, &mut seen_records, header_records);
        extend_missing_comment_anchors(&mut comment_anchors, header_comment_anchors);
        extend_unique_text_box_records(&mut text_boxes, &mut seen_text_boxes, header_text_boxes);
        extend_unique_revision_records(&mut revisions, header_revisions);
        extend_unique_floating_shape_records(&mut floating_shapes, header_floating_shapes);
        field_entries.extend(header_fields);
        let mut header = header_blocks.default;
        // Omitted odd/default refs inherit the previous section; an explicit
        // default ref, even when blank/unresolved, resets the inherited surface.
        if !header_has_default && !inherited_header.is_empty() {
            header = inherited_header.clone();
        }
        if header_has_default || !header.is_empty() {
            inherited_header = header.clone();
        }

        let HeaderFooterPartRead {
            blocks: footer_blocks,
            records: footer_records,
            comment_anchors: footer_comment_anchors,
            text_boxes: footer_text_boxes,
            revisions: footer_revisions,
            floating_shapes: footer_floating_shapes,
            fields: footer_fields,
        } = read_hf_parts(
            zip,
            &refs.footers,
            HeaderFooterPartKind::Footer,
            rels,
            part_env,
        );
        extend_unique_header_footer_records(&mut records, &mut seen_records, footer_records);
        extend_missing_comment_anchors(&mut comment_anchors, footer_comment_anchors);
        extend_unique_text_box_records(&mut text_boxes, &mut seen_text_boxes, footer_text_boxes);
        extend_unique_revision_records(&mut revisions, footer_revisions);
        extend_unique_floating_shape_records(&mut floating_shapes, footer_floating_shapes);
        field_entries.extend(footer_fields);
        let mut footer = footer_blocks.default;
        // Same inheritance rule as headers.
        if !footer_has_default && !inherited_footer.is_empty() {
            footer = inherited_footer.clone();
        }
        if footer_has_default || !footer.is_empty() {
            inherited_footer = footer.clone();
        }
        sections.push(SectionHeaderFooter {
            header,
            first_header: header_blocks.first,
            even_header: header_blocks.even,
            footer,
            first_footer: footer_blocks.first,
            even_footer: footer_blocks.even,
        });
    }

    let final_section = sections.last().cloned().unwrap_or_default();
    HeaderFooterRead {
        sections,
        final_section,
        records,
        comment_anchors,
        text_boxes,
        revisions,
        floating_shapes,
        fields: field_entries,
    }
}

fn extend_unique_header_footer_records(
    records: &mut Vec<HeaderFooter>,
    seen: &mut std::collections::HashSet<String>,
    next: Vec<HeaderFooter>,
) {
    for record in next {
        if seen.insert(record.id.clone()) {
            records.push(record);
        }
    }
}

fn extend_unique_text_box_records(
    records: &mut Vec<TextBox>,
    seen: &mut std::collections::HashSet<String>,
    next: Vec<TextBox>,
) {
    for record in next {
        if seen.insert(record.id.clone()) {
            records.push(record);
        }
    }
}

fn extend_unique_revision_records(records: &mut Vec<Revision>, next: Vec<Revision>) {
    for record in next {
        if !records.contains(&record) {
            records.push(record);
        }
    }
}

fn extend_unique_floating_shape_records(
    records: &mut Vec<FloatingShape>,
    next: Vec<FloatingShape>,
) {
    for record in next {
        if !records.contains(&record) {
            records.push(record);
        }
    }
}

fn apply_section_header_footers(blocks: &mut [Block], sections: &[SectionHeaderFooter]) {
    if sections.is_empty() {
        return;
    }
    let section_break_count = blocks
        .iter()
        .filter(|block| matches!(block, Block::SectionBreak(_)))
        .count();
    let section_count = if sections.len() > section_break_count {
        section_break_count
    } else {
        sections.len()
    };
    let mut section_iter = sections[..section_count].iter();
    for block in blocks {
        if let Block::SectionBreak(setup) = block {
            let Some(section) = section_iter.next() else {
                break;
            };
            setup.header = section.header.clone();
            setup.first_header = section.first_header.clone();
            setup.even_header = section.even_header.clone();
            setup.footer = section.footer.clone();
            setup.first_footer = section.first_footer.clone();
            setup.even_footer = section.even_footer.clone();
        }
    }
}

fn has_default_header_footer_ref(refs: &[body::HeaderFooterRef]) -> bool {
    refs.iter()
        .any(|reference| normalized_header_footer_type(&reference.type_name) == "default")
}

/// Read each unique referenced header/footer part once (dedup by part name), with
/// its own `_rels`/media so links and images inside the part resolve correctly.
#[derive(Clone, Copy)]
enum HeaderFooterPartKind {
    Header,
    Footer,
}

fn read_hf_parts(
    zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>,
    refs: &[body::HeaderFooterRef],
    part_kind: HeaderFooterPartKind,
    rels: &Rels,
    env: PartParseEnv<'_>,
) -> HeaderFooterPartRead {
    let PartParseEnv {
        styles,
        numbering,
        properties,
        preserve_legacy_form_cache,
    } = env;
    let mut seen_blocks = std::collections::HashSet::new();
    let mut seen_records = std::collections::HashSet::new();
    let mut seen_text_boxes = std::collections::HashSet::new();
    let mut seen_revisions = std::collections::HashSet::new();
    let mut seen_floating_shapes = std::collections::HashSet::new();
    let mut blocks = HeaderFooterBlocks::default();
    let mut records = Vec::new();
    let mut comment_anchors = HashMap::new();
    let mut text_boxes = Vec::new();
    let mut revisions = Vec::new();
    let mut floating_shapes = Vec::new();
    let mut field_entries = Vec::new();
    let mut seen_fields = std::collections::HashSet::new();
    for reference in refs {
        let Some((target, external)) = rels.get(&reference.rel_id) else {
            continue;
        };
        if *external {
            continue;
        }
        let path = normalize_part(target);
        let Some(xml) = part(zip, &path) else {
            continue;
        };
        let part_rels = part(zip, &part_rels_path(&path))
            .map(|s| parse_rels(&s))
            .unwrap_or_default();
        let part_media = read_media(zip, &part_rels);
        let field_properties = fields::FieldDocumentProperties {
            core: properties.core,
            custom: properties.custom,
            variables: properties.variables,
            extended: properties.extended,
            file_size_bytes: properties.file_size_bytes,
        };
        let raw_ref_targets =
            fields::ref_targets_with_properties(&xml, field_properties, preserve_legacy_form_cache);
        let ref_position_context = fields::ref_position_context(&xml, numbering);
        let ref_number_context = fields::ref_number_context(&xml, numbering);
        let page_ref_context = fields::PageRefContext::empty();
        let note_ref_context = fields::note_ref_context_with_properties(
            &xml,
            &raw_ref_targets,
            field_properties,
            preserve_legacy_form_cache,
        );
        let ref_targets = fields::ref_targets_with_note_context(
            &xml,
            field_properties,
            preserve_legacy_form_cache,
            &note_ref_context,
        );
        let section_context = fields::section_context_with_properties(
            &xml,
            &ref_targets,
            field_properties,
            preserve_legacy_form_cache,
        );
        let style_ref_context = fields::style_ref_context_with_properties(
            &xml,
            styles,
            numbering,
            &fields::StyleRefResolutionSources {
                document_bookmarks: &ref_targets,
                note_refs: &note_ref_context,
                sections: &section_context,
            },
            field_properties,
            preserve_legacy_form_cache,
        );
        let legacy_form_context = fields::legacy_form_context(&xml, preserve_legacy_form_cache);
        let table_formula_context = fields::table_formula_context_with_properties(
            &xml,
            &ref_targets,
            &note_ref_context,
            &section_context,
            field_properties,
            preserve_legacy_form_cache,
        );
        let sequence_heading_context = fields::sequence_heading_context(&xml, styles);
        let toc_entries = fields::toc_entries_with_properties(
            &xml,
            styles,
            &ref_targets,
            &note_ref_context,
            &section_context,
            field_properties,
            preserve_legacy_form_cache,
        );
        let bookmark_names = fields::bookmark_names(&xml);
        let field_resolution_context = fields::FieldResolutionContext {
            properties: field_properties,
            document_bookmarks: &ref_targets,
            note_refs: &note_ref_context,
            sections: &section_context,
            style_refs: &style_ref_context,
            legacy_forms: &legacy_form_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
        };
        let hf_ctx = body::Ctx {
            styles,
            numbering,
            rels: &part_rels,
            media: &part_media,
            ref_targets: &ref_targets,
            ref_position_context: &ref_position_context,
            ref_number_context: &ref_number_context,
            page_ref_context: &page_ref_context,
            note_ref_context: &note_ref_context,
            section_context: &section_context,
            style_ref_context: &style_ref_context,
            legacy_form_context: &legacy_form_context,
            table_formula_context: &table_formula_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
            core_properties: properties.core,
            custom_properties: properties.custom,
            document_variables: properties.variables,
            extended_properties: properties.extended,
            file_size_bytes: properties.file_size_bytes,
            ref_field_cursor: Default::default(),
            page_field_cursor: Default::default(),
            last_page_field_unsupported_display_format: Default::default(),
            page_ref_field_cursor: Default::default(),
            note_ref_field_cursor: Default::default(),
            section_field_cursor: Default::default(),
            style_ref_field_cursor: Default::default(),
            form_field_cursor: Default::default(),
            formula_field_cursor: Default::default(),
            sequence_counters: Default::default(),
            sequence_heading_counts: Default::default(),
            sequence_heading_scopes: Default::default(),
            autonum_counter: Default::default(),
            listnum_counter: Default::default(),
            field_bookmarks: Default::default(),
            counters: Default::default(),
        };
        let type_name = normalized_header_footer_type(&reference.type_name);
        extend_missing_comment_anchors(
            &mut comment_anchors,
            comments::parse_anchors(&xml, &field_resolution_context),
        );
        if seen_text_boxes.insert((path.clone(), type_name.to_string())) {
            text_boxes.extend(read_text_boxes_with_prefix(
                &xml,
                &hf_ctx,
                &[],
                &format!("{path}#{type_name}-text-box"),
            ));
        }
        if seen_revisions.insert((path.clone(), type_name.to_string())) {
            revisions.extend(revisions::parse(&xml, &field_resolution_context));
        }
        if seen_floating_shapes.insert((path.clone(), type_name.to_string())) {
            floating_shapes.extend(read_floating_shapes(
                &xml,
                ShapeFieldContext {
                    properties: fields::FieldDocumentProperties {
                        core: properties.core,
                        custom: properties.custom,
                        variables: properties.variables,
                        extended: properties.extended,
                        file_size_bytes: properties.file_size_bytes,
                    },
                    document_bookmarks: &ref_targets,
                    ref_positions: &ref_position_context,
                    ref_numbers: &ref_number_context,
                    page_refs: &page_ref_context,
                    note_refs: &note_ref_context,
                    sections: &section_context,
                    legacy_forms: &legacy_form_context,
                    table_formulas: &table_formula_context,
                    toc_entries: &toc_entries,
                    bookmark_names: &bookmark_names,
                    style_refs: &style_ref_context,
                    sequence_headings: &sequence_heading_context,
                },
            ));
        }
        if seen_fields.insert((path.clone(), type_name.to_string())) {
            field_entries.extend(fields::parse(
                &xml,
                styles,
                &toc_entries,
                numbering,
                fields::FieldDocumentProperties {
                    core: properties.core,
                    custom: properties.custom,
                    variables: properties.variables,
                    extended: properties.extended,
                    file_size_bytes: properties.file_size_bytes,
                },
                preserve_legacy_form_cache,
            ));
        }
        let part_blocks = body::parse_hdrftr(&xml, &hf_ctx);
        if seen_blocks.insert((path.clone(), type_name.to_string())) {
            match type_name {
                "first" => blocks.first.extend(part_blocks.clone()),
                "even" => blocks.even.extend(part_blocks.clone()),
                _ => blocks.default.extend(part_blocks.clone()),
            }
        }
        if seen_records.insert((path.clone(), type_name.to_string())) {
            let text = blocks_text(&part_blocks);
            if !text.is_empty() {
                records.push(HeaderFooter {
                    id: format!("{path}#{type_name}"),
                    kind: header_footer_kind(part_kind, type_name),
                    section: None,
                    text,
                });
            }
        }
    }
    HeaderFooterPartRead {
        blocks,
        records,
        comment_anchors,
        text_boxes,
        revisions,
        floating_shapes,
        fields: field_entries,
    }
}

fn extend_missing_comment_anchors(
    anchors: &mut HashMap<String, TextAnchor>,
    next: HashMap<String, TextAnchor>,
) {
    for (id, anchor) in next {
        anchors.entry(id).or_insert(anchor);
    }
}

fn normalized_header_footer_type(value: &str) -> &'static str {
    let value = value.trim();
    match value {
        "first" => "first",
        "even" => "even",
        _ => "default",
    }
}

fn header_footer_kind(part_kind: HeaderFooterPartKind, type_name: &str) -> HeaderFooterKind {
    match (part_kind, type_name) {
        (HeaderFooterPartKind::Header, "first") => HeaderFooterKind::FirstPageHeader,
        (HeaderFooterPartKind::Header, "even") => HeaderFooterKind::EvenPageHeader,
        (HeaderFooterPartKind::Header, _) => HeaderFooterKind::Header,
        (HeaderFooterPartKind::Footer, "first") => HeaderFooterKind::FirstPageFooter,
        (HeaderFooterPartKind::Footer, "even") => HeaderFooterKind::EvenPageFooter,
        (HeaderFooterPartKind::Footer, _) => HeaderFooterKind::Footer,
    }
}

#[derive(Default)]
struct NotePartRead {
    blocks: Vec<Block>,
    records: Vec<Note>,
    comment_anchors: HashMap<String, TextAnchor>,
    revisions: Vec<Revision>,
    floating_shapes: Vec<FloatingShape>,
    text_boxes: Vec<TextBox>,
    fields: Vec<Field>,
}

/// Read a footnotes/endnotes part (if present) into its real notes' blocks, with
/// the part's own rels/media so links and images inside notes resolve.
fn read_notes(
    zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>,
    name: &str,
    tag: &[u8],
    kind: NoteKind,
    env: PartParseEnv<'_>,
) -> NotePartRead {
    let PartParseEnv {
        styles,
        numbering,
        properties,
        preserve_legacy_form_cache,
    } = env;
    let Some(xml) = part(zip, name) else {
        return NotePartRead::default();
    };
    let part_rels = part(zip, &part_rels_path(name))
        .map(|s| parse_rels(&s))
        .unwrap_or_default();
    let part_media = read_media(zip, &part_rels);
    let field_properties = fields::FieldDocumentProperties {
        core: properties.core,
        custom: properties.custom,
        variables: properties.variables,
        extended: properties.extended,
        file_size_bytes: properties.file_size_bytes,
    };
    let raw_ref_targets =
        fields::ref_targets_with_properties(&xml, field_properties, preserve_legacy_form_cache);
    let ref_position_context = fields::ref_position_context(&xml, numbering);
    let ref_number_context = fields::ref_number_context(&xml, numbering);
    let page_ref_context = fields::PageRefContext::empty();
    let note_ref_context = fields::note_ref_context_with_properties(
        &xml,
        &raw_ref_targets,
        field_properties,
        preserve_legacy_form_cache,
    );
    let ref_targets = fields::ref_targets_with_note_context(
        &xml,
        field_properties,
        preserve_legacy_form_cache,
        &note_ref_context,
    );
    let section_context = fields::section_context_with_properties(
        &xml,
        &ref_targets,
        field_properties,
        preserve_legacy_form_cache,
    );
    let style_ref_context = fields::style_ref_context_with_properties(
        &xml,
        styles,
        numbering,
        &fields::StyleRefResolutionSources {
            document_bookmarks: &ref_targets,
            note_refs: &note_ref_context,
            sections: &section_context,
        },
        field_properties,
        preserve_legacy_form_cache,
    );
    let legacy_form_context = fields::legacy_form_context(&xml, preserve_legacy_form_cache);
    let table_formula_context = fields::table_formula_context_with_properties(
        &xml,
        &ref_targets,
        &note_ref_context,
        &section_context,
        field_properties,
        preserve_legacy_form_cache,
    );
    let sequence_heading_context = fields::sequence_heading_context(&xml, styles);
    let toc_entries = fields::toc_entries_with_properties(
        &xml,
        styles,
        &ref_targets,
        &note_ref_context,
        &section_context,
        field_properties,
        preserve_legacy_form_cache,
    );
    let bookmark_names = fields::bookmark_names(&xml);
    let field_resolution_context = fields::FieldResolutionContext {
        properties: field_properties,
        document_bookmarks: &ref_targets,
        note_refs: &note_ref_context,
        sections: &section_context,
        style_refs: &style_ref_context,
        legacy_forms: &legacy_form_context,
        toc_entries: &toc_entries,
        bookmark_names: &bookmark_names,
    };
    let ctx = body::Ctx {
        styles,
        numbering,
        rels: &part_rels,
        media: &part_media,
        ref_targets: &ref_targets,
        ref_position_context: &ref_position_context,
        ref_number_context: &ref_number_context,
        page_ref_context: &page_ref_context,
        note_ref_context: &note_ref_context,
        section_context: &section_context,
        style_ref_context: &style_ref_context,
        legacy_form_context: &legacy_form_context,
        table_formula_context: &table_formula_context,
        toc_entries: &toc_entries,
        bookmark_names: &bookmark_names,
        core_properties: properties.core,
        custom_properties: properties.custom,
        document_variables: properties.variables,
        extended_properties: properties.extended,
        file_size_bytes: properties.file_size_bytes,
        ref_field_cursor: Default::default(),
        page_field_cursor: Default::default(),
        last_page_field_unsupported_display_format: Default::default(),
        page_ref_field_cursor: Default::default(),
        note_ref_field_cursor: Default::default(),
        section_field_cursor: Default::default(),
        style_ref_field_cursor: Default::default(),
        form_field_cursor: Default::default(),
        formula_field_cursor: Default::default(),
        sequence_counters: Default::default(),
        sequence_heading_counts: Default::default(),
        sequence_heading_scopes: Default::default(),
        autonum_counter: Default::default(),
        listnum_counter: Default::default(),
        field_bookmarks: Default::default(),
        counters: Default::default(),
    };
    let mut blocks = Vec::new();
    let mut records = Vec::new();
    let comment_anchors = comments::parse_anchors(&xml, &field_resolution_context);
    let revisions = revisions::parse(&xml, &field_resolution_context);
    let floating_shapes = read_floating_shapes(
        &xml,
        ShapeFieldContext {
            properties: fields::FieldDocumentProperties {
                core: properties.core,
                custom: properties.custom,
                variables: properties.variables,
                extended: properties.extended,
                file_size_bytes: properties.file_size_bytes,
            },
            document_bookmarks: &ref_targets,
            ref_positions: &ref_position_context,
            ref_numbers: &ref_number_context,
            page_refs: &page_ref_context,
            note_refs: &note_ref_context,
            sections: &section_context,
            legacy_forms: &legacy_form_context,
            table_formulas: &table_formula_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
            style_refs: &style_ref_context,
            sequence_headings: &sequence_heading_context,
        },
    );
    let text_box_id_prefix = format!("{name}-text-box");
    let text_boxes = read_text_boxes_with_prefix(&xml, &ctx, &floating_shapes, &text_box_id_prefix);
    let fields = fields::parse(
        &xml,
        styles,
        &toc_entries,
        numbering,
        fields::FieldDocumentProperties {
            core: properties.core,
            custom: properties.custom,
            variables: properties.variables,
            extended: properties.extended,
            file_size_bytes: properties.file_size_bytes,
        },
        preserve_legacy_form_cache,
    );
    for (id, note_blocks) in body::parse_note_entries(&xml, &ctx, tag) {
        let text = blocks_text(&note_blocks);
        records.push(Note {
            id,
            kind,
            text,
            anchor: None,
        });
        blocks.extend(note_blocks);
    }
    NotePartRead {
        blocks,
        records,
        comment_anchors,
        revisions,
        floating_shapes,
        text_boxes,
        fields,
    }
}

fn read_text_boxes(
    doc_xml: &str,
    ctx: &body::Ctx<'_>,
    floating_shapes: &[FloatingShape],
) -> Vec<TextBox> {
    read_text_boxes_with_prefix(doc_xml, ctx, floating_shapes, "docx-text-box")
}

fn read_text_boxes_with_prefix(
    doc_xml: &str,
    ctx: &body::Ctx<'_>,
    floating_shapes: &[FloatingShape],
    id_prefix: &str,
) -> Vec<TextBox> {
    let text_boxes: Vec<_> = body::parse_text_boxes(doc_xml, ctx)
        .into_iter()
        .enumerate()
        .filter(|(_, text)| !text.is_empty())
        .collect();
    let ordered_anchors = ordered_text_box_anchors(&text_boxes, floating_shapes);
    text_boxes
        .into_iter()
        .enumerate()
        .map(|(text_box_index, (index, text))| TextBox {
            id: format!("{id_prefix}-{index}"),
            anchor: ordered_anchors
                .get(text_box_index)
                .and_then(|anchor| anchor.clone())
                .or_else(|| text_box_anchor(&text, floating_shapes)),
            text,
        })
        .collect()
}

fn ordered_text_box_anchors(
    text_boxes: &[(usize, String)],
    floating_shapes: &[FloatingShape],
) -> Vec<Option<TextAnchor>> {
    let text_box_shapes: Vec<_> = floating_shapes
        .iter()
        .filter(|shape| shape.text.is_some() && shape.anchor_text.is_some())
        .collect();
    if text_boxes.len() != text_box_shapes.len()
        || !text_boxes
            .iter()
            .map(|(_, text)| text.as_str())
            .zip(&text_box_shapes)
            .all(|(text, shape)| shape.text.as_deref() == Some(text))
    {
        return vec![None; text_boxes.len()];
    }
    text_box_shapes
        .into_iter()
        .map(text_anchor_from_shape)
        .collect()
}

fn text_box_anchor(text: &str, floating_shapes: &[FloatingShape]) -> Option<TextAnchor> {
    let mut matches = floating_shapes.iter().filter(|shape| {
        shape.text.as_deref() == Some(text) && shape.anchor_text.as_deref().is_some()
    });
    let shape = matches.next()?;
    if matches.next().is_some() {
        return None;
    }
    text_anchor_from_shape(shape)
}

fn text_anchor_from_shape(shape: &FloatingShape) -> Option<TextAnchor> {
    Some(TextAnchor {
        id: shape.id.clone(),
        text: shape.anchor_text.clone()?,
    })
}

/// Read-only field-resolution context threaded through the floating-shape
/// readers and their `ShapeFieldCursor` helpers. Bundles the document property
/// refs and every field-family context into one borrow so the shape scanners do
/// not pass a dozen individual parameters.
#[derive(Clone, Copy)]
struct ShapeFieldContext<'a> {
    properties: fields::FieldDocumentProperties<'a>,
    document_bookmarks: &'a HashMap<String, String>,
    ref_positions: &'a fields::RefPositionContext,
    ref_numbers: &'a fields::RefNumberContext,
    page_refs: &'a fields::PageRefContext,
    note_refs: &'a fields::NoteRefContext,
    sections: &'a fields::SectionContext,
    legacy_forms: &'a fields::LegacyFormContext,
    table_formulas: &'a fields::TableFormulaContext,
    toc_entries: &'a [fields::TocEntry],
    bookmark_names: &'a HashSet<String>,
    style_refs: &'a fields::StyleRefContext,
    sequence_headings: &'a fields::SequenceHeadingContext,
}

/// The per-field positions a `ShapeFieldCursor` resolves for one instruction,
/// bundled so `computed_shape_context_field_result` takes one value instead of
/// eight parallel `Option`s.
#[derive(Default)]
struct ShapeFieldPositions {
    ref_position: Option<fields::RefFieldPosition>,
    page_position: Option<fields::PageRefPosition>,
    page_ref_position: Option<fields::PageRefPosition>,
    page_ref_order: Option<usize>,
    note_ref_position: Option<fields::NoteRefFieldPosition>,
    ref_note_position: Option<fields::NoteRefFieldPosition>,
    section_position: Option<fields::SectionFieldPosition>,
    style_ref_position: Option<fields::StyleRefFieldPosition>,
}

fn read_floating_shapes(doc_xml: &str, cx: ShapeFieldContext<'_>) -> Vec<FloatingShape> {
    let mut r = Reader::from_str(doc_xml);
    let mut shapes = Vec::new();
    let mut shape_field_cursor = ShapeFieldCursor::default();
    let mut scan_depth = 0usize;
    let mut in_body = false;
    let mut body_depth = 0usize;
    let mut body_block_candidate_depths = vec![0usize];
    let mut next_body_block_index = 0usize;
    let mut current_body_block_index = None;
    let mut current_body_block_depth = None;
    let mut current_body_block_text = String::new();
    let mut current_body_block_shapes = Vec::new();
    let mut anchor_complex_field = FloatingAnchorComplexField::default();
    let mut anchor_field_state = fields::ContextlessFieldState::with_document_and_note_context(
        cx.properties,
        cx.document_bookmarks,
        cx.note_refs,
    )
    .with_toc_context(cx.toc_entries, cx.bookmark_names)
    .with_section_context(cx.sections)
    .with_legacy_form_context_from(cx.legacy_forms, 0);
    let mut alternate_content_stack = Vec::new();
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if should_skip_redundant_alternate_branch(
                    &mut alternate_content_stack,
                    scan_depth,
                    name,
                ) {
                    skip_subtree(&mut r);
                    continue;
                }
                if is_old_revision_content(name) {
                    skip_subtree(&mut r);
                    continue;
                }
                if name == b"AlternateContent" {
                    alternate_content_stack.push(AlternateContentState {
                        branch_depth: scan_depth + 1,
                        took_branch: false,
                    });
                }
                if name == b"fldSimple" {
                    shape_field_cursor.start_simple_field(&e, scan_depth + 1, cx);
                } else if name == b"fldChar" {
                    shape_field_cursor.apply_field_char(&e, cx);
                }
                if name == b"body" {
                    in_body = true;
                    body_depth = 0;
                    body_block_candidate_depths.clear();
                    body_block_candidate_depths.push(0);
                    current_body_block_index = None;
                    current_body_block_depth = None;
                    current_body_block_text.clear();
                    current_body_block_shapes.clear();
                    anchor_complex_field = FloatingAnchorComplexField::default();
                    anchor_field_state.clear();
                    alternate_content_stack.clear();
                    scan_depth += 1;
                    continue;
                }
                if in_body {
                    if current_body_block_index.is_none()
                        && body_block_candidate_depths.contains(&body_depth)
                        && is_transparent_body_block_container(name)
                    {
                        body_block_candidate_depths.push(body_depth + 1);
                    }
                    if current_body_block_index.is_none()
                        && body_block_candidate_depths.contains(&body_depth)
                        && is_body_block(name)
                    {
                        current_body_block_index = Some(next_body_block_index);
                        current_body_block_depth = Some(body_depth + 1);
                        current_body_block_text.clear();
                        current_body_block_shapes.clear();
                        anchor_complex_field = FloatingAnchorComplexField::default();
                        anchor_field_state.clear();
                        next_body_block_index += 1;
                    }
                    body_depth += 1;
                }
                if in_body && current_body_block_index.is_some() && name == b"fldSimple" {
                    let simple_field_depth = scan_depth + 1;
                    if anchor_complex_field.suppresses_result() {
                        skip_subtree(&mut r);
                        shape_field_cursor.end_element(b"fldSimple", simple_field_depth);
                        body_depth = body_depth.saturating_sub(1);
                        continue;
                    } else if let Some(instruction) = attr_local_trimmed(&e, b"instr") {
                        if is_text_form_field_instruction(&instruction) {
                            let text = computed_floating_anchor_simple_text_form_field_text(
                                &mut r,
                                &instruction,
                                &mut anchor_field_state,
                            );
                            if let Some(text) = text {
                                append_floating_anchor_text(&mut current_body_block_text, &text);
                            }
                            shape_field_cursor.end_element(b"fldSimple", simple_field_depth);
                            body_depth = body_depth.saturating_sub(1);
                            continue;
                        } else if let Some(text) = computed_floating_anchor_field_text(
                            &instruction,
                            &mut anchor_field_state,
                        ) {
                            append_floating_anchor_text(&mut current_body_block_text, &text);
                            skip_subtree(&mut r);
                            shape_field_cursor.end_element(b"fldSimple", simple_field_depth);
                            body_depth = body_depth.saturating_sub(1);
                            continue;
                        }
                    }
                }
                if in_body && current_body_block_index.is_some() && name == b"fldChar" {
                    if let Some(text) =
                        anchor_complex_field.apply_field_char(&e, &mut anchor_field_state)
                    {
                        append_floating_anchor_text(&mut current_body_block_text, &text);
                    }
                    skip_subtree(&mut r);
                    body_depth = body_depth.saturating_sub(1);
                    continue;
                }
                if name == b"instrText" {
                    let instruction = read_text(&mut r);
                    shape_field_cursor.append_instruction_text(&instruction);
                    if in_body && current_body_block_index.is_some() {
                        anchor_complex_field.append_instruction_text(&instruction);
                    }
                    if in_body {
                        body_depth = body_depth.saturating_sub(1);
                    }
                    continue;
                }
                if name == b"anchor" {
                    let index = shapes.len();
                    let shape = read_floating_shape(
                        &mut r,
                        &e,
                        index,
                        current_body_block_index,
                        cx,
                        &mut shape_field_cursor,
                    );
                    anchor_field_state = anchor_field_state.with_legacy_form_context_from(
                        cx.legacy_forms,
                        shape_field_cursor.next_legacy_form_position(),
                    );
                    shapes.push(shape);
                    if current_body_block_index.is_some() {
                        current_body_block_shapes.push(FloatingShapeAnchorCandidate {
                            shape_index: index,
                            raw_prefix: current_body_block_text.clone(),
                        });
                    }
                    if in_body {
                        body_depth = body_depth.saturating_sub(1);
                    }
                    continue;
                }
                if in_body && current_body_block_index.is_some() && name == b"t" {
                    let text = read_text(&mut r);
                    anchor_complex_field.append_result_text(&text);
                    if !anchor_complex_field.suppresses_result() {
                        append_floating_anchor_text(&mut current_body_block_text, &text);
                    }
                    body_depth = body_depth.saturating_sub(1);
                    continue;
                }
                if in_body && current_body_block_index.is_some() {
                    if let Some(marker) = inline_marker_text(&e) {
                        anchor_complex_field.append_result_text(marker);
                        if !anchor_complex_field.suppresses_result() {
                            append_floating_anchor_text(&mut current_body_block_text, marker);
                        }
                        skip_subtree(&mut r);
                        body_depth = body_depth.saturating_sub(1);
                        continue;
                    }
                }
                if in_body && current_body_block_index.is_some() && name == b"sym" {
                    if let Some(ch) = floating_run_symbol_char(&e) {
                        anchor_complex_field.append_result_char(ch);
                    }
                    if !anchor_complex_field.suppresses_result() {
                        append_floating_anchor_symbol(&mut current_body_block_text, &e);
                    }
                    skip_subtree(&mut r);
                    body_depth = body_depth.saturating_sub(1);
                    continue;
                }
                scan_depth += 1;
            }
            Ok(Event::Empty(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if in_body
                    && current_body_block_index.is_none()
                    && body_block_candidate_depths.contains(&body_depth)
                    && is_body_block(name)
                {
                    next_body_block_index += 1;
                }
                if name == b"anchor" {
                    let index = shapes.len();
                    shapes.push(floating_shape_shell(index, &e, current_body_block_index));
                    if current_body_block_index.is_some() {
                        current_body_block_shapes.push(FloatingShapeAnchorCandidate {
                            shape_index: index,
                            raw_prefix: current_body_block_text.clone(),
                        });
                    }
                } else if in_body && current_body_block_index.is_some() {
                    if name == b"fldChar" {
                        if let Some(text) =
                            anchor_complex_field.apply_field_char(&e, &mut anchor_field_state)
                        {
                            append_floating_anchor_text(&mut current_body_block_text, &text);
                        }
                    } else {
                        if let Some(marker) = inline_marker_text(&e) {
                            anchor_complex_field.append_result_text(marker);
                        } else if name == b"sym" {
                            if let Some(ch) = floating_run_symbol_char(&e) {
                                anchor_complex_field.append_result_char(ch);
                            }
                        }
                        if !anchor_complex_field.suppresses_result() {
                            append_floating_anchor_empty(
                                &mut current_body_block_text,
                                &e,
                                name,
                                &mut anchor_field_state,
                            );
                        }
                    }
                }
                if name == b"fldSimple" {
                    shape_field_cursor.empty_simple_field(&e, cx);
                } else if name == b"fldChar" {
                    shape_field_cursor.apply_field_char(&e, cx);
                }
            }
            Ok(Event::End(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                shape_field_cursor.end_element(name, scan_depth);
                if name == b"body" {
                    in_body = false;
                    body_depth = 0;
                    body_block_candidate_depths.clear();
                    body_block_candidate_depths.push(0);
                    current_body_block_index = None;
                    current_body_block_depth = None;
                    current_body_block_text.clear();
                    current_body_block_shapes.clear();
                    anchor_complex_field = FloatingAnchorComplexField::default();
                    anchor_field_state.clear();
                    alternate_content_stack.clear();
                    scan_depth = scan_depth.saturating_sub(1);
                    continue;
                }
                if name == b"AlternateContent"
                    && alternate_content_stack
                        .last()
                        .is_some_and(|state| state.branch_depth == scan_depth)
                {
                    alternate_content_stack.pop();
                }
                if in_body {
                    let ending_current_body_block = current_body_block_depth == Some(body_depth);
                    if ending_current_body_block {
                        apply_floating_anchor_text_with_offsets(
                            &mut shapes,
                            &current_body_block_shapes,
                            &current_body_block_text,
                        );
                    }
                    if body_block_candidate_depths.last().copied() == Some(body_depth) {
                        body_block_candidate_depths.pop();
                    }
                    body_depth = body_depth.saturating_sub(1);
                    if ending_current_body_block || body_depth == 0 {
                        current_body_block_index = None;
                        current_body_block_depth = None;
                        current_body_block_text.clear();
                        current_body_block_shapes.clear();
                        anchor_complex_field = FloatingAnchorComplexField::default();
                        anchor_field_state.clear();
                    }
                }
                scan_depth = scan_depth.saturating_sub(1);
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    shapes
}

fn append_floating_anchor_text(out: &mut String, text: &str) {
    out.push_str(text);
}

fn append_floating_anchor_symbol(out: &mut String, e: &BytesStart<'_>) {
    if let Some(ch) = floating_run_symbol_char(e) {
        out.push(ch);
    }
}

fn append_floating_anchor_empty(
    out: &mut String,
    e: &BytesStart<'_>,
    name: &[u8],
    field_state: &mut fields::ContextlessFieldState<'_>,
) {
    if name == b"fldSimple" {
        if let Some(text) = computed_floating_anchor_simple_field_text(e, field_state) {
            append_floating_anchor_text(out, &text);
        }
    } else if name == b"sym" {
        append_floating_anchor_symbol(out, e);
    } else if let Some(marker) = inline_marker_text(e) {
        append_floating_anchor_text(out, marker);
    }
}

fn append_floating_anchor_empty_marker(out: &mut String, e: &BytesStart<'_>, name: &[u8]) {
    if name == b"sym" {
        append_floating_anchor_symbol(out, e);
    } else if let Some(marker) = inline_marker_text(e) {
        append_floating_anchor_text(out, marker);
    }
}

fn computed_floating_anchor_simple_field_text(
    e: &BytesStart<'_>,
    field_state: &mut fields::ContextlessFieldState<'_>,
) -> Option<String> {
    let instruction = attr_local_trimmed(e, b"instr")?;
    computed_floating_anchor_field_text(&instruction, field_state)
}

fn computed_floating_anchor_simple_text_form_field_text(
    r: &mut Reader<&[u8]>,
    instruction: &str,
    field_state: &mut fields::ContextlessFieldState<'_>,
) -> Option<String> {
    let current_result = read_floating_anchor_simple_field_current_result(r);
    field_state
        .computed_legacy_text_form_current_result(instruction, &current_result)
        .or_else(|| (!current_result.is_empty()).then_some(current_result))
}

fn read_floating_anchor_simple_field_current_result(r: &mut Reader<&[u8]>) -> String {
    let mut result = String::new();
    let mut depth = 1usize;
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if name == b"t" {
                    result.push_str(&read_text(r));
                } else if name == b"sym" {
                    append_floating_anchor_symbol(&mut result, &e);
                    skip_subtree(r);
                } else if let Some(marker) = inline_marker_text(&e) {
                    result.push_str(marker);
                    skip_subtree(r);
                } else {
                    depth += 1;
                }
            }
            Ok(Event::Empty(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                append_floating_anchor_empty_marker(&mut result, &e, name);
            }
            Ok(Event::End(_)) => {
                depth = depth.saturating_sub(1);
                if depth == 0 {
                    break;
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    result
}

fn computed_floating_anchor_field_text(
    instruction: &str,
    field_state: &mut fields::ContextlessFieldState<'_>,
) -> Option<String> {
    fields::computed_contextless_result(instruction, field_state)
}

#[derive(Default)]
struct FloatingAnchorComplexField {
    depth: usize,
    instruction: String,
    phase: Option<FloatingAnchorComplexFieldPhase>,
    computed_result: Option<String>,
    result_text: String,
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum FloatingAnchorComplexFieldPhase {
    Instruction,
    Result,
}

impl FloatingAnchorComplexField {
    fn apply_field_char(
        &mut self,
        e: &BytesStart<'_>,
        field_state: &mut fields::ContextlessFieldState<'_>,
    ) -> Option<String> {
        match field_char_type(e).as_deref() {
            Some("begin") => {
                if self.depth == 0 {
                    self.instruction.clear();
                    self.result_text.clear();
                    self.phase = Some(FloatingAnchorComplexFieldPhase::Instruction);
                    self.computed_result = None;
                }
                self.depth += 1;
                None
            }
            Some("separate")
                if self.depth == 1
                    && self.phase == Some(FloatingAnchorComplexFieldPhase::Instruction) =>
            {
                self.phase = Some(FloatingAnchorComplexFieldPhase::Result);
                if !is_text_form_field_instruction(&self.instruction) {
                    self.computed_result =
                        computed_floating_anchor_field_text(&self.instruction, field_state);
                }
                self.computed_result.clone()
            }
            Some("end") => {
                let computed_text_form = if self.depth == 1
                    && self.phase == Some(FloatingAnchorComplexFieldPhase::Result)
                    && self.computed_result.is_none()
                    && is_text_form_field_instruction(&self.instruction)
                {
                    field_state
                        .computed_legacy_text_form_current_result(
                            &self.instruction,
                            &self.result_text,
                        )
                        .or_else(|| {
                            (!self.result_text.is_empty()).then_some(self.result_text.clone())
                        })
                } else {
                    None
                };
                if self.depth > 0 {
                    self.depth -= 1;
                    if self.depth == 0 {
                        self.instruction.clear();
                        self.result_text.clear();
                        self.phase = None;
                        self.computed_result = None;
                    }
                }
                computed_text_form
            }
            _ => None,
        }
    }

    fn append_instruction_text(&mut self, text: &str) {
        if self.depth == 1 && self.phase == Some(FloatingAnchorComplexFieldPhase::Instruction) {
            self.instruction.push_str(text);
        }
    }

    fn suppresses_result(&self) -> bool {
        self.depth > 0
            && self.phase == Some(FloatingAnchorComplexFieldPhase::Result)
            && (self.computed_result.is_some() || is_text_form_field_instruction(&self.instruction))
    }

    fn append_result_text(&mut self, text: &str) {
        if self.collects_result_text() {
            self.result_text.push_str(text);
        }
    }

    fn append_result_char(&mut self, ch: char) {
        if self.collects_result_text() {
            self.result_text.push(ch);
        }
    }

    fn collects_result_text(&self) -> bool {
        self.depth > 0
            && self.phase == Some(FloatingAnchorComplexFieldPhase::Result)
            && self.computed_result.is_none()
            && is_text_form_field_instruction(&self.instruction)
    }
}

#[derive(Debug, Clone)]
struct FloatingShapeAnchorCandidate {
    shape_index: usize,
    raw_prefix: String,
}

#[derive(Debug, Clone, Copy)]
struct AlternateContentState {
    branch_depth: usize,
    took_branch: bool,
}

#[derive(Debug, Default)]
struct ShapeFieldCursor {
    next_index: usize,
    ref_index: usize,
    sequence_index: usize,
    sequence_counters: HashMap<String, i64>,
    sequence_heading_scopes: HashMap<(String, u8), u32>,
    autonum_counter: i64,
    listnum_counter: i64,
    style_ref_index: usize,
    page_index: usize,
    page_ref_index: usize,
    note_ref_index: usize,
    section_index: usize,
    formula_index: usize,
    simple_field_depth: Option<usize>,
    simple_text_form: Option<ShapeSimpleTextFormField>,
    complex_field: Option<ShapeFieldCursorField>,
}

#[derive(Debug)]
struct ShapeSimpleTextFormField {
    instruction: String,
    result_text: String,
    legacy_form_index: usize,
    depth: usize,
}

#[derive(Debug)]
struct ShapeFieldCursorField {
    instruction: String,
    phase: ShapeFieldCursorPhase,
    computed_result: Option<String>,
    ref_indexed: bool,
    legacy_form_indexed: bool,
    style_ref_indexed: bool,
    page_indexed: bool,
    page_ref_indexed: bool,
    note_ref_indexed: bool,
    section_indexed: bool,
    formula_indexed: bool,
    result_text: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ShapeFieldCursorPhase {
    Instruction,
    Result,
}

impl ShapeFieldCursor {
    fn start_simple_field(&mut self, e: &BytesStart<'_>, depth: usize, cx: ShapeFieldContext<'_>) {
        if self.simple_field_depth.is_some() {
            return;
        }
        self.simple_field_depth = Some(depth);
        if let Some(instruction) = attr_local(e, b"instr") {
            self.index_simple_field_instruction(&instruction, cx);
        }
    }

    fn empty_simple_field(&mut self, e: &BytesStart<'_>, cx: ShapeFieldContext<'_>) {
        if self.simple_field_depth.is_some() {
            return;
        }
        if let Some(instruction) = attr_local(e, b"instr") {
            self.index_simple_field_instruction(&instruction, cx);
        }
    }

    /// Advance every field-family cursor past one simple-field instruction so
    /// later fields resolve to their correct source-ordered position.
    fn index_simple_field_instruction(&mut self, instruction: &str, cx: ShapeFieldContext<'_>) {
        self.computed_sequence_result(instruction, cx.sequence_headings);
        self.computed_autonum_result(instruction);
        self.computed_listnum_result(instruction);
        self.next_ref_field_context(instruction, cx.ref_positions, cx.note_refs);
        self.next_style_ref_field_position(instruction, cx.style_refs);
        self.next_page_field_position(instruction, cx.page_refs);
        self.next_page_ref_field_context(instruction, cx.page_refs);
        self.next_note_ref_field_position(instruction, cx.note_refs);
        self.next_section_field_position(instruction, cx.sections);
        self.next_table_formula_result(instruction, cx.table_formulas);
        self.next_legacy_form_index(instruction);
    }

    fn end_element(&mut self, name: &[u8], depth: usize) {
        if name == b"fldSimple" && self.simple_field_depth == Some(depth) {
            self.simple_field_depth = None;
        }
    }

    fn start_simple_text_form_field(&mut self, instruction: &str, depth: usize) -> bool {
        if self.simple_text_form.is_some() || !is_text_form_field_instruction(instruction) {
            return false;
        }
        let Some(index) = self.next_legacy_form_index(instruction) else {
            return false;
        };
        self.simple_text_form = Some(ShapeSimpleTextFormField {
            instruction: instruction.to_string(),
            result_text: String::new(),
            legacy_form_index: index,
            depth,
        });
        true
    }

    fn append_simple_text_form_result_text(&mut self, text: &str) -> bool {
        let Some(field) = self.simple_text_form.as_mut() else {
            return false;
        };
        field.result_text.push_str(text);
        true
    }

    fn end_simple_text_form_field(
        &mut self,
        name: &[u8],
        depth: usize,
        legacy_forms: &fields::LegacyFormContext,
    ) -> Option<String> {
        if name != b"fldSimple"
            || self
                .simple_text_form
                .as_ref()
                .is_none_or(|field| field.depth != depth)
        {
            return None;
        }
        let field = self.simple_text_form.take()?;
        fields::computed_legacy_form_result(
            &field.instruction,
            &field.result_text,
            legacy_forms,
            field.legacy_form_index,
        )
        .or_else(|| (!field.result_text.is_empty()).then_some(field.result_text))
    }

    fn in_simple_text_form_field(&self) -> bool {
        self.simple_text_form.is_some()
    }

    fn apply_field_char(
        &mut self,
        e: &BytesStart<'_>,
        cx: ShapeFieldContext<'_>,
    ) -> Option<String> {
        if self.simple_field_depth.is_some() {
            return None;
        }
        match field_char_type(e).as_deref() {
            Some("begin") => {
                self.complex_field = Some(ShapeFieldCursorField {
                    instruction: String::new(),
                    phase: ShapeFieldCursorPhase::Instruction,
                    computed_result: None,
                    ref_indexed: false,
                    legacy_form_indexed: false,
                    style_ref_indexed: false,
                    page_indexed: false,
                    page_ref_indexed: false,
                    note_ref_indexed: false,
                    section_indexed: false,
                    formula_indexed: false,
                    result_text: String::new(),
                });
            }
            Some("separate") => {
                if let Some(field) = self.complex_field.as_mut() {
                    field.phase = ShapeFieldCursorPhase::Result;
                }
            }
            Some("end") => {
                if let Some(field) = self.complex_field.take() {
                    if field.computed_result.is_none() {
                        self.computed_sequence_result(&field.instruction, cx.sequence_headings);
                        self.computed_autonum_result(&field.instruction);
                        self.computed_listnum_result(&field.instruction);
                        if !field.ref_indexed {
                            self.next_ref_field_context(
                                &field.instruction,
                                cx.ref_positions,
                                cx.note_refs,
                            );
                        }
                        if !field.style_ref_indexed {
                            self.next_style_ref_field_position(&field.instruction, cx.style_refs);
                        }
                        if !field.page_indexed {
                            self.next_page_field_position(&field.instruction, cx.page_refs);
                        }
                        if !field.page_ref_indexed {
                            self.next_page_ref_field_context(&field.instruction, cx.page_refs);
                        }
                        if !field.note_ref_indexed {
                            self.next_note_ref_field_position(&field.instruction, cx.note_refs);
                        }
                        if !field.section_indexed {
                            self.next_section_field_position(&field.instruction, cx.sections);
                        }
                        if !field.formula_indexed {
                            self.next_table_formula_result(&field.instruction, cx.table_formulas);
                        }
                        if !field.legacy_form_indexed {
                            self.next_legacy_form_index(&field.instruction);
                        }
                    }
                    return field.computed_result;
                }
            }
            _ => {}
        }
        None
    }

    fn append_instruction_text(&mut self, text: &str) {
        if self.simple_field_depth.is_some() {
            return;
        }
        if let Some(field) = self.complex_field.as_mut() {
            if field.phase == ShapeFieldCursorPhase::Instruction {
                field.instruction.push_str(text);
            }
        }
    }

    fn current_complex_instruction(&self) -> Option<&str> {
        let field = self.complex_field.as_ref()?;
        (field.phase == ShapeFieldCursorPhase::Result).then_some(field.instruction.as_str())
    }

    fn current_complex_style_ref_position(
        &mut self,
        style_refs: &fields::StyleRefContext,
    ) -> Option<fields::StyleRefFieldPosition> {
        let field = self.complex_field.as_mut()?;
        if field.phase != ShapeFieldCursorPhase::Result || field.style_ref_indexed {
            return None;
        }
        let instruction = field.instruction.clone();
        if !fields::is_style_ref_field_instruction(&instruction) {
            return None;
        }
        field.style_ref_indexed = true;
        self.next_style_ref_field_position(&instruction, style_refs)
    }

    fn current_complex_page_field_position(
        &mut self,
        page_refs: &fields::PageRefContext,
    ) -> Option<fields::PageRefPosition> {
        let instruction = {
            let field = self.complex_field.as_ref()?;
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.page_indexed
            {
                return None;
            }
            field.instruction.clone()
        };
        let position = self.next_page_field_position(&instruction, page_refs);
        if let Some(field) = self.complex_field.as_mut() {
            if FieldKind::from_instruction(&instruction) == FieldKind::Page {
                field.page_indexed = true;
            }
        }
        position
    }

    fn current_complex_ref_field_context(
        &mut self,
        ref_positions: &fields::RefPositionContext,
        note_refs: &fields::NoteRefContext,
    ) -> (
        Option<fields::RefFieldPosition>,
        Option<fields::NoteRefFieldPosition>,
    ) {
        let instruction = {
            let Some(field) = self.complex_field.as_ref() else {
                return (None, None);
            };
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.ref_indexed
            {
                return (None, None);
            }
            field.instruction.clone()
        };
        let context = self.next_ref_field_context(&instruction, ref_positions, note_refs);
        if let Some(field) = self.complex_field.as_mut() {
            if fields::is_ref_position_field_instruction(&instruction) {
                field.ref_indexed = true;
            }
        }
        context
    }

    fn current_complex_page_ref_field_context(
        &mut self,
        page_refs: &fields::PageRefContext,
    ) -> (Option<fields::PageRefPosition>, Option<usize>) {
        let instruction = {
            let Some(field) = self.complex_field.as_ref() else {
                return (None, None);
            };
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.page_ref_indexed
            {
                return (None, None);
            }
            field.instruction.clone()
        };
        let context = self.next_page_ref_field_context(&instruction, page_refs);
        if let Some(field) = self.complex_field.as_mut() {
            if FieldKind::from_instruction(&instruction) == FieldKind::PageRef {
                field.page_ref_indexed = true;
            }
        }
        context
    }

    fn current_complex_note_ref_field_position(
        &mut self,
        note_refs: &fields::NoteRefContext,
    ) -> Option<fields::NoteRefFieldPosition> {
        let instruction = {
            let field = self.complex_field.as_ref()?;
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.note_ref_indexed
            {
                return None;
            }
            field.instruction.clone()
        };
        let position = self.next_note_ref_field_position(&instruction, note_refs);
        if let Some(field) = self.complex_field.as_mut() {
            if FieldKind::from_instruction(&instruction) == FieldKind::NoteRef {
                field.note_ref_indexed = true;
            }
        }
        position
    }

    fn current_complex_section_field_position(
        &mut self,
        sections: &fields::SectionContext,
    ) -> Option<fields::SectionFieldPosition> {
        let instruction = {
            let field = self.complex_field.as_ref()?;
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.section_indexed
            {
                return None;
            }
            field.instruction.clone()
        };
        let position = self.next_section_field_position(&instruction, sections);
        if let Some(field) = self.complex_field.as_mut() {
            if fields::is_section_field_instruction(&instruction) {
                field.section_indexed = true;
            }
        }
        position
    }

    fn current_complex_table_formula_result(
        &mut self,
        table_formulas: &fields::TableFormulaContext,
    ) -> Option<String> {
        let instruction = {
            let field = self.complex_field.as_ref()?;
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.formula_indexed
            {
                return None;
            }
            field.instruction.clone()
        };
        let result = self.next_table_formula_result(&instruction, table_formulas);
        if let Some(field) = self.complex_field.as_mut() {
            if is_table_formula_field_instruction(&instruction) {
                field.formula_indexed = true;
            }
        }
        result
    }

    fn set_complex_result(&mut self, text: String) {
        if let Some(field) = self.complex_field.as_mut() {
            if field.phase == ShapeFieldCursorPhase::Result {
                field.computed_result = Some(text);
            }
        }
    }

    fn append_complex_result_text(&mut self, text: &str) {
        if let Some(field) = self.complex_field.as_mut() {
            if field.phase == ShapeFieldCursorPhase::Result && field.computed_result.is_none() {
                field.result_text.push_str(text);
            }
        }
    }

    fn computed_complex_source_order_result(
        &mut self,
        sequence_headings: &fields::SequenceHeadingContext,
    ) -> Option<String> {
        let field = self.complex_field.as_ref()?;
        if field.phase != ShapeFieldCursorPhase::Result || field.computed_result.is_some() {
            return None;
        }
        let instruction = field.instruction.clone();
        self.computed_sequence_result(&instruction, sequence_headings)
            .or_else(|| self.computed_autonum_result(&instruction))
            .or_else(|| self.computed_listnum_result(&instruction))
    }

    fn computed_complex_legacy_form_result(
        &mut self,
        legacy_forms: &fields::LegacyFormContext,
        include_empty_text_form: bool,
    ) -> Option<String> {
        let (instruction, current_result) = {
            let field = self.complex_field.as_ref()?;
            if field.phase != ShapeFieldCursorPhase::Result
                || field.computed_result.is_some()
                || field.legacy_form_indexed
            {
                return None;
            }
            (field.instruction.clone(), field.result_text.clone())
        };
        let is_text_form = matches!(
            FieldKind::from_instruction(&instruction),
            FieldKind::FormField(kind) if kind == "FORMTEXT"
        );
        if is_text_form && (!include_empty_text_form || !current_result.is_empty()) {
            return None;
        }
        let index = self.next_legacy_form_index(&instruction)?;
        if let Some(field) = self.complex_field.as_mut() {
            field.legacy_form_indexed = true;
        }
        fields::computed_legacy_form_result(&instruction, &current_result, legacy_forms, index)
    }

    fn suppresses_complex_result(&self) -> bool {
        self.complex_field.as_ref().is_some_and(|field| {
            field.phase == ShapeFieldCursorPhase::Result && field.computed_result.is_some()
        })
    }

    fn next_legacy_form_index(&mut self, instruction: &str) -> Option<usize> {
        if !is_legacy_form_field_instruction(instruction) {
            return None;
        }
        let index = self.next_index;
        self.next_index += 1;
        Some(index)
    }

    fn next_legacy_form_position(&self) -> usize {
        self.next_index
    }

    fn next_style_ref_field_position(
        &mut self,
        instruction: &str,
        style_refs: &fields::StyleRefContext,
    ) -> Option<fields::StyleRefFieldPosition> {
        if !fields::is_style_ref_field_instruction(instruction) {
            return None;
        }
        let index = self.style_ref_index;
        self.style_ref_index += 1;
        style_refs.field_position(index)
    }

    fn next_ref_field_context(
        &mut self,
        instruction: &str,
        ref_positions: &fields::RefPositionContext,
        note_refs: &fields::NoteRefContext,
    ) -> (
        Option<fields::RefFieldPosition>,
        Option<fields::NoteRefFieldPosition>,
    ) {
        if !fields::is_ref_position_field_instruction(instruction) {
            return (None, None);
        }
        let index = self.ref_index;
        self.ref_index += 1;
        (
            ref_positions.field_position(index),
            note_refs.ref_field_position(index),
        )
    }

    fn next_page_field_position(
        &mut self,
        instruction: &str,
        page_refs: &fields::PageRefContext,
    ) -> Option<fields::PageRefPosition> {
        if FieldKind::from_instruction(instruction) != FieldKind::Page {
            return None;
        }
        let index = self.page_index;
        self.page_index += 1;
        page_refs.page_field_position(index)
    }

    fn next_page_ref_field_context(
        &mut self,
        instruction: &str,
        page_refs: &fields::PageRefContext,
    ) -> (Option<fields::PageRefPosition>, Option<usize>) {
        if FieldKind::from_instruction(instruction) != FieldKind::PageRef {
            return (None, None);
        }
        let index = self.page_ref_index;
        self.page_ref_index += 1;
        (
            page_refs.field_position(index),
            page_refs.field_order(index),
        )
    }

    fn next_note_ref_field_position(
        &mut self,
        instruction: &str,
        note_refs: &fields::NoteRefContext,
    ) -> Option<fields::NoteRefFieldPosition> {
        if FieldKind::from_instruction(instruction) != FieldKind::NoteRef {
            return None;
        }
        let index = self.note_ref_index;
        self.note_ref_index += 1;
        note_refs.field_position(index)
    }

    fn next_section_field_position(
        &mut self,
        instruction: &str,
        sections: &fields::SectionContext,
    ) -> Option<fields::SectionFieldPosition> {
        if !fields::is_section_field_instruction(instruction) {
            return None;
        }
        let index = self.section_index;
        self.section_index += 1;
        sections.field_position(index)
    }

    fn next_table_formula_result(
        &mut self,
        instruction: &str,
        table_formulas: &fields::TableFormulaContext,
    ) -> Option<String> {
        if !is_table_formula_field_instruction(instruction) {
            return None;
        }
        let index = self.formula_index;
        self.formula_index += 1;
        table_formulas.field_result(index)
    }

    fn computed_sequence_result(
        &mut self,
        instruction: &str,
        sequence_headings: &fields::SequenceHeadingContext,
    ) -> Option<String> {
        if FieldKind::from_instruction(instruction) != FieldKind::Sequence {
            return None;
        }
        let index = self.sequence_index;
        self.sequence_index += 1;
        let heading_scope = sequence_headings.field_scope(index);
        fields::computed_sequence_result_with_heading_scope(
            instruction,
            &mut self.sequence_counters,
            heading_scope,
            &mut self.sequence_heading_scopes,
        )
    }

    fn computed_autonum_result(&mut self, instruction: &str) -> Option<String> {
        if !matches!(
            FieldKind::from_instruction(instruction),
            FieldKind::Numbering(kind)
                if kind == "AUTONUM"
                    || kind == "AUTONUMLGL"
                    || kind == "AUTONUMOUT"
                    || kind == "BIDIOUTLINE"
        ) {
            return None;
        }
        fields::computed_numbering_result(instruction, &mut self.autonum_counter)
    }

    fn computed_listnum_result(&mut self, instruction: &str) -> Option<String> {
        if !matches!(
            FieldKind::from_instruction(instruction),
            FieldKind::Numbering(kind) if kind == "LISTNUM"
        ) {
            return None;
        }
        fields::computed_listnum_result(instruction, &mut self.listnum_counter)
    }
}

fn is_legacy_form_field_instruction(instruction: &str) -> bool {
    matches!(
        FieldKind::from_instruction(instruction),
        FieldKind::FormField(_)
    )
}

fn is_text_form_field_instruction(instruction: &str) -> bool {
    matches!(
        FieldKind::from_instruction(instruction),
        FieldKind::FormField(kind) if kind == "FORMTEXT"
    )
}

fn is_table_formula_field_instruction(instruction: &str) -> bool {
    matches!(
        FieldKind::from_instruction(instruction),
        FieldKind::Dynamic(kind) if kind == "="
    )
}

fn should_skip_redundant_alternate_branch(
    stack: &mut [AlternateContentState],
    body_depth: usize,
    name: &[u8],
) -> bool {
    if !matches!(name, b"Choice" | b"Fallback") {
        return false;
    }
    let Some(state) = stack.last_mut() else {
        return false;
    };
    if state.branch_depth != body_depth {
        return false;
    }
    if state.took_branch {
        true
    } else {
        state.took_branch = true;
        false
    }
}

fn apply_floating_anchor_text_with_offsets(
    shapes: &mut [FloatingShape],
    shape_indices: &[FloatingShapeAnchorCandidate],
    raw: &str,
) {
    if shape_indices.is_empty() {
        return;
    }
    let text = text::finalize(raw);
    if text.is_empty() {
        return;
    }
    for index in shape_indices {
        if let Some(shape) = shapes.get_mut(index.shape_index) {
            shape.anchor_text = Some(text.clone());
            shape.anchor_char_offset = normalized_anchor_char_offset(raw, &index.raw_prefix);
        }
    }
}

fn normalized_anchor_char_offset(raw: &str, raw_prefix: &str) -> Option<usize> {
    let suffix = raw.get(raw_prefix.len()..)?;
    const MARKER: char = '\u{E000}';
    if raw.contains(MARKER) {
        return None;
    }
    let mut marked = String::with_capacity(raw.len() + MARKER.len_utf8());
    marked.push_str(raw_prefix);
    marked.push(MARKER);
    marked.push_str(suffix);
    let normalized = text::finalize(&marked);
    let marker_byte = normalized.find(MARKER)?;
    Some(normalized[..marker_byte].chars().count())
}

fn read_floating_shape(
    r: &mut Reader<&[u8]>,
    start: &BytesStart<'_>,
    index: usize,
    anchor_block_index: Option<usize>,
    cx: ShapeFieldContext<'_>,
    shape_field_cursor: &mut ShapeFieldCursor,
) -> FloatingShape {
    let mut shape = floating_shape_shell(index, start, anchor_block_index);
    let mut text_box_depth = 0usize;
    let mut shape_text = String::new();
    let mut field_bookmarks = HashMap::new();
    let mut outline_depth = 0usize;
    let mut solid_fill = None;
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if text_box_depth > 0 {
                    match name {
                        b"t" => {
                            let text = read_text(r);
                            if !shape_field_cursor.append_simple_text_form_result_text(&text)
                                && !shape_field_cursor.suppresses_complex_result()
                            {
                                shape_field_cursor.append_complex_result_text(&text);
                                append_shape_text(&mut shape_text, &text);
                            }
                        }
                        b"fldSimple" => {
                            if shape_field_cursor.suppresses_complex_result() {
                                skip_subtree(r);
                            } else if shape_field_cursor.in_simple_text_form_field() {
                                text_box_depth += 1;
                            } else if append_shape_simple_field(
                                &mut shape_text,
                                &e,
                                cx,
                                &mut field_bookmarks,
                                shape_field_cursor,
                                Some(text_box_depth + 1),
                            ) {
                                skip_subtree(r);
                            } else {
                                text_box_depth += 1;
                            }
                        }
                        b"fldChar" => {
                            apply_shape_field_char(
                                &mut shape_text,
                                &e,
                                cx,
                                &mut field_bookmarks,
                                shape_field_cursor,
                            );
                            text_box_depth += 1;
                        }
                        b"instrText" => {
                            shape_field_cursor.append_instruction_text(&read_text(r));
                        }
                        b"sym" => {
                            if let Some(text) = shape_symbol_text(&e) {
                                if !shape_field_cursor.append_simple_text_form_result_text(&text)
                                    && !shape_field_cursor.suppresses_complex_result()
                                {
                                    shape_field_cursor.append_complex_result_text(&text);
                                    append_shape_text(&mut shape_text, &text);
                                }
                            }
                            skip_subtree(r);
                        }
                        b"tab" | b"br" | b"cr" | b"noBreakHyphen" | b"softHyphen" => {
                            if let Some(text) = shape_empty_text(&e, name) {
                                if shape_field_cursor.append_simple_text_form_result_text(&text) {
                                    skip_subtree(r);
                                    continue;
                                }
                            }
                            if !shape_field_cursor.suppresses_complex_result() {
                                append_shape_empty(&mut shape_text, &e, name);
                            }
                            skip_subtree(r);
                        }
                        _ => text_box_depth += 1,
                    }
                    continue;
                }
                enter_shape_color_context(name, &mut outline_depth, &mut solid_fill);
                match name {
                    b"positionH" => shape.horizontal_position = Some(read_shape_position(r, &e)),
                    b"positionV" => shape.vertical_position = Some(read_shape_position(r, &e)),
                    b"simplePos" => shape.simple_position = shape_point(&e),
                    b"extent" => shape.extent = shape_extent(&e),
                    b"effectExtent" => shape.effect_extent = shape_effect_extent(&e),
                    b"docPr" => apply_shape_doc_pr(&mut shape, &e),
                    b"prstGeom" => apply_shape_preset_geometry(&mut shape, &e),
                    b"srgbClr" => apply_shape_srgb_color(&mut shape, &e, solid_fill),
                    b"txbxContent" => text_box_depth = 1,
                    name if is_shape_wrapping_name(name) => {
                        shape.wrapping = Some(read_shape_wrapping(r, &e));
                    }
                    _ => {}
                }
            }
            Ok(Event::Empty(e)) => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if text_box_depth > 0 {
                    if name == b"fldChar" {
                        apply_shape_field_char(
                            &mut shape_text,
                            &e,
                            cx,
                            &mut field_bookmarks,
                            shape_field_cursor,
                        );
                    }
                    if let Some(text) = shape_empty_text(&e, name) {
                        if shape_field_cursor.append_simple_text_form_result_text(&text) {
                            continue;
                        }
                    }
                    if !shape_field_cursor.suppresses_complex_result()
                        && (name != b"fldSimple"
                            || !append_shape_simple_field(
                                &mut shape_text,
                                &e,
                                cx,
                                &mut field_bookmarks,
                                shape_field_cursor,
                                None,
                            ))
                    {
                        append_shape_empty(&mut shape_text, &e, name);
                    }
                    continue;
                }
                if name == b"srgbClr" {
                    apply_shape_srgb_color(&mut shape, &e, solid_fill);
                }
                match name {
                    b"positionH" => shape.horizontal_position = Some(empty_shape_position(&e)),
                    b"positionV" => shape.vertical_position = Some(empty_shape_position(&e)),
                    b"simplePos" => shape.simple_position = shape_point(&e),
                    b"extent" => shape.extent = shape_extent(&e),
                    b"effectExtent" => shape.effect_extent = shape_effect_extent(&e),
                    b"docPr" => apply_shape_doc_pr(&mut shape, &e),
                    b"prstGeom" => apply_shape_preset_geometry(&mut shape, &e),
                    name if is_shape_wrapping_name(name) => {
                        shape.wrapping = Some(shape_wrapping(&e));
                    }
                    _ => {}
                }
            }
            Ok(Event::End(e)) if local(e.name().as_ref()) == b"anchor" => break,
            Ok(Event::End(e)) if text_box_depth > 0 => {
                let qname = e.name();
                let name = local(qname.as_ref());
                if let Some(text) = shape_field_cursor.end_simple_text_form_field(
                    name,
                    text_box_depth,
                    cx.legacy_forms,
                ) {
                    if !text.is_empty() {
                        append_shape_text(&mut shape_text, &text);
                    }
                }
                if name == b"p" {
                    append_shape_paragraph_break(&mut shape_text);
                }
                text_box_depth = text_box_depth.saturating_sub(1);
            }
            Ok(Event::End(_)) => {
                leave_shape_color_context(&mut outline_depth, &mut solid_fill);
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    shape.text = finalized_shape_text(shape_text);
    shape
}

fn floating_shape_shell(
    index: usize,
    start: &BytesStart<'_>,
    anchor_block_index: Option<usize>,
) -> FloatingShape {
    FloatingShape {
        id: format!("docx-floating-shape-{index}"),
        name: None,
        description: None,
        text: None,
        preset_geometry: None,
        fill_color: None,
        outline_color: None,
        simple_position_enabled: attr_bool(start, b"simplePos"),
        simple_position: None,
        effect_extent: None,
        anchor_block_index,
        anchor_text: None,
        anchor_char_offset: None,
        extent: None,
        horizontal_position: None,
        vertical_position: None,
        relative_height: attr_i64(start, b"relativeHeight"),
        behind_doc: attr_bool(start, b"behindDoc"),
        layout_in_cell: attr_bool(start, b"layoutInCell"),
        locked: attr_bool(start, b"locked"),
        allow_overlap: attr_bool(start, b"allowOverlap"),
        distance: ShapeDistance {
            top_emu: attr_i64(start, b"distT"),
            bottom_emu: attr_i64(start, b"distB"),
            left_emu: attr_i64(start, b"distL"),
            right_emu: attr_i64(start, b"distR"),
        },
        wrapping: None,
    }
}

fn is_body_block(name: &[u8]) -> bool {
    matches!(name, b"p" | b"tbl")
}

fn is_transparent_body_block_container(name: &[u8]) -> bool {
    matches!(
        name,
        b"sdt"
            | b"sdtContent"
            | b"customXml"
            | b"smartTag"
            | b"ins"
            | b"moveTo"
            | b"AlternateContent"
            | b"Choice"
            | b"Fallback"
    )
}

fn is_old_revision_content(name: &[u8]) -> bool {
    matches!(name, b"del" | b"moveFrom")
}

fn append_shape_text(out: &mut String, text: &str) {
    let previous_is_space = matches!(out.chars().last(), Some(' ' | '\n' | '\t'));
    let previous_is_joiner = out.ends_with('-') || out.ends_with('\u{00ad}');
    let next_is_space = matches!(text.chars().next(), Some(' ' | '\n' | '\t'));
    if !out.is_empty() && !previous_is_space && !previous_is_joiner && !next_is_space {
        out.push(' ');
    }
    out.push_str(text);
}

fn append_shape_symbol(out: &mut String, e: &BytesStart<'_>) {
    if let Some(text) = shape_symbol_text(e) {
        append_shape_text(out, &text);
    }
}

fn shape_symbol_text(e: &BytesStart<'_>) -> Option<String> {
    let ch = floating_run_symbol_char(e)?;
    let mut buf = [0; 4];
    Some(ch.encode_utf8(&mut buf).to_string())
}

fn shape_empty_text(e: &BytesStart<'_>, name: &[u8]) -> Option<String> {
    match name {
        b"sym" => shape_symbol_text(e),
        b"tab" => Some("\t".to_string()),
        b"br" | b"cr" => Some("\n".to_string()),
        b"noBreakHyphen" => Some("-".to_string()),
        b"softHyphen" => Some("\u{00ad}".to_string()),
        _ => None,
    }
}

fn computed_shape_ref_result(
    instruction: &str,
    cx: ShapeFieldContext<'_>,
    field_bookmarks: &HashMap<String, String>,
    ref_position: Option<fields::RefFieldPosition>,
    note_ref_position: Option<fields::NoteRefFieldPosition>,
) -> Option<String> {
    let ctx = fields::RefResultContext {
        bookmarks: cx.document_bookmarks,
        ref_positions: cx.ref_positions,
        ref_numbers: cx.ref_numbers,
        note_refs: cx.note_refs,
        field_bookmarks,
    };
    fields::computed_ref_result(instruction, &ctx, ref_position.clone(), note_ref_position).or_else(
        || {
            fields::computed_direct_bookmark_ref_result(
                instruction,
                &ctx,
                ref_position,
                note_ref_position,
            )
        },
    )
}

fn computed_shape_context_field_result(
    instruction: &str,
    cx: ShapeFieldContext<'_>,
    field_bookmarks: &mut HashMap<String, String>,
    positions: ShapeFieldPositions,
) -> Option<String> {
    let properties = cx.properties;
    let document_bookmarks = cx.document_bookmarks;
    if update_field_bookmarks_from_instruction(instruction, field_bookmarks) {
        return Some(String::new());
    }
    fields::computed_formula_result_with_bookmark_context(
        instruction,
        document_bookmarks,
        field_bookmarks,
    )
    .or_else(|| fields::computed_page_result(instruction, positions.page_position))
    .or_else(|| {
        fields::computed_page_ref_result(
            instruction,
            cx.page_refs,
            positions.page_ref_position,
            positions.page_ref_order,
        )
    })
    .or_else(|| {
        fields::computed_note_ref_result(instruction, cx.note_refs, positions.note_ref_position)
    })
    .or_else(|| fields::computed_section_result(instruction, positions.section_position))
    .or_else(|| {
        fields::computed_if_compare_result_with_bookmark_context(
            instruction,
            document_bookmarks,
            field_bookmarks,
        )
    })
    .or_else(|| {
        fields::computed_merge_control_result_with_bookmark_context(
            instruction,
            document_bookmarks,
            field_bookmarks,
        )
    })
    .or_else(|| {
        computed_shape_ref_result(
            instruction,
            cx,
            field_bookmarks,
            positions.ref_position,
            positions.ref_note_position,
        )
    })
    .or_else(|| fields::computed_dynamic_result_with_bookmarks(instruction, field_bookmarks))
    .or_else(|| fields::computed_toc_entry_result(instruction))
    .or_else(|| {
        fields::computed_document_info_result(
            instruction,
            properties.core,
            properties.custom,
            properties.variables,
            properties.extended,
            properties.file_size_bytes,
        )
    })
    .or_else(|| fields::computed_revision_number_result(instruction, properties.core))
    .or_else(|| {
        fields::computed_style_ref_result(instruction, cx.style_refs, positions.style_ref_position)
    })
    .or_else(|| fields::computed_display_result(instruction))
    .or_else(|| fields::computed_action_result(instruction))
    .or_else(|| fields::computed_reference_index_result(instruction))
    .or_else(|| fields::computed_toc_result(instruction, cx.toc_entries, cx.bookmark_names))
}

fn apply_shape_field_char(
    out: &mut String,
    e: &BytesStart<'_>,
    cx: ShapeFieldContext<'_>,
    field_bookmarks: &mut HashMap<String, String>,
    shape_field_cursor: &mut ShapeFieldCursor,
) {
    if field_char_type(e).as_deref() == Some("end") {
        let computed =
            shape_field_cursor.computed_complex_legacy_form_result(cx.legacy_forms, true);
        if let Some(text) = computed {
            shape_field_cursor.set_complex_result(text);
        }
    }
    let completed = shape_field_cursor.apply_field_char(e, cx);
    let computed = shape_field_cursor
        .current_complex_instruction()
        .map(str::to_string)
        .and_then(|instruction| {
            let page_position =
                shape_field_cursor.current_complex_page_field_position(cx.page_refs);
            let (ref_position, ref_note_position) = shape_field_cursor
                .current_complex_ref_field_context(cx.ref_positions, cx.note_refs);
            let (page_ref_position, page_ref_order) =
                shape_field_cursor.current_complex_page_ref_field_context(cx.page_refs);
            let note_ref_position =
                shape_field_cursor.current_complex_note_ref_field_position(cx.note_refs);
            let section_position =
                shape_field_cursor.current_complex_section_field_position(cx.sections);
            let style_ref_position =
                shape_field_cursor.current_complex_style_ref_position(cx.style_refs);
            shape_field_cursor
                .current_complex_table_formula_result(cx.table_formulas)
                .or_else(|| {
                    computed_shape_context_field_result(
                        &instruction,
                        cx,
                        field_bookmarks,
                        ShapeFieldPositions {
                            ref_position,
                            page_position,
                            page_ref_position,
                            page_ref_order,
                            note_ref_position,
                            ref_note_position,
                            section_position,
                            style_ref_position,
                        },
                    )
                })
        })
        .or_else(|| shape_field_cursor.computed_complex_source_order_result(cx.sequence_headings))
        .or_else(|| shape_field_cursor.computed_complex_legacy_form_result(cx.legacy_forms, false));
    if let Some(text) = computed {
        shape_field_cursor.set_complex_result(text);
    }
    if let Some(text) = completed {
        if !text.is_empty() {
            append_shape_text(out, &text);
        }
    }
}

fn append_shape_simple_field(
    out: &mut String,
    e: &BytesStart<'_>,
    cx: ShapeFieldContext<'_>,
    field_bookmarks: &mut HashMap<String, String>,
    shape_field_cursor: &mut ShapeFieldCursor,
    simple_text_form_depth: Option<usize>,
) -> bool {
    let Some(instruction) = attr_local(e, b"instr") else {
        return false;
    };
    if update_field_bookmarks_from_instruction(&instruction, field_bookmarks) {
        return true;
    }
    if let Some(depth) = simple_text_form_depth {
        if shape_field_cursor.start_simple_text_form_field(&instruction, depth) {
            return false;
        }
    }
    let page_position = shape_field_cursor.next_page_field_position(&instruction, cx.page_refs);
    let (ref_position, ref_note_position) =
        shape_field_cursor.next_ref_field_context(&instruction, cx.ref_positions, cx.note_refs);
    let (page_ref_position, page_ref_order) =
        shape_field_cursor.next_page_ref_field_context(&instruction, cx.page_refs);
    let note_ref_position =
        shape_field_cursor.next_note_ref_field_position(&instruction, cx.note_refs);
    let section_position =
        shape_field_cursor.next_section_field_position(&instruction, cx.sections);
    let style_ref_position =
        shape_field_cursor.next_style_ref_field_position(&instruction, cx.style_refs);
    let text = shape_field_cursor
        .next_table_formula_result(&instruction, cx.table_formulas)
        .or_else(|| {
            computed_shape_context_field_result(
                &instruction,
                cx,
                field_bookmarks,
                ShapeFieldPositions {
                    ref_position,
                    page_position,
                    page_ref_position,
                    page_ref_order,
                    note_ref_position,
                    ref_note_position,
                    section_position,
                    style_ref_position,
                },
            )
        })
        .or_else(|| shape_field_cursor.computed_sequence_result(&instruction, cx.sequence_headings))
        .or_else(|| shape_field_cursor.computed_autonum_result(&instruction))
        .or_else(|| shape_field_cursor.computed_listnum_result(&instruction))
        .or_else(|| {
            let index = shape_field_cursor.next_legacy_form_index(&instruction)?;
            fields::computed_legacy_form_result(&instruction, "", cx.legacy_forms, index)
        });
    let Some(text) = text else {
        return false;
    };
    if !text.is_empty() {
        append_shape_text(out, &text);
    }
    true
}

fn append_shape_empty(out: &mut String, e: &BytesStart<'_>, name: &[u8]) {
    match name {
        b"sym" => append_shape_symbol(out, e),
        b"tab" => out.push('\t'),
        b"br" | b"cr" => out.push('\n'),
        b"noBreakHyphen" => out.push('-'),
        b"softHyphen" => out.push('\u{00ad}'),
        _ => {}
    }
}

fn append_shape_paragraph_break(out: &mut String) {
    if !out.is_empty() && !out.ends_with('\n') {
        out.push('\n');
    }
}

fn finalized_shape_text(text: String) -> Option<String> {
    let text = text.trim_matches('\n').to_string();
    (!text.trim().is_empty()).then_some(text)
}

fn floating_run_symbol_char(e: &BytesStart<'_>) -> Option<char> {
    let value = attr_local_trimmed(e, b"char")?;
    let font = attr_local_trimmed(e, b"font");
    fields::computed_run_symbol_char(font.as_deref(), &value)
}

fn empty_shape_position(start: &BytesStart<'_>) -> ShapePosition {
    ShapePosition {
        relative_from: attr_local_trimmed(start, b"relativeFrom"),
        offset_emu: None,
        align: None,
    }
}

fn read_shape_position(r: &mut Reader<&[u8]>, start: &BytesStart<'_>) -> ShapePosition {
    let mut position = empty_shape_position(start);
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) if local(e.name().as_ref()) == b"posOffset" => {
                position.offset_emu = read_i64_text(r);
            }
            Ok(Event::Start(e)) if local(e.name().as_ref()) == b"align" => {
                position.align = Some(read_text(r));
            }
            Ok(Event::End(e))
                if matches!(local(e.name().as_ref()), b"positionH" | b"positionV") =>
            {
                break;
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    position
}

fn shape_extent(e: &BytesStart<'_>) -> Option<ShapeExtent> {
    Some(ShapeExtent {
        cx_emu: attr_i64(e, b"cx")?,
        cy_emu: attr_i64(e, b"cy")?,
    })
}

fn shape_point(e: &BytesStart<'_>) -> Option<ShapePoint> {
    Some(ShapePoint {
        x_emu: attr_i64(e, b"x")?,
        y_emu: attr_i64(e, b"y")?,
    })
}

fn shape_effect_extent(e: &BytesStart<'_>) -> Option<ShapeEffectExtent> {
    Some(ShapeEffectExtent {
        left_emu: attr_i64(e, b"l")?,
        top_emu: attr_i64(e, b"t")?,
        right_emu: attr_i64(e, b"r")?,
        bottom_emu: attr_i64(e, b"b")?,
    })
}

fn is_shape_wrapping_name(name: &[u8]) -> bool {
    matches!(
        name,
        b"wrapNone" | b"wrapSquare" | b"wrapTight" | b"wrapThrough" | b"wrapTopAndBottom"
    )
}

fn shape_wrapping(e: &BytesStart<'_>) -> ShapeWrapping {
    let kind = match local(e.name().as_ref()) {
        b"wrapNone" => "none",
        b"wrapSquare" => "square",
        b"wrapTight" => "tight",
        b"wrapThrough" => "through",
        b"wrapTopAndBottom" => "topAndBottom",
        _ => "unknown",
    };
    ShapeWrapping {
        kind: kind.to_string(),
        text: attr_local_trimmed(e, b"wrapText"),
        distance: ShapeDistance {
            top_emu: attr_i64(e, b"distT"),
            bottom_emu: attr_i64(e, b"distB"),
            left_emu: attr_i64(e, b"distL"),
            right_emu: attr_i64(e, b"distR"),
        },
        polygon: Vec::new(),
    }
}

fn read_shape_wrapping(r: &mut Reader<&[u8]>, start: &BytesStart<'_>) -> ShapeWrapping {
    let mut wrapping = shape_wrapping(start);
    let qname = start.name();
    let wrap_name = local(qname.as_ref()).to_vec();
    loop {
        match r.read_event() {
            Ok(Event::Empty(e)) if is_wrap_polygon_point(local(e.name().as_ref())) => {
                if let Some(point) = shape_point(&e) {
                    wrapping.polygon.push(point);
                }
            }
            Ok(Event::Start(e)) if is_wrap_polygon_point(local(e.name().as_ref())) => {
                if let Some(point) = shape_point(&e) {
                    wrapping.polygon.push(point);
                }
                skip_subtree(r);
            }
            Ok(Event::Start(e)) if local(e.name().as_ref()) == b"wrapPolygon" => {}
            Ok(Event::Start(_)) => skip_subtree(r),
            Ok(Event::End(e)) if local(e.name().as_ref()) == wrap_name.as_slice() => break,
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    wrapping
}

fn is_wrap_polygon_point(name: &[u8]) -> bool {
    matches!(name, b"start" | b"lineTo")
}

fn apply_shape_doc_pr(shape: &mut FloatingShape, e: &BytesStart<'_>) {
    if let Some(id) = attr_local_trimmed(e, b"id") {
        shape.id = id;
    }
    shape.name = attr_local_trimmed(e, b"name");
    shape.description = attr_local_trimmed(e, b"descr");
}

fn apply_shape_preset_geometry(shape: &mut FloatingShape, e: &BytesStart<'_>) {
    if shape.preset_geometry.is_none() {
        shape.preset_geometry = attr_local_trimmed(e, b"prst");
    }
}

#[derive(Debug, Clone, Copy)]
enum ShapeColorTarget {
    Fill,
    Outline,
}

fn enter_shape_color_context(
    name: &[u8],
    outline_depth: &mut usize,
    solid_fill: &mut Option<(usize, ShapeColorTarget)>,
) {
    if *outline_depth > 0 || name == b"ln" {
        *outline_depth += 1;
    }
    if name == b"solidFill" {
        let target = if *outline_depth > 0 {
            ShapeColorTarget::Outline
        } else {
            ShapeColorTarget::Fill
        };
        *solid_fill = Some((1, target));
    } else if let Some((depth, _)) = solid_fill.as_mut() {
        *depth += 1;
    }
}

fn leave_shape_color_context(
    outline_depth: &mut usize,
    solid_fill: &mut Option<(usize, ShapeColorTarget)>,
) {
    if let Some((depth, _)) = solid_fill.as_mut() {
        *depth = depth.saturating_sub(1);
        if *depth == 0 {
            *solid_fill = None;
        }
    }
    *outline_depth = outline_depth.saturating_sub(1);
}

fn apply_shape_srgb_color(
    shape: &mut FloatingShape,
    e: &BytesStart<'_>,
    solid_fill: Option<(usize, ShapeColorTarget)>,
) {
    let Some((_, target)) = solid_fill else {
        return;
    };
    let Some(color) = attr_local(e, b"val").and_then(|value| parse_rgb_hex_color(&value)) else {
        return;
    };
    match target {
        ShapeColorTarget::Fill if shape.fill_color.is_none() => shape.fill_color = Some(color),
        ShapeColorTarget::Outline if shape.outline_color.is_none() => {
            shape.outline_color = Some(color);
        }
        _ => {}
    }
}

pub(crate) fn parse_rgb_hex_color(value: &str) -> Option<Color> {
    let value = value.trim();
    if value.len() != 6 {
        return None;
    }
    let rgb = u32::from_str_radix(value, 16).ok()?;
    Some(Color {
        r: (rgb >> 16) as u8,
        g: (rgb >> 8) as u8,
        b: rgb as u8,
    })
}

pub(crate) fn attr_i64(e: &BytesStart<'_>, key: &[u8]) -> Option<i64> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_i32(e: &BytesStart<'_>, key: &[u8]) -> Option<i32> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_u8(e: &BytesStart<'_>, key: &[u8]) -> Option<u8> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_u16(e: &BytesStart<'_>, key: &[u8]) -> Option<u16> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_f32(e: &BytesStart<'_>, key: &[u8]) -> Option<f32> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_u32(e: &BytesStart<'_>, key: &[u8]) -> Option<u32> {
    attr_local(e, key)?.trim().parse().ok()
}

pub(crate) fn attr_usize(e: &BytesStart<'_>, key: &[u8]) -> Option<usize> {
    attr_local(e, key)?.trim().parse().ok()
}

fn attr_bool(e: &BytesStart<'_>, key: &[u8]) -> Option<bool> {
    attr_local(e, key).map(|value| toggle_on(Some(value)))
}

fn parse_core_properties(xml: &str) -> CoreProperties {
    let mut r = Reader::from_str(xml);
    let mut props = CoreProperties::default();
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) => {
                let key = local(e.name().as_ref()).to_vec();
                if is_core_property_key(&key) {
                    set_core_property_value(&mut props, &key, read_text(&mut r));
                }
            }
            Ok(Event::Empty(e)) => {
                let key = local(e.name().as_ref()).to_vec();
                if is_core_property_key(&key) {
                    set_core_property_value(&mut props, &key, String::new());
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    props
}

fn is_core_property_key(key: &[u8]) -> bool {
    matches!(
        key,
        b"title"
            | b"subject"
            | b"creator"
            | b"description"
            | b"keywords"
            | b"category"
            | b"contentStatus"
            | b"lastModifiedBy"
            | b"created"
            | b"modified"
            | b"lastPrinted"
            | b"revision"
            | b"version"
    )
}

fn set_core_property_value(props: &mut CoreProperties, key: &[u8], value: String) {
    match key {
        b"title" => props.title = Some(value),
        b"subject" => props.subject = Some(value),
        b"creator" => props.creator = Some(value),
        b"description" => props.description = Some(value),
        b"keywords" => props.keywords = Some(value),
        b"category" => props.category = Some(value),
        b"contentStatus" => props.content_status = Some(value),
        b"lastModifiedBy" => props.last_modified_by = Some(value),
        b"created" => props.created = Some(value),
        b"modified" => props.modified = Some(value),
        b"lastPrinted" => props.last_printed = Some(value),
        b"revision" => props.revision = Some(value),
        b"version" => props.version = Some(value),
        _ => {}
    }
}

fn parse_custom_properties(xml: &str) -> BTreeMap<String, String> {
    let mut r = Reader::from_str(xml);
    let mut props = BTreeMap::new();
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) if local(e.name().as_ref()) == b"property" => {
                if let Some(name) = attr_local_trimmed(&e, b"name") {
                    if let Some(value) = read_custom_property_value(&mut r) {
                        props.insert(name, value);
                    }
                } else {
                    skip_subtree(&mut r);
                }
            }
            Ok(Event::Empty(e)) if local(e.name().as_ref()) == b"property" => {
                if let Some(name) = attr_local_trimmed(&e, b"name") {
                    props.insert(name, String::new());
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    props
}

fn read_custom_xml_items(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>) -> Vec<CustomXmlItem> {
    let mut names = Vec::new();
    for index in 0..zip.len() {
        if let Ok(file) = zip.by_index(index) {
            let name = file.name().to_string();
            if let Some(number) = custom_xml_item_number(&name) {
                names.push((number, name));
            }
        }
    }
    names.sort_by_key(|(number, _)| *number);
    names
        .into_iter()
        .filter_map(|(number, name)| {
            let xml = part(zip, &name)?;
            let store_item_id = part(zip, &format!("customXml/itemProps{number}.xml"))
                .and_then(|props| custom_xml_item_id(&props))
                .unwrap_or_default();
            Some(CustomXmlItem { store_item_id, xml })
        })
        .collect()
}

fn custom_xml_item_number(name: &str) -> Option<usize> {
    name.strip_prefix("customXml/item")?
        .strip_suffix(".xml")?
        .parse()
        .ok()
}

fn custom_xml_item_id(xml: &str) -> Option<String> {
    let mut r = Reader::from_str(xml);
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) | Ok(Event::Empty(e))
                if local(e.name().as_ref()) == b"datastoreItem" =>
            {
                return attr_local_trimmed(&e, b"itemID");
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    None
}

fn parse_extended_properties(xml: &str) -> HashMap<String, String> {
    let mut r = Reader::from_str(xml);
    let mut props = HashMap::new();
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) => {
                let key = local(e.name().as_ref()).to_vec();
                if is_extended_property_key(&key) {
                    if let Ok(name) = std::str::from_utf8(&key) {
                        props.insert(document_property_key(name), read_text(&mut r));
                    }
                }
            }
            Ok(Event::Empty(e)) => {
                let key = local(e.name().as_ref()).to_vec();
                if is_extended_property_key(&key) {
                    if let Ok(name) = std::str::from_utf8(&key) {
                        props.insert(document_property_key(name), String::new());
                    }
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    props
}

fn is_extended_property_key(key: &[u8]) -> bool {
    matches!(
        key,
        b"Application"
            | b"AppVersion"
            | b"Characters"
            | b"CharactersWithSpaces"
            | b"Company"
            | b"DocSecurity"
            | b"HiddenSlides"
            | b"HyperlinkBase"
            | b"HyperlinksChanged"
            | b"Lines"
            | b"LinksUpToDate"
            | b"Manager"
            | b"MMClips"
            | b"Notes"
            | b"Pages"
            | b"Paragraphs"
            | b"PresentationFormat"
            | b"ScaleCrop"
            | b"SharedDoc"
            | b"Slides"
            | b"Template"
            | b"TotalTime"
            | b"Words"
    )
}

fn parse_document_variables(xml: &str) -> HashMap<String, String> {
    let mut r = Reader::from_str(xml);
    let mut vars = HashMap::new();
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) | Ok(Event::Empty(e)) if local(e.name().as_ref()) == b"docVar" => {
                if let Some(name) = attr_local_trimmed(&e, b"name") {
                    vars.insert(
                        document_property_key(&name),
                        attr_local(&e, b"val").unwrap_or_default(),
                    );
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    vars
}

fn settings_preserves_legacy_form_cache(xml: &str) -> bool {
    let mut r = Reader::from_str(xml);
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) | Ok(Event::Empty(e))
                if local(e.name().as_ref()) == b"documentProtection" =>
            {
                let edit_forms = attr_local(&e, b"edit")
                    .as_deref()
                    .is_some_and(|edit| edit.trim().eq_ignore_ascii_case("forms"));
                if edit_forms
                    && attr_local(&e, b"enforcement").is_some_and(|value| toggle_on(Some(value)))
                {
                    return true;
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    false
}

fn parse_document_id(xml: &str) -> Option<String> {
    let mut r = Reader::from_str(xml);
    loop {
        match r.read_event() {
            Ok(Event::Start(e)) | Ok(Event::Empty(e)) if local(e.name().as_ref()) == b"docId" => {
                return attr_local(&e, b"val")
                    .map(|id| id.trim().to_owned())
                    .filter(|id| !id.is_empty());
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    None
}

fn read_custom_property_value(r: &mut Reader<&[u8]>) -> Option<String> {
    let mut value = None;
    loop {
        match r.read_event() {
            Ok(Event::Start(_)) if value.is_none() => {
                value = Some(read_text(r));
            }
            Ok(Event::Empty(_)) if value.is_none() => {
                value = Some(String::new());
            }
            Ok(Event::End(e)) if local(e.name().as_ref()) == b"property" => break,
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    value
}

/// `word/header1.xml` → `word/_rels/header1.xml.rels`.
fn part_rels_path(part_path: &str) -> String {
    match part_path.rsplit_once('/') {
        Some((dir, file)) => format!("{dir}/_rels/{file}.rels"),
        None => format!("_rels/{part_path}.rels"),
    }
}

/// Largest accepted *decompressed* size for an XML part — orders of magnitude
/// above any real document (a 64 MiB `document.xml` is a ~50,000-page doc), but
/// bounds a zip bomb. We reject a part whose declared uncompressed size already
/// exceeds this (rather than silently truncating it), and `take` still caps the
/// actual read in case the ZIP's declared size lies.
const MAX_XML_PART: u64 = 64 << 20;
/// Largest accepted embedded media (image) entry.
const MAX_MEDIA_PART: u64 = 64 << 20;
/// Whole-archive budget for decompressed media. Per-entry caps alone don't bound a
/// hostile package with thousands of large image relationships; this caps the
/// cumulative media inflation across all entries.
const MAX_TOTAL_MEDIA: u64 = 256 << 20;

/// Read a ZIP entry to a UTF-8 string, if present — bounded to guard against a
/// zip bomb (a tiny entry that decompresses to gigabytes).
fn part(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str) -> Option<String> {
    let f = zip.by_name(name).ok()?;
    if f.size() > MAX_XML_PART {
        return None;
    }
    let mut s = String::new();
    f.take(MAX_XML_PART).read_to_string(&mut s).ok()?;
    Some(s)
}

/// Read a ZIP entry to raw bytes (for media), bounded like [`part`].
fn part_bytes(zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>, name: &str) -> Option<Vec<u8>> {
    let f = zip.by_name(name).ok()?;
    if f.size() > MAX_MEDIA_PART {
        return None;
    }
    let mut v = Vec::new();
    f.take(MAX_MEDIA_PART).read_to_end(&mut v).ok()?;
    Some(v)
}

/// Cap on relationships the lenient reader path collects from one `.rels` part — bounds
/// memory on a size-capped but record-stuffed part (the package layer caps separately).
const MAX_REL_RECORDS: usize = 1 << 16;

/// `word/_rels/document.xml.rels`: `<Relationship Id Target TargetMode?/>`.
fn parse_rels(xml: &str) -> Rels {
    let mut r = Reader::from_str(xml);
    let mut map = HashMap::new();
    loop {
        if map.len() >= MAX_REL_RECORDS {
            break; // bounded: stop collecting (lenient read path)
        }
        match r.read_event() {
            Ok(Event::Start(e)) | Ok(Event::Empty(e))
                if local(e.name().as_ref()) == b"Relationship" =>
            {
                if let (Some(id), Some(target)) = (
                    attr_local_trimmed(&e, b"Id"),
                    attr_local_trimmed(&e, b"Target"),
                ) {
                    let external = attr_local_trimmed(&e, b"TargetMode")
                        .is_some_and(|value| value == "External");
                    map.insert(id, (target, external));
                }
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    map
}

/// Pre-read every embedded raster image referenced by an internal relationship
/// into `rel-id → Image`. Metafiles are extracted only when they are a bounded
/// single-DIB wrapper; vector metafiles stay placeholders.
fn read_media(
    zip: &mut zip::ZipArchive<std::io::Cursor<&[u8]>>,
    rels: &Rels,
) -> HashMap<String, Image> {
    let mut media = HashMap::new();
    // Collect first to avoid borrowing `rels` while mutably borrowing `zip`.
    let image_rels: Vec<(String, String)> = rels
        .iter()
        .filter(|(_, (target, external))| {
            !external
                && (mime_for(target).is_some()
                    || crate::metafile::format_for_part(target).is_some())
        })
        .map(|(id, (target, _))| (id.clone(), target.clone()))
        .collect();
    let mut total: u64 = 0;
    for (id, target) in image_rels {
        let path = normalize_part(&target);
        if let Some(bytes) = part_bytes(zip, &path) {
            if let Some(mime) = mime_for(&target) {
                // Stop BEFORE inserting a part that would push the in-memory media set past
                // the whole-archive budget, so the advertised cap is a hard ceiling (not
                // cap + one part). `part_bytes` already bounds each part to MAX_MEDIA_PART.
                if total.saturating_add(bytes.len() as u64) > MAX_TOTAL_MEDIA {
                    break;
                }
                total = total.saturating_add(bytes.len() as u64);
                let (width_px, height_px) = crate::image::dims(&bytes, mime).unzip();
                media.insert(
                    id,
                    Image {
                        alt: None,
                        bytes: Some(bytes),
                        mime: Some(mime.to_string()),
                        width_px,
                        height_px,
                        rotation_degrees: None,
                        floating_offset_emu: None,
                    },
                );
                continue;
            }
            let Some((kind, compressed_by_extension)) = crate::metafile::format_for_part(&target)
            else {
                continue;
            };
            let compressed = compressed_by_extension || crate::metafile::is_gzip_payload(&bytes);
            let Some(raster) = crate::metafile::extract_raster(kind, &bytes, compressed) else {
                continue;
            };
            // Stop BEFORE inserting a part that would push the in-memory media set past
            // the whole-archive budget, so the advertised cap is a hard ceiling (not
            // cap + one part). Metafile wrappers store the decoded RGBA payload.
            if total.saturating_add(raster.rgba.len() as u64) > MAX_TOTAL_MEDIA {
                break;
            }
            total = total.saturating_add(raster.rgba.len() as u64);
            media.insert(
                id,
                Image {
                    alt: None,
                    bytes: Some(raster.rgba),
                    mime: Some(crate::image::MIME_RAW_RGBA.to_string()),
                    width_px: Some(raster.width_px),
                    height_px: Some(raster.height_px),
                    rotation_degrees: None,
                    floating_offset_emu: None,
                },
            );
        }
    }
    media
}

/// A `word/document.xml.rels` relationship target → a ZIP entry name, resolving it
/// relative to the `word/` directory and normalizing `.`/`..`/leading-`/` per OPC URI
/// rules: `media/image1.png` → `word/media/image1.png`, `/word/header1.xml` →
/// `word/header1.xml`, `../customXml/item1.xml` → `customXml/item1.xml`, `./media/x.png`
/// → `word/media/x.png`. A target escaping the package root yields the joined remainder.
fn normalize_part(target: &str) -> String {
    // `/`-absolute targets are package-root relative; others are relative to `word/`.
    let base: &[&str] = if target.starts_with('/') {
        &[]
    } else {
        &["word"]
    };
    let mut segs: Vec<&str> = base.to_vec();
    for seg in target.split('/') {
        match seg {
            "" | "." => {}
            ".." => {
                segs.pop();
            }
            s => segs.push(s),
        }
    }
    segs.join("/")
}

/// MIME type for a media target by extension, restricted to the rasters the
/// `.doc` path also extracts. `None` ⇒ not a normal encoded raster.
fn mime_for(target: &str) -> Option<&'static str> {
    let ext = target.rsplit('.').next()?.to_ascii_lowercase();
    match ext.as_str() {
        "png" => Some("image/png"),
        "jpg" | "jpeg" => Some("image/jpeg"),
        "gif" => Some("image/gif"),
        "bmp" => Some("image/bmp"),
        "tif" | "tiff" => Some("image/tiff"),
        "webp" => Some("image/webp"),
        _ => None,
    }
}

/// Flat text of just the main body (excludes headers/footers).
fn body_text(model: &DocModel) -> String {
    blocks_text(&model.blocks)
}

fn blocks_text(blocks: &[Block]) -> String {
    let mut raw = String::new();
    flatten(blocks, &mut raw);
    text::finalize(&raw)
}

fn attach_note_reference_anchors(
    notes: &mut [Note],
    doc_xml: &str,
    ctx: &fields::FieldResolutionContext<'_>,
) {
    let footnote_refs = body::scan_note_ref_anchors(doc_xml, b"footnoteReference", ctx);
    let endnote_refs = body::scan_note_ref_anchors(doc_xml, b"endnoteReference", ctx);
    for note in notes {
        let anchor_text = match note.kind {
            NoteKind::Footnote => footnote_refs.get(&note.id),
            NoteKind::Endnote => endnote_refs.get(&note.id),
        };
        if let Some(text) = anchor_text {
            note.anchor = Some(TextAnchor {
                id: note.id.clone(),
                text: text.clone(),
            });
        }
    }
}

/// Flat text of the running headers and footers only.
pub(crate) fn header_footer_text(model: &DocModel) -> String {
    let mut raw = String::new();
    flatten_header_footer_surfaces(model, &mut raw);
    text::finalize(&raw)
}

fn flatten_header_footer_surfaces(model: &DocModel, out: &mut String) {
    for block in &model.blocks {
        if let Block::SectionBreak(section) = block {
            flatten(&section.header, out);
            flatten(&section.first_header, out);
            flatten(&section.even_header, out);
            flatten(&section.footer, out);
            flatten(&section.first_footer, out);
            flatten(&section.even_footer, out);
        }
    }
    flatten(&model.setup.header, out);
    flatten(&model.setup.first_header, out);
    flatten(&model.setup.even_header, out);
    flatten(&model.setup.footer, out);
    flatten(&model.setup.first_footer, out);
    flatten(&model.setup.even_footer, out);
}

pub(crate) fn main_text_with_revision_view(state: &DocxState, view: crate::RevisionView) -> String {
    let Some(doc_xml) = state.package.part("word/document.xml") else {
        return state.main_text.clone();
    };
    let doc_xml = String::from_utf8_lossy(&doc_xml);
    let core_properties = state
        .package
        .part("docProps/core.xml")
        .map(|xml| parse_core_properties(&String::from_utf8_lossy(&xml)))
        .unwrap_or_else(|| state.core_properties.clone());
    let custom_properties = state
        .package
        .part("docProps/custom.xml")
        .map(|xml| parse_custom_properties(&String::from_utf8_lossy(&xml)))
        .unwrap_or_default();
    let custom_property_fields = custom_properties
        .iter()
        .map(|(key, value)| (document_property_key(key), value.clone()))
        .collect::<HashMap<_, _>>();
    let settings_xml = state.package.part("word/settings.xml");
    let document_variables = settings_xml
        .as_deref()
        .map(|xml| parse_document_variables(&String::from_utf8_lossy(xml)))
        .unwrap_or_default();
    let preserve_legacy_form_cache = settings_xml
        .as_deref()
        .is_some_and(|xml| settings_preserves_legacy_form_cache(&String::from_utf8_lossy(xml)));
    let extended_properties = state
        .package
        .part("docProps/app.xml")
        .map(|xml| parse_extended_properties(&String::from_utf8_lossy(&xml)))
        .unwrap_or_default();
    let properties = fields::FieldDocumentProperties {
        core: &core_properties,
        custom: &custom_property_fields,
        variables: &document_variables,
        extended: &extended_properties,
        file_size_bytes: None,
    };
    let styles = state
        .package
        .part("word/styles.xml")
        .map(|xml| styles::parse(&String::from_utf8_lossy(&xml)))
        .unwrap_or_default();
    let raw_document_bookmarks =
        fields::ref_targets_with_properties(&doc_xml, properties, preserve_legacy_form_cache);
    let note_ref_context = fields::note_ref_context_with_properties(
        &doc_xml,
        &raw_document_bookmarks,
        properties,
        preserve_legacy_form_cache,
    );
    let document_bookmarks = fields::ref_targets_with_note_context(
        &doc_xml,
        properties,
        preserve_legacy_form_cache,
        &note_ref_context,
    );
    let section_context = fields::section_context_with_properties(
        &doc_xml,
        &document_bookmarks,
        properties,
        preserve_legacy_form_cache,
    );
    let toc_entries = fields::toc_entries_with_properties(
        &doc_xml,
        &styles,
        &document_bookmarks,
        &note_ref_context,
        &section_context,
        properties,
        preserve_legacy_form_cache,
    );
    let legacy_form_context = fields::legacy_form_context(&doc_xml, preserve_legacy_form_cache);
    let bookmark_names = fields::bookmark_names(&doc_xml);
    // `main_text_with_view` never consults style-ref context, but the shared
    // `FieldResolutionContext` requires a borrow; an empty default is sufficient and
    // avoids an unused style-ref scan here.
    let style_ref_context = fields::StyleRefContext::default();
    revisions::main_text_with_view(
        &doc_xml,
        view,
        Some(&fields::FieldResolutionContext {
            properties,
            document_bookmarks: &document_bookmarks,
            note_refs: &note_ref_context,
            sections: &section_context,
            style_refs: &style_ref_context,
            legacy_forms: &legacy_form_context,
            toc_entries: &toc_entries,
            bookmark_names: &bookmark_names,
        }),
    )
}

fn flatten(blocks: &[Block], out: &mut String) {
    for b in blocks {
        match b {
            Block::Paragraph(p) => {
                out.push_str(&p.text());
                out.push('\n');
            }
            Block::PageBreak | Block::SectionBreak(_) => out.push('\n'),
            Block::Image(_) | Block::Chart(_) => {}
            Block::Table(t) => {
                for row in &t.rows {
                    for (i, cell) in row.cells.iter().enumerate() {
                        if i > 0 {
                            out.push('\t');
                        }
                        flatten_inline(&cell.blocks, out);
                    }
                    out.push('\n');
                }
            }
        }
    }
}

/// Flatten a cell's content to a single line (paragraphs and nested-table cells
/// space-joined) so a table row stays one tab-separated line.
fn flatten_inline(blocks: &[Block], out: &mut String) {
    let mut first = true;
    for b in blocks {
        match b {
            Block::Paragraph(p) => {
                let t = p.text();
                if !t.is_empty() {
                    if !first {
                        out.push(' ');
                    }
                    out.push_str(&t);
                    first = false;
                }
            }
            Block::Table(t) => {
                for row in &t.rows {
                    for cell in &row.cells {
                        if !first {
                            out.push(' ');
                        }
                        flatten_inline(&cell.blocks, out);
                        first = false;
                    }
                }
            }
            Block::Image(_) | Block::Chart(_) | Block::PageBreak | Block::SectionBreak(_) => {}
        }
    }
}

// --- shared XML helpers (namespace-prefix-agnostic, like the rxls .xlsx path) ---

/// Strip a namespace prefix: `w:p` → `p`, `r:embed` → `embed`.
pub(crate) fn local(name: &[u8]) -> &[u8] {
    match name.iter().rposition(|&b| b == b':') {
        Some(i) => &name[i + 1..],
        None => name,
    }
}

/// First attribute value whose local name equals `key` (unescaped, owned).
pub(crate) fn attr_local(e: &BytesStart<'_>, key: &[u8]) -> Option<String> {
    e.attributes().flatten().find_map(|a| {
        if local(a.key.as_ref()) == key {
            a.unescape_value().ok().map(|v| v.into_owned())
        } else {
            None
        }
    })
}

pub(crate) fn attr_local_trimmed_preserve_empty(e: &BytesStart<'_>, key: &[u8]) -> Option<String> {
    attr_local(e, key).map(|value| value.trim().to_owned())
}

pub(crate) fn attr_local_trimmed(e: &BytesStart<'_>, key: &[u8]) -> Option<String> {
    attr_local(e, key)
        .map(|value| value.trim().to_owned())
        .filter(|value| !value.is_empty())
}

pub(crate) fn is_page_break_type(e: &BytesStart<'_>) -> bool {
    attr_local_trimmed(e, b"type").is_some_and(|value| value == "page")
}

pub(crate) fn field_char_type(e: &BytesStart<'_>) -> Option<String> {
    attr_local_trimmed(e, b"fldCharType")
}

/// Resolve an OOXML on/off toggle: a present element with no `w:val` means *on*;
/// `false`/`0`/`off` mean *off*; anything else is *on*.
pub(crate) fn toggle_on(val: Option<String>) -> bool {
    match val.as_deref().map(str::trim) {
        None => true,
        Some(v) => v != "0" && !v.eq_ignore_ascii_case("false") && !v.eq_ignore_ascii_case("off"),
    }
}

#[cfg(test)]
mod tests {
    use super::{
        custom_xml_item_id, normalize_part, parse_document_id, parse_rels, toggle_on,
        MAX_REL_RECORDS,
    };

    #[test]
    fn toggle_on_accepts_case_insensitive_off_values() {
        assert!(!toggle_on(Some("FALSE".to_string())));
        assert!(!toggle_on(Some(" Off ".to_string())));
        assert!(!toggle_on(Some("0".to_string())));
        assert!(toggle_on(None));
        assert!(toggle_on(Some("true".to_string())));
    }

    /// The lenient reader path bounds how many relationships it collects
    /// from one part, so a size-capped but record-stuffed `.rels` can't amplify memory.
    #[test]
    fn reader_rels_parse_is_bounded() {
        let mut s = String::from(
            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">"#,
        );
        for i in 0..(MAX_REL_RECORDS + 1000) {
            s.push_str(&format!(r#"<Relationship Id="r{i}" Target="t{i}"/>"#));
        }
        s.push_str("</Relationships>");
        assert!(
            parse_rels(&s).len() <= MAX_REL_RECORDS,
            "reader rels not bounded"
        );
    }

    #[test]
    fn reader_rels_trims_ooxml_values() {
        let rels = parse_rels(
            r#"<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
                <Relationship Id=" rLink " Target=" https://example.com/ " TargetMode=" External "/>
            </Relationships>"#,
        );
        assert_eq!(
            rels.get("rLink")
                .map(|(target, external)| (target.as_str(), *external)),
            Some(("https://example.com/", true))
        );
    }

    #[test]
    fn parse_document_id_trims_ooxml_value() {
        let xml = r#"<w:settings xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml">
            <w14:docId w14:val=" 6ECD4467 "/>
        </w:settings>"#;
        assert_eq!(parse_document_id(xml).as_deref(), Some("6ECD4467"));

        let alternate_prefix =
            r#"<settings><m:docId xmlns:m="urn:any" m:val=" 6ECD4467 "/></settings>"#;
        assert_eq!(
            parse_document_id(alternate_prefix).as_deref(),
            Some("6ECD4467")
        );
    }

    #[test]
    fn custom_xml_item_id_trims_ooxml_value() {
        let xml = r#"<ds:datastoreItem xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml" ds:itemID=" {11111111-2222-3333-4444-555555555555} ">
            <ds:schemaRefs/>
        </ds:datastoreItem>"#;
        assert_eq!(
            custom_xml_item_id(xml).as_deref(),
            Some("{11111111-2222-3333-4444-555555555555}")
        );

        let blank = r#"<ds:datastoreItem xmlns:ds="http://schemas.openxmlformats.org/officeDocument/2006/customXml" ds:itemID=" "/>"#;
        assert_eq!(custom_xml_item_id(blank), None);
    }

    /// Relationship targets resolve relative to `word/` with `.`/`..`/
    /// leading-`/` normalized per OPC URI rules (the reader was missing dot-segment ones).
    #[test]
    fn normalize_part_resolves_dot_segments() {
        assert_eq!(normalize_part("media/image1.png"), "word/media/image1.png");
        assert_eq!(
            normalize_part("/word/media/image1.png"),
            "word/media/image1.png"
        );
        assert_eq!(
            normalize_part("./media/image1.png"),
            "word/media/image1.png"
        );
        assert_eq!(
            normalize_part("../customXml/item1.xml"),
            "customXml/item1.xml"
        );
        assert_eq!(normalize_part("header1.xml"), "word/header1.xml");
    }
}