word-ooxml 1.0.0

Reading and writing of the WordprocessingML format (.docx).
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
//! The minimal in-memory model of a WordprocessingML document: a document body is a sequence of
//! block-level content — paragraphs and tables, interleaved in reading order, matching how
//! WordprocessingML itself structures `w:body` (`EG_BlockLevelElts`: a mix of `w:p` and `w:tbl`).
//!
//! Character formatting (bold/italic/underline on runs), paragraph alignment, inline images, a
//! default header/footer, simple fields (page numbers), named styles, hyperlinks, numbered/bulleted
//! lists, footnotes/endnotes, comments, structured document tags (content controls) and a document
//! theme (colors/fonts) are modeled — see the project roadmap, for what comes next.

/// A `.docx` document: a sequence of block-level content (paragraphs and tables), in reading order,
/// plus an optional default header/footer and a set of named styles (`word/styles.xml`)
/// paragraphs/runs can refer to.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Document {
    /// The blocks that make up the document body, in order.
    pub blocks: Vec<Block>,
    /// The document's default header (`w:headerReference[@w:type='default']`), shown on every page
    /// unless a page-specific header overrides it (`header_first`/ `header_even`, below).
    pub header: Option<HeaderFooter>,
    /// The document's default footer, mirroring `header`.
    pub footer: Option<HeaderFooter>,
    /// A header shown only on the section's first page (`w:headerReference[@w:type='first']`),
    /// overriding `header` for that one page. Setting this (or `footer_first`) automatically makes
    /// the writer emit `w:sectPr/w:titlePg` (`CT_OnOff`) — without it, Word ignores the
    /// `first`-type reference entirely and just repeats the default header, per ECMA-376.
    pub header_first: Option<HeaderFooter>,
    /// A footer shown only on the section's first page, mirroring `header_first`.
    pub footer_first: Option<HeaderFooter>,
    /// A header shown only on even-numbered pages (`w:headerReference[@w:type='even']`) —
    /// `header`/`header_first` become the odd-page headers once this is set. Setting this (or
    /// `footer_even`) automatically makes the writer emit `w:evenAndOddHeaders` in
    /// `word/settings.xml` (`CT_OnOff`) — without it, Word ignores the `even`-type reference and
    /// just repeats the default/odd header on every page, per ECMA-376.
    pub header_even: Option<HeaderFooter>,
    /// A footer shown only on even-numbered pages, mirroring `header_even`.
    pub footer_even: Option<HeaderFooter>,
    /// This document's page setup — size, orientation, margins, columns (`w:sectPr`'s
    /// `pgSz`/`pgMar`/`cols`). Unlike `header`/`footer`, this is not optional: WordprocessingML
    /// always needs *some* page setup, so `Default` gives the exact fixed A4/standard-margins
    /// values this crate has always written since (`PageSetup::default`), preserving old behavior
    /// for callers who don't set this. Only a single, document-wide page setup is modeled —
    /// WordprocessingML actually allows several independent page setups via mid-document section
    /// breaks (a new `w:sectPr` inside a paragraph's own `w:pPr`), deliberately not modeled here:
    /// mid-document section breaks are a rare, advanced case, and supporting only a single
    /// document-wide page setup keeps the model considerably simpler without real demand yet for
    /// the alternative.
    pub page_setup: PageSetup,
    /// Named styles declared for this document (`word/styles.xml`, `CT_Styles`'s `style` elements),
    /// referenced from paragraphs (`Paragraph.style_id`) and runs (`Run.style_id`) by id. Only
    /// written if non-empty — see `writer.rs`.
    pub styles: Vec<Style>,
    /// Numbering (list) definitions declared for this document (`word/numbering.xml`), referenced
    /// from paragraphs (`Paragraph.numbering_id`) by id. Only written if non-empty — see
    /// `writer.rs`.
    pub numbering_definitions: Vec<NumberingDefinition>,
    /// Footnotes declared for this document (`word/footnotes.xml`), referenced from the body by id
    /// (`RunContent::NoteReference`). Only written if non-empty — see `writer.rs`.
    pub footnotes: Vec<Note>,
    /// Endnotes declared for this document (`word/endnotes.xml`), mirroring `footnotes`.
    pub endnotes: Vec<Note>,
    /// Comments declared for this document (`word/comments.xml`), anchored to a range of the body
    /// via `Run.comment_ids` — see [`Comment`]'s doc comment for how the underlying
    /// `w:commentRangeStart`/ `w:commentRangeEnd`/`w:commentReference` markers are derived from
    /// that field rather than modeled by hand. Only written if non-empty — see `writer.rs`.
    pub comments: Vec<Comment>,
    /// This document's theme (`word/theme/theme1.xml`), or `None` to leave it unset entirely — a
    /// document with no theme part still opens fine in Word, just falling back to whatever theme
    /// Word's own default template carries. Only written if `Some` — see `writer.rs`, and
    /// [`Theme`]'s own doc comment for what is/isn't modeled.
    pub theme: Option<Theme>,
    /// Whether Word should track changes (insertions/deletions/formatting changes) made to this
    /// document from now on (`w:trackRevisions` — confirmed via ECMA-376's own `CT_Settings` schema
    /// fragment and docx4j's generated `CTSettings` binding; despite the UI calling the feature
    /// "Track Changes", the underlying element is *not* named `w:trackChanges`, easy to get wrong —
    /// `CT_OnOff`, in `word/settings.xml`). This is only the simple on/off editing-mode toggle —
    /// matching the equivalent checkbox under Word's Review > Track Changes menu — not a way to
    /// author individual tracked revisions (`w:ins`/`w:del`/`w:rPrChange`/..) programmatically;
    /// this crate exposes exactly this one on/off toggle and nothing more — no API here creates
    /// individual revision marks. `false` (the default) omits `w:trackRevisions` entirely, which is
    /// equivalent to explicitly disabling it.
    pub track_changes: bool,
    /// This document's core properties (`docProps/core.xml`, `CT_CoreProperties` — title, author,
    /// subject, etc.). Left at its `Default` (every field `None`) writes the same near-empty
    /// `<cp:coreProperties/>` this crate has always written; setting any field populates just that
    /// element, since `CT_CoreProperties` is an `xsd:all` group (every child optional, no fixed
    /// order — confirmed via ECMA-376's own schema fragment, unlike the many strict `xsd:sequence`
    /// groups this project has had to pin down elsewhere).
    pub properties: DocumentProperties,
    /// This document's editing-restriction protection (`w:documentProtection`, `CT_DocProtect`, in
    /// `word/settings.xml`), or `None` for no restriction. Only the no-password form is modeled
    /// (`w:enforcement="1"` with no `w:cryptProviderType`/hash/salt) — a password-protected variant
    /// involves a cryptographic hash of the password plus a random salt, real complexity with no
    /// proportionate demand seen yet in this project, matching the "simple case first" posture
    /// already applied elsewhere (e.g. `Run.text_border`'s fixed appearance instead of
    /// `CT_Border`'s full richness). See [`ProtectionKind`] for which restriction levels are
    /// modeled.
    pub protection: Option<ProtectionKind>,
    /// This document's extended properties (`docProps/app.xml`, `CT_Properties` —
    /// application-defined metadata, distinct from `docProps/core.xml`'s Dublin Core fields above).
    /// Only `Company`/`Manager` are modeled — see [`ExtendedProperties`]'s own doc comment for why
    /// the many statistical fields (`Words`/`Pages`/ `Characters`/..) aren't. Left at its `Default`
    /// (both fields `None`), this crate still always writes `docProps/app.xml` with just
    /// `Application` set (unchanged from before this field existed) — see `writer.rs`'s
    /// `to_extended_properties_xml`.
    pub extended_properties: ExtendedProperties,
    /// This document's custom properties (`docProps/custom.xml`, `CT_Properties` — arbitrary
    /// user-defined name/value metadata pairs). A `Vec` of `(name, value)` pairs, not a map — order
    /// matters here: it determines the `pid` (property id) each entry gets when written (`2`, `3`,
    /// `4`. in declaration order; `0`/`1` are reserved by the format and never assigned), so
    /// insertion order is preserved rather than an arbitrary hash-map order. Only written if
    /// non-empty, same "optional part" convention as `styles`/`footnotes`/etc. See
    /// [`CustomPropertyValue`] for which value types are modeled.
    pub custom_properties: Vec<(String, CustomPropertyValue)>,
}

/// This document's core properties (`docProps/core.xml`, `CT_CoreProperties`). Every field mirrors
/// a Dublin Core / Dublin Core Terms element Word's own File > Info panel shows and lets a user
/// edit — `None` leaves the corresponding XML element out entirely (mirrors Word's own behavior: an
/// absent element is treated as an empty property, not a validation error). Dates
/// (`created`/`modified`) are plain ISO-8601/W3CDTF strings (e.g. `"2026-07-17T10:00:00Z"`), not a
/// dedicated date/time type — this crate has no date/time dependency, and two optional metadata
/// fields don't justify adding one; the caller is responsible for supplying a valid W3CDTF string,
/// not validated when writing (same best-effort posture as `Paragraph.numbering_id` referencing a
/// declaration that may not exist). A handful of `CT_CoreProperties`' children are not modeled here
/// (`dc:identifier`, `dc:language`, `cp:lastPrinted`, `cp:version`) — niche fields with no real
/// demand seen yet, same scope-reduction posture as elsewhere in this crate.
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct DocumentProperties {
    /// The document's title (`dc:title`), shown in Word's title bar and File > Info panel.
    pub title: Option<String>,
    /// The document's subject (`dc:subject`).
    pub subject: Option<String>,
    /// The document's author (`dc:creator`).
    pub creator: Option<String>,
    /// Search keywords/tags (`cp:keywords`).
    pub keywords: Option<String>,
    /// A longer description of the document (`dc:description`) — shown as "Comments" in Word's own
    /// File > Info panel despite the underlying element being `dc:description`.
    pub description: Option<String>,
    /// The user who last modified the document (`cp:lastModifiedBy`).
    pub last_modified_by: Option<String>,
    /// The document's revision number, as a plain string (`cp:revision`, schema-typed as
    /// `xsd:string`, even though Word itself always populates it with a decimal integer in
    /// practice).
    pub revision: Option<String>,
    /// When the document was created (`dcterms:created`), a W3CDTF string. See this struct's own
    /// doc comment for the string-not-a-type choice.
    pub created: Option<String>,
    /// When the document was last modified (`dcterms:modified`), mirroring `created`.
    pub modified: Option<String>,
    /// The document's category (`cp:category`), a free-form classification string distinct from
    /// `subject`.
    pub category: Option<String>,
    /// The document's content status (`cp:contentStatus`, e.g. "Draft", "Final" — a free-form
    /// string, not a fixed enumeration).
    pub content_status: Option<String>,
}

/// Which editing restrictions are enforced on a document (`w:documentProtection/@w:edit`,
/// `ST_DocProtect`) once `Document.protection` is `Some`. `ST_DocProtect`'s `"none"` value isn't
/// modeled as its own variant — `Document.protection: Option::None` already expresses "no
/// restriction", same convention as `Highlight`'s `"none"`/ `VerticalAlign`'s
/// `"baseline"`/`UnderlineStyle`'s `"none"` elsewhere in this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ProtectionKind {
    /// Edits are restricted to regions delimited by matching range permissions — in practice, with
    /// none declared (this crate doesn't model range permissions), this means no editing at all.
    ReadOnly,
    /// Edits are restricted to inserting/deleting comments (plus the same range-permission
    /// carve-out as `ReadOnly`).
    Comments,
    /// Edits are tracked as revisions, and applications shouldn't allow turning tracking back off
    /// while this is enforced — per ECMA-376, this value "shall imply the presence of the
    /// `trackRevisions` element", though this crate does not automatically set
    /// `Document.track_changes` when this variant is used (best-effort, not validated, same posture
    /// as `Hyperlink::Internal`'s anchor not being checked against a real bookmark).
    TrackedChanges,
    /// Edits are restricted to form fields in sections marked as form-protected (this crate doesn't
    /// model per-section `formProt`, so in practice this behaves like `ReadOnly` for any document
    /// it writes).
    Forms,
}

impl ProtectionKind {
    /// This kind's `w:edit` attribute value (`ST_DocProtect`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            ProtectionKind::ReadOnly => "readOnly",
            ProtectionKind::Comments => "comments",
            ProtectionKind::TrackedChanges => "trackedChanges",
            ProtectionKind::Forms => "forms",
        }
    }

    /// Parses a `w:edit` attribute value (`ST_DocProtect`) into a [`ProtectionKind`], or `None` for
    /// `"none"` or any unrecognized value — mirrors this crate's usual forgiving-on-read policy.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "readOnly" => Some(ProtectionKind::ReadOnly),
            "comments" => Some(ProtectionKind::Comments),
            "trackedChanges" => Some(ProtectionKind::TrackedChanges),
            "forms" => Some(ProtectionKind::Forms),
            _ => None,
        }
    }
}

/// This document's extended properties (`docProps/app.xml`, `CT_Properties` — confirmed via
/// ECMA-376's own schema fragment to be an `xsd:all` group, same "no fixed order" shape as
/// `CT_CoreProperties`). Only `Company`/`Manager` are modeled here: the two fields a user actually
/// edits (shown right next to Title/Author/Category in Word's own Summary tab, alongside the
/// `docProps/core.xml` fields already modeled by [`DocumentProperties`]). `CT_Properties` has many
/// more children (`Words`, `Pages`, `Characters`, `Lines`, `Paragraphs`, `TotalTime`,
/// `Application`, `AppVersion`, `DocSecurity`, `ScaleCrop`, `LinksUpToDate`..) — these are
/// statistics/environment fields Word itself computes when it saves a document, not meaningful for
/// a generation library to set by hand, so they're deliberately left out (this crate's `writer.rs`
/// still always sets `Application` to identify itself as the producer, same as before this struct
/// existed, but that value isn't exposed as a settable field here).
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ExtendedProperties {
    /// The document's associated company/organization (`Company`).
    pub company: Option<String>,
    /// The document's manager (`Manager`).
    pub manager: Option<String>,
}

impl ExtendedProperties {
    /// Creates an empty set of extended properties (every field `None`).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the document's company and returns it for chaining.
    pub fn with_company(mut self, company: impl Into<String>) -> Self {
        self.company = Some(company.into());
        self
    }

    /// Sets the document's manager and returns it for chaining.
    pub fn with_manager(mut self, manager: impl Into<String>) -> Self {
        self.manager = Some(manager.into());
        self
    }
}

/// A single custom document property's value (`docProps/custom.xml`, `CT_Property`'s value
/// `xsd:choice` — this crate models 4 of its many variant types: `vt:lpwstr` (`Text`), `vt:bool`
/// (`Bool`), `vt:i4` (`Int`), `vt:r8` (`Number`)). `CT_Property` also allows a date variant
/// (`vt:filetime`) and several others (vectors, blobs, currency..) not modeled here — same "simple
/// case first" scope reduction as `DocumentProperties.created`/`.modified` not getting a dedicated
/// date/time type either (no `chrono` dependency for this crate).
#[derive(Debug, Clone, PartialEq)]
pub enum CustomPropertyValue {
    /// A text value (`vt:lpwstr`).
    Text(String),
    /// A boolean value (`vt:bool`).
    Bool(bool),
    /// A 32-bit signed integer value (`vt:i4`).
    Int(i32),
    /// A 64-bit floating-point value (`vt:r8`).
    Number(f64),
}

/// The content of a header or footer: a sequence of block-level content (paragraphs and tables) —
/// the same content model WordprocessingML gives the document body (`CT_HdrFtr` reuses
/// `EG_BlockLevelElts`, the exact group `w:body` uses), just without a `w:body` wrapper or section
/// properties of its own.
// `Eq` dropped (was `PartialEq, Eq`): transitively contains `Vec<Block>` -> `Block::Paragraph` ->
// `Run` -> `RunContent::Image`/`RunContent::Chart`, neither `drawing::ShapeProperties` nor
// `chart::ChartSpace` implementing `Eq` — Same reasoning applies to every other type below in this
// transitive closure (`Block`, `Paragraph`, `Run`, `Table`/`TableRow`/`TableCell`,
// `StructuredDocumentTag`, `Note`, `Comment`).
#[derive(Debug, Default, Clone, PartialEq)]
pub struct HeaderFooter {
    /// The blocks that make up this header/footer's content, in order.
    pub blocks: Vec<Block>,
}

/// A document's page setup (`w:sectPr`'s `pgSz`/`pgMar`/`cols`, `CT_PageSz`/
/// `CT_PageMar`/`CT_Columns`) — size, orientation, margins, and an optional equal-width
/// multi-column layout. See `Document.page_setup`'s doc comment for why only one, document-wide
/// page setup is modeled (no mid-document section breaks).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PageSetup {
    /// The page's width, in twips (`w:pgSz/@w`).
    pub width_twips: u32,
    /// The page's height, in twips (`w:pgSz/@h`).
    pub height_twips: u32,
    /// The page's orientation (`w:pgSz/@orient`). Note that real Word output also swaps
    /// `width_twips`/`height_twips` so the page is actually wider than tall for `Landscape` — this
    /// crate does not do that automatically (setting `Landscape` alone, without also swapping the
    /// dimensions, produces a schema-valid but visually portrait-shaped "landscape" page); the
    /// caller is responsible for passing dimensions that already match the chosen orientation, same
    /// "no hidden magic" convention as the rest of this crate.
    pub orientation: Orientation,
    /// The page's top margin, in twips (`w:pgMar/@top`).
    pub margin_top_twips: u32,
    /// The page's bottom margin, in twips (`w:pgMar/@bottom`).
    pub margin_bottom_twips: u32,
    /// The page's left margin, in twips (`w:pgMar/@left`).
    pub margin_left_twips: u32,
    /// The page's right margin, in twips (`w:pgMar/@right`).
    pub margin_right_twips: u32,
    /// The distance from the top of the page to the header's content, in twips (`w:pgMar/@header`).
    pub margin_header_twips: u32,
    /// The distance from the bottom of the page to the footer's content, in twips
    /// (`w:pgMar/@footer`).
    pub margin_footer_twips: u32,
    /// Extra binding-side margin, in twips (`w:pgMar/@gutter`) — added to the left margin (or the
    /// right, under `w:sectPr/@rtlGutter`, not modeled here; always left-side).
    pub margin_gutter_twips: u32,
    /// The number of equal-width columns the page's text flows into (`w:cols`, `CT_Columns`), or
    /// `None` to omit `w:cols` entirely (a single column, Word's default). When `Some`, written as
    /// `w:cols/@num` with `w:equalWidth="true"` and a fixed `w:space`
    /// (`DEFAULT_COLUMN_SPACING_TWIPS`, matching Word's own default spacing between columns) —
    /// `CT_Columns` also allows unequal, individually-sized columns via a repeated `w:col` child,
    /// not modeled here, same "equal widths only" scope reduction as `Table.column_widths` versus
    /// per-column-width columns is NOT (`Table.column_widths` sets individual widths; this only
    /// sets a column *count*, all equal) — kept deliberately simple since the common case
    /// (newsletter-style equal columns) doesn't need more.
    pub columns: Option<u32>,
}

impl Default for PageSetup {
    /// A4 portrait with the standard margins this crate has always written (fixed since) —
    /// preserves old behavior exactly for a `Document` that doesn't set `page_setup` explicitly.
    fn default() -> Self {
        Self {
            width_twips: 11_906,
            height_twips: 16_838,
            orientation: Orientation::Portrait,
            margin_top_twips: 1_417,
            margin_bottom_twips: 1_417,
            margin_left_twips: 1_417,
            margin_right_twips: 1_417,
            margin_header_twips: 708,
            margin_footer_twips: 708,
            margin_gutter_twips: 0,
            columns: None,
        }
    }
}

impl PageSetup {
    /// Creates a page setup with this crate's previous fixed defaults (A4 portrait, standard
    /// margins) — the same as [`PageSetup::default`], spelled out as a constructor for consistency
    /// with every other type in this crate.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the page's width/height, in twips, and returns it for chaining.
    pub fn with_size_twips(mut self, width_twips: u32, height_twips: u32) -> Self {
        self.width_twips = width_twips;
        self.height_twips = height_twips;
        self
    }

    /// Sets the page's orientation and returns it for chaining. See `orientation`'s doc comment —
    /// does not swap `width_twips`/ `height_twips` automatically.
    pub fn with_orientation(mut self, orientation: Orientation) -> Self {
        self.orientation = orientation;
        self
    }

    /// Sets the page's top/bottom/left/right margins, in twips, and returns it for chaining.
    pub fn with_margins_twips(mut self, top: u32, bottom: u32, left: u32, right: u32) -> Self {
        self.margin_top_twips = top;
        self.margin_bottom_twips = bottom;
        self.margin_left_twips = left;
        self.margin_right_twips = right;
        self
    }

    /// Sets the header/footer margins, in twips, and returns it for chaining.
    pub fn with_header_footer_margins_twips(mut self, header: u32, footer: u32) -> Self {
        self.margin_header_twips = header;
        self.margin_footer_twips = footer;
        self
    }

    /// Sets the binding-side gutter margin, in twips, and returns it for chaining.
    pub fn with_gutter_twips(mut self, gutter: u32) -> Self {
        self.margin_gutter_twips = gutter;
        self
    }

    /// Sets the number of equal-width columns and returns it for chaining. See `columns`'s doc
    /// comment.
    pub fn with_columns(mut self, columns: u32) -> Self {
        self.columns = Some(columns);
        self
    }
}

/// A page's orientation (`w:pgSz/@orient`, `ST_PageOrientation` — exactly 2 values).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Orientation {
    Portrait,
    Landscape,
}

impl Orientation {
    /// This orientation's `w:pgSz`/`orient` value (`ST_PageOrientation`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            Orientation::Portrait => "portrait",
            Orientation::Landscape => "landscape",
        }
    }

    /// Parses a `w:pgSz`/`orient` value (`ST_PageOrientation`) back into an [`Orientation`], or
    /// `None` for an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "portrait" => Some(Orientation::Portrait),
            "landscape" => Some(Orientation::Landscape),
            _ => None,
        }
    }
}

/// A single block-level element of a document body: a paragraph, a table, or a structured document
/// tag (content control) wrapping more blocks. Real WordprocessingML documents freely interleave
/// these (e.g. a paragraph, then a table, then another paragraph), so this is modeled as a sequence
/// of blocks rather than separate lists per kind — matching
/// `EG_ContentBlockContent`/`EG_BlockLevelElts`, the actual schema group
/// `w:body`/`w:sdtContent`/etc. share.
#[derive(Debug, Clone, PartialEq)]
pub enum Block {
    Paragraph(Paragraph),
    Table(Table),
    StructuredDocumentTag(StructuredDocumentTag),
}

/// A paragraph: a sequence of runs, plus paragraph-level formatting.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Paragraph {
    /// The runs that make up this paragraph, in order.
    pub runs: Vec<Run>,
    /// The paragraph's horizontal alignment, or `None` to leave it unspecified (inherits from the
    /// paragraph style / Word's default). Overrides the alignment of `style_id`'s style, if any.
    pub alignment: Option<Alignment>,
    /// The id of a paragraph-type [`Style`] to apply (`w:pStyle`), or `None` to use the document's
    /// default paragraph style. The referenced style must actually be declared in `Document.styles`
    /// for the document to be well-formed — this is not validated when writing.
    pub style_id: Option<String>,
    /// The id of a [`NumberingDefinition`] to apply (`w:numPr/w:numId`), making this paragraph an
    /// item of that list, or `None` for a regular paragraph. The referenced definition must
    /// actually be declared in `Document.numbering_definitions` for the document to be well-formed
    /// — not validated when writing, same convention as `style_id`.
    pub numbering_id: Option<u32>,
    /// Which indent level of `numbering_id`'s list this paragraph is at (`w:numPr/w:ilvl`,
    /// 0-indexed). Only meaningful when `numbering_id` is `Some`; must be within the range of
    /// levels the referenced [`NumberingDefinition`] actually declares — not validated when
    /// writing.
    pub numbering_level: u8,
    /// This paragraph's line spacing (`w:spacing/@line`, written together with
    /// `w:spacing/@lineRule="auto"`), or `None` to leave it unspecified. Unlike
    /// `space_before`/`space_after` (raw twips), this is in `w:spacing`'s "auto" units — 240ths of
    /// a single line, so `240` is single spacing, `360` is 1.5 lines, `480` is double — matching
    /// what Word's own line-spacing dropdown offers. The twips-based `atLeast`/`exact` line-height
    /// modes (`w:lineRule`'s other two values, meant for exact point-based line heights rather than
    /// a multiple of the current font) aren't modeled.
    pub line_spacing: Option<u32>,
    /// Extra space before this paragraph, in twips (`w:spacing/@before`, `ST_TwipsMeasure`,
    /// twentieths of a point) — raw units, no conversion, matching `Run.character_spacing`'s
    /// precedent. `None` leaves it unspecified. `w:spacing/@beforeAutospacing` (letting Word
    /// compute it automatically instead) isn't modeled.
    pub space_before: Option<u32>,
    /// Extra space after this paragraph, in twips, mirroring `space_before`.
    pub space_after: Option<u32>,
    /// This paragraph's background shading color (`w:shd/@fill`), mirroring `Run.shading_color` —
    /// see that field's doc comment for the same `val`/`color` fixed-pair convention.
    pub shading_color: Option<String>,
    /// Whether this paragraph has a border around it (`w:pBdr`), mirroring `Run.text_border` — a
    /// simple on/off switch with the same fixed appearance (`val="single" sz="4" space="0"
    /// color="auto"`), applied to all four sides (`top`/`left`/`bottom`/`right`). `CT_PBdr`'s
    /// `between` (a rule drawn between paragraphs sharing this same border, when several
    /// consecutive paragraphs all have it) and `bar` (a vertical bar in the margin, used for
    /// revision-style paragraph marking) aren't modeled, same scope-reduction posture as
    /// `text_border` not exposing all of `CT_Border`'s richness.
    pub border: bool,
    /// Whether this paragraph should stay on the same page as the one following it (`w:keepNext`,
    /// `CT_OnOff`) — Word moves both to the next page together rather than letting a page break
    /// fall between them. Commonly set on heading paragraphs, so a heading never ends up alone at
    /// the bottom of a page with its content starting on the next one.
    pub keep_with_next: bool,
    /// Whether every line of this paragraph must stay together on the same page (`w:keepLines`,
    /// `CT_OnOff`) — prevents the paragraph itself from being split across a page break partway
    /// through.
    pub keep_lines_together: bool,
    /// Whether this paragraph always starts on a new page (`w:pageBreakBefore`, `CT_OnOff`) — a
    /// page break is forced immediately before it, regardless of how much room is left on the
    /// current page. Distinct from `RunContent::Break(BreakKind::Page)`, which inserts an explicit
    /// page break wherever it appears within a run's content, mid-paragraph; this is a
    /// paragraph-level property instead.
    pub page_break_before: bool,
    /// This paragraph's custom tab stops (`w:tabs`, `CT_Tabs`), in order. Left empty (the default)
    /// to fall back entirely to Word's own default tab stops (evenly spaced, typically every 720
    /// twips/half inch) — setting even one custom stop here does not disable Word's defaults beyond
    /// it, per ECMA-376.
    pub tabs: Vec<TabStop>,
    /// Whether to ignore the spacing above/below this paragraph when the paragraph immediately
    /// before/after it shares the same paragraph style (`w:contextualSpacing`, `CT_OnOff`) —
    /// commonly set on list item styles, so consecutive list items don't get extra vertical gaps
    /// between them even if the style itself sets `space_before`/ `space_after`.
    pub contextual_spacing: bool,
}

/// A single custom tab stop (`w:tab`, `CT_TabStop`), one entry of `Paragraph.tabs`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TabStop {
    /// The tab stop's position, in twips, measured from the paragraph's left margin (`w:tab/@pos`,
    /// `ST_SignedTwipsMeasure` — signed, since a tab stop can be positioned left of the margin
    /// under a negative indent).
    pub position_twips: i32,
    /// How text is aligned relative to this tab stop (`w:tab/@val`).
    pub alignment: TabStopAlignment,
    /// The leader character repeated between the preceding text and this tab stop
    /// (`w:tab/@leader`), or `None` for a blank leader (Word's default when the attribute is
    /// omitted).
    pub leader: Option<TabLeader>,
}

impl TabStop {
    /// Creates a left-aligned tab stop at the given position, with no leader — the most common
    /// case.
    pub fn new(position_twips: i32) -> Self {
        Self {
            position_twips,
            alignment: TabStopAlignment::Left,
            leader: None,
        }
    }

    /// Sets this tab stop's alignment and returns it for chaining.
    pub fn with_alignment(mut self, alignment: TabStopAlignment) -> Self {
        self.alignment = alignment;
        self
    }

    /// Sets this tab stop's leader character and returns it for chaining.
    pub fn with_leader(mut self, leader: TabLeader) -> Self {
        self.leader = Some(leader);
        self
    }
}

/// How text is aligned relative to a [`TabStop`] (`w:tab/@val`, `ST_TabJc`).
///
/// `ST_TabJc` also defines `clear` (removes an inherited tab stop from a base style, not meaningful
/// when authoring a fresh document) and `num` (a legacy "list tab" tied to outline numbering) —
/// neither modeled here, same scope reduction as elsewhere in this crate.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabStopAlignment {
    Left,
    Center,
    Right,
    Decimal,
    Bar,
}

impl TabStopAlignment {
    /// This alignment's `w:tab`/`val` value (`ST_TabJc`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            TabStopAlignment::Left => "left",
            TabStopAlignment::Center => "center",
            TabStopAlignment::Right => "right",
            TabStopAlignment::Decimal => "decimal",
            TabStopAlignment::Bar => "bar",
        }
    }

    /// Parses a `w:tab`/`val` value (`ST_TabJc`) back into a [`TabStopAlignment`], or `None` for
    /// `clear`/`num`/an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "left" => Some(TabStopAlignment::Left),
            "center" => Some(TabStopAlignment::Center),
            "right" => Some(TabStopAlignment::Right),
            "decimal" => Some(TabStopAlignment::Decimal),
            "bar" => Some(TabStopAlignment::Bar),
            _ => None,
        }
    }
}

/// A [`TabStop`]'s leader character (`w:tab/@leader`, `ST_TabTlc`) — repeated between the preceding
/// text and the tab stop itself (e.g. dotted leaders in a table of contents).
///
/// `ST_TabTlc` also defines `none`, explicitly clearing any inherited leader — not modeled as its
/// own variant here, since `TabStop.leader: Option<TabLeader>` already expresses "no leader" via
/// `None`, same convention as [`Highlight`]'s own `"none"` value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TabLeader {
    Dot,
    Hyphen,
    Underscore,
    Heavy,
    MiddleDot,
}

impl TabLeader {
    /// This leader's `w:tab`/`leader` value (`ST_TabTlc`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            TabLeader::Dot => "dot",
            TabLeader::Hyphen => "hyphen",
            TabLeader::Underscore => "underscore",
            TabLeader::Heavy => "heavy",
            TabLeader::MiddleDot => "middleDot",
        }
    }

    /// Parses a `w:tab`/`leader` value (`ST_TabTlc`) back into a [`TabLeader`], or `None` for
    /// `"none"` or an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "dot" => Some(TabLeader::Dot),
            "hyphen" => Some(TabLeader::Hyphen),
            "underscore" => Some(TabLeader::Underscore),
            "heavy" => Some(TabLeader::Heavy),
            "middleDot" => Some(TabLeader::MiddleDot),
            _ => None,
        }
    }
}

/// A run: a contiguous span of content (text, an inline image, or a field) sharing the same
/// formatting.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Run {
    /// The run's content.
    pub content: RunContent,
    /// Whether the run is bold (`<w:b/>`, WordprocessingML `CT_RPr`). Meaningful for
    /// [`RunContent::Text`] and [`RunContent::Field`]; ignored when writing an image run.
    pub bold: bool,
    /// Whether the run is italic (`<w:i/>`).
    pub italic: bool,
    /// The run's underline style (`<w:u w:val="..">`, `CT_Underline`), or `None` for no underline.
    /// See [`UnderlineStyle`]'s doc comment for the full palette of styles (`ST_Underline`).
    pub underline: Option<UnderlineStyle>,
    /// The color of `underline`'s line (`w:u`'s `color` attribute), as a plain 6-digit RGB hex
    /// string, or `None` to leave it unset (matches the text color — visually the same outcome as
    /// `CT_Underline`'s other `color` choice, the literal string `"auto"`, which isn't modeled
    /// separately, same convention as `Run.color`). Only meaningful when `underline` is `Some`;
    /// theme-relative colors (`w:themeColor`/`w:themeTint`/`w:themeShade`) aren't modeled either,
    /// same scope limit as `color` itself.
    pub underline_color: Option<String>,
    /// The run's text color (`<w:color w:val="..">`, `CT_Color`), as a plain 6-digit RGB hex string
    /// (no leading `#`, e.g. `"FF0000"`), or `None` to leave it unset (inherits from the
    /// paragraph/character style, or Word's own default — visually the same outcome as `CT_Color`'s
    /// other `val` choice, the literal string `"auto"`, which isn't modeled separately since
    /// omitting the element entirely already achieves it). Theme-relative colors
    /// (`w:themeColor`/`w:themeTint`/ `w:themeShade`, `CT_Color`'s other attributes) aren't modeled
    /// either — same scope limit as [`Theme`] itself, which only lets a document's theme be *set*,
    /// not referenced from formatting.
    pub color: Option<String>,
    /// The run's font size in whole points (e.g. `12`), or `None` to leave it unset. Written as
    /// `<w:sz w:val="..">`/`<w:szCs w:val="..">` (`CT_HpsMeasure`, in half-points — `24` for a 12pt
    /// run — the writer does the doubling), both set to the same value since complex-script sizing
    /// isn't modeled separately. WordprocessingML's `w:sz` actually allows half-point granularity
    /// (e.g. 10.5pt), but only whole points are modeled here — no real need for finer granularity
    /// has come up.
    pub font_size: Option<u16>,
    /// The run's font family/typeface (e.g. `"Calibri"`), or `None` to leave it unset. Written as
    /// `<w:rFonts w:ascii=".." w:hAnsi="..">` (`CT_Fonts`), both set to the same value;
    /// `w:eastAsia`/`w:cs` (East Asian / complex-script typefaces) aren't modeled, same scope limit
    /// as [`FontScheme`]'s Latin-only typefaces.
    pub font_family: Option<String>,
    /// The run's highlight color (`<w:highlight w:val="..">`, `CT_Highlight` — a fixed
    /// "highlighter" palette, distinct from `color`), or `None` for no highlighting. See
    /// [`Highlight`]'s doc comment.
    pub highlight: Option<Highlight>,
    /// Whether the run is struck through (`<w:strike/>`, `CT_OnOff`) — a single horizontal line
    /// through the text. WordprocessingML also defines `w:dstrike` (double strikethrough), not
    /// modeled here.
    pub strike: bool,
    /// The run's vertical alignment (`<w:vertAlign w:val="..">`, `CT_VerticalAlignRun`) —
    /// superscript or subscript, or `None` for the normal baseline position. See
    /// [`VerticalAlign`]'s doc comment.
    pub vertical_align: Option<VerticalAlign>,
    /// Whether lowercase letters in the run are displayed as small capital letters
    /// (`<w:smallCaps/>`, `CT_OnOff`) — a display-only effect, the underlying text isn't changed.
    /// Distinct from `all_caps`, which affects lowercase AND uppercase letters the same way.
    pub small_caps: bool,
    /// Whether all characters in the run are displayed as capital letters (`<w:caps/>`, `CT_OnOff`)
    /// — like `small_caps`, a display-only effect. `small_caps` and `all_caps` are mutually
    /// exclusive in practice (Word's UI won't let both apply to the same text at once), but that
    /// isn't enforced here — setting both just lets `all_caps` visually win, matching real Word
    /// rendering.
    pub all_caps: bool,
    /// The run's background shading color (`<w:shd w:val="clear" w:color="auto" w:fill="..">`,
    /// `CT_Shd`), as a plain 6-digit RGB hex string, or `None` for no shading. Unlike `highlight`'s
    /// fixed 16-color "highlighter" palette, this is an arbitrary color, closer to a text
    /// background fill — `val`/`color` (the shading pattern and its foreground color) are always
    /// written as the fixed `"clear"`/`"auto"` pair for a plain solid fill, matching this crate's
    /// convention for schema-mandatory-but-out-of-scope attributes (see `Theme`'s `fmtScheme`);
    /// patterned shading (crosshatch, stripes, etc.) and `w:themeFill` aren't modeled.
    pub shading_color: Option<String>,
    /// Whether the run has a border around its text (`<w:bdr w:val="single" w:sz="4" w:space="0"
    /// w:color="auto"/>`, `CT_Border`) — a simple on/off flag rather than exposing `CT_Border`'s
    /// full richness (border style, width, spacing, color, shadow, frame effect), since this
    /// property is niche enough that a single sensible fixed appearance (thin single black line, no
    /// gap) covers the common case; broader configurability can be added later if a real need comes
    /// up, same posture as `strike` not modeling `w:dstrike`.
    pub text_border: bool,
    /// Character spacing adjustment (`<w:spacing w:val="..">`, `CT_SignedTwipsMeasure`), in twips
    /// (twentieths of a point) — positive expands letter spacing, negative condenses it — or `None`
    /// to leave it unset.
    pub character_spacing: Option<i16>,
    /// The run's vertical position, raised or lowered from the normal baseline (`<w:position
    /// w:val="..">`, `CT_SignedHpsMeasure`), in half-points — positive raises, negative lowers — or
    /// `None` to leave it at the baseline. Distinct from `vertical_align` (superscript/subscript):
    /// `position` shifts the baseline without shrinking the font size, `vertical_align` does both
    /// together.
    pub vertical_position: Option<i16>,
    /// Whether the run's text is hidden (`<w:vanish/>`, `CT_OnOff`) — present in the document but
    /// not displayed or printed by default (Word's Home > Show/Hide formatting marks toggle reveals
    /// it).
    pub hidden: bool,
    /// The id of a character-type [`Style`] to apply (`w:rStyle`), or `None`. Like
    /// `Paragraph.style_id`, not validated against `Document.styles` when writing.
    pub style_id: Option<String>,
    /// A hyperlink to apply to this run (`w:hyperlink`), or `None`. See [`Hyperlink`]'s doc comment
    /// for how this reconciles with the underlying XML, where a hyperlink actually wraps a run
    /// rather than being one of its properties.
    pub hyperlink: Option<Hyperlink>,
    /// The ids of the [`Comment`]s (`Document.comments`) whose range covers this run — usually
    /// empty, usually a single id, but a run can fall inside several overlapping comment ranges at
    /// once (real Word documents do have overlapping comments), hence a `Vec` rather than an
    /// `Option<u32>`.
    ///
    /// Strictly, in the underlying XML, a comment range is not a run property either:
    /// `w:commentRangeStart`/`w:commentRangeEnd` (`CT_MarkupRange`) are empty siblings of `w:r`
    /// marking where a range starts/ends, and `w:commentReference` (the balloon anchor mark) is its
    /// own run placed right after the matching `w:commentRangeEnd` — none of which the caller has
    /// to place by hand here, unlike [`NoteReference`]. The writer derives all three automatically:
    /// consecutive runs sharing an id become one `w:commentRangeStart`/`w:commentRangeEnd` pair
    /// spanning them (not one pair per run — that would emit the same id's start/end repeatedly,
    /// breaking the pairing `CT_MarkupRange`'s doc comment describes), with the matching
    /// `w:commentReference` written immediately after the range closes (see `write_paragraph` in
    /// `writer.rs`). Only comment ranges within a single paragraph are supported — WordprocessingML
    /// does allow a range to span several paragraphs or even wrap a whole table ("cross structure"
    /// annotations, ECMA-376 §2.13.4), out of scope for now, the same kind of deliberate scope
    /// limit as header/footer's "default"-only variant.
    pub comment_ids: Vec<u32>,
    /// The [`Bookmark`]s whose range covers this run — same range-tracking convention as
    /// `comment_ids`, but each bookmark's id/name pair travels directly with the run rather than
    /// being centralized in a separate `Document`-level list: unlike a comment reference (which
    /// only ever needs an id, since the name/author/date lives in `word/comments.xml`, a whole
    /// separate part), `w:bookmarkStart` carries its `w:name` right there on the inline marker
    /// itself, so there is no separate part `write_paragraph` would need to consult.
    ///
    /// Strictly, in the underlying XML, a bookmark range is not a run property either —
    /// `w:bookmarkStart`/`w:bookmarkEnd` (`CT_Bookmark`/ `CT_MarkupRange`) are empty siblings of
    /// `w:r`, members of the same `EG_PContent` choice group as `w:commentRangeStart`/
    /// `commentRangeEnd`, so the writer derives them the same way: runs sharing a bookmark id
    /// (repeated by the caller on each one, same asymmetry as `comment_ids`) become one
    /// `w:bookmarkStart`/ `w:bookmarkEnd` pair spanning them. Only bookmark ranges within a single
    /// paragraph are supported (not a range spanning several paragraphs, nor a zero-width "point"
    /// bookmark with no run content at all) — same deliberate scope limit as `comment_ids`.
    pub bookmarks: Vec<Bookmark>,
}

/// A named bookmark (`w:bookmarkStart`'s `w:name`, `CT_Bookmark`), attached to one or more runs via
/// `Run.bookmarks` to mark which run(s) fall within its range. `Hyperlink::Internal`'s anchor name
/// is meant to match a bookmark's `name` here for the resulting link to actually go anywhere in
/// Word — not validated when writing (same best-effort posture as `Paragraph.numbering_id`
/// referencing a declaration that may not exist).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Bookmark {
    /// This bookmark's id (`w:bookmarkStart`/`w:bookmarkEnd`'s `w:id`), pairing a start with its
    /// matching end — purely an internal wiring detail, never referenced from outside the document
    /// (unlike `name`, which is what `Hyperlink::Internal`'s anchor actually points to).
    pub id: u32,
    /// This bookmark's name (`w:bookmarkStart`'s `w:name`), what `Hyperlink::Internal(name)` refers
    /// to.
    pub name: String,
}

impl Bookmark {
    /// Creates a new bookmark with the given id and name. The id only needs to be unique among a
    /// paragraph's currently-open bookmarks (mirroring `comment_ids`'s own uniqueness scope) — this
    /// crate does not track or validate uniqueness across the whole document.
    pub fn new(id: u32, name: impl Into<String>) -> Self {
        Self {
            id,
            name: name.into(),
        }
    }
}

/// A hyperlink attached to a run (`w:hyperlink`, `CT_Hyperlink`): either a link to an external URL,
/// or a link to a bookmark elsewhere in the same document.
///
/// Strictly, in the underlying XML, a hyperlink is not a run property: `<w:hyperlink>` wraps its
/// own nested run(s) (`CT_Hyperlink`'s content is `EG_PContent`, the very same group `w:p` itself
/// uses), making it a sibling of `<w:r>` in a paragraph's content, much like [`Field`]'s
/// `<w:fldSimple>`. It is modeled here as a property on [`Run`] instead (alongside `style_id`,
/// `bold`..) for a simpler, more consistent public API — the run's own text/formatting still apply
/// normally, the hyperlink just adds link behavior on top. When several consecutive runs each set a
/// hyperlink, every one of them is written as its own separate `<w:hyperlink>` (and, for an
/// external link, its own OPC relationship, even when two runs happen to share the same URL) rather
/// than merged into a single wrapper — simpler and safer than trying to detect and dedupe repeated
/// URLs across runs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Hyperlink {
    /// A link to an external URL (`r:id`, an OPC relationship with `TargetMode="External"` — the
    /// target is never resolved or validated as a package part, unlike an image's `r:embed`).
    External(String),
    /// A link to a bookmark elsewhere in the same document (`w:anchor`), with no relationship at
    /// all. The anchor name is meant to match a [`Bookmark::name`] set via `Run.bookmarks`
    /// somewhere in the document, but this is not validated when writing — an `Internal` hyperlink
    /// to a name that isn't actually bookmarked anywhere still produces a well-formed `.docx`, just
    /// a dead link in Word.
    Internal(String),
}

/// A named style declared in `word/styles.xml` (`CT_Style`), applied to paragraphs or runs by id
/// (`Paragraph.style_id`/`Run.style_id`).
///
/// Only the handful of fields covering the common case — a name, an optional base style to inherit
/// from, and the same character/paragraph formatting already modeled on [`Run`]/[`Paragraph`] — are
/// modeled. `CT_Style` has many more (`next`, `link`, `hidden`, `uiPriority`, table-style-specific
/// properties..), out of scope for now; a style marked as the type's default (`CT_Style`'s
/// `default` attribute) isn't modeled either — Word falls back to its own built-in default when
/// none is declared, which is sufficient for a first version.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Style {
    /// The style's id (`w:styleId`), referenced by `Paragraph.style_id`/ `Run.style_id`.
    pub id: String,
    /// The style's human-readable name (`w:name`), shown in Word's style picker.
    pub name: String,
    /// Whether this is a paragraph or character style (`w:type`, `ST_StyleType` — only these two of
    /// its four values are modeled; `table`/`numbering` styles are out of scope for now).
    pub kind: StyleKind,
    /// The id of another style this one inherits from (`w:basedOn`), or `None`.
    pub based_on: Option<String>,
    /// Whether text in this style is bold. Meaningful for both style kinds: a paragraph style's run
    /// formatting is the default for text typed in that paragraph, unless a run/character style
    /// overrides it.
    pub bold: bool,
    /// Whether text in this style is italic.
    pub italic: bool,
    /// This style's underline style, mirroring `Run.underline`.
    pub underline: Option<UnderlineStyle>,
    /// This style's underline color, mirroring `Run.underline_color`.
    pub underline_color: Option<String>,
    /// This style's text color, mirroring `Run.color` — see that field's doc comment.
    pub color: Option<String>,
    /// This style's font size in whole points, mirroring `Run.font_size`.
    pub font_size: Option<u16>,
    /// This style's font family/typeface, mirroring `Run.font_family`.
    pub font_family: Option<String>,
    /// This style's highlight color, mirroring `Run.highlight`.
    pub highlight: Option<Highlight>,
    /// Whether text in this style is struck through, mirroring `Run.strike`.
    pub strike: bool,
    /// This style's vertical alignment, mirroring `Run.vertical_align`.
    pub vertical_align: Option<VerticalAlign>,
    /// Whether text in this style is displayed as small caps, mirroring `Run.small_caps`.
    pub small_caps: bool,
    /// Whether text in this style is displayed as all caps, mirroring `Run.all_caps`.
    pub all_caps: bool,
    /// This style's background shading color, mirroring `Run.shading_color`.
    pub shading_color: Option<String>,
    /// Whether text in this style has a border, mirroring `Run.text_border`.
    pub text_border: bool,
    /// This style's character spacing adjustment, mirroring `Run.character_spacing`.
    pub character_spacing: Option<i16>,
    /// This style's vertical position, mirroring `Run.vertical_position`.
    pub vertical_position: Option<i16>,
    /// Whether text in this style is hidden, mirroring `Run.hidden`.
    pub hidden: bool,
    /// The paragraph alignment this style sets. Only meaningful for [`StyleKind::Paragraph`];
    /// ignored (not written) for a character style, which has no paragraph-level formatting of its
    /// own.
    pub alignment: Option<Alignment>,
    /// This style's line spacing, mirroring `Paragraph.line_spacing`. Only meaningful for
    /// [`StyleKind::Paragraph`], same restriction as `alignment`.
    pub line_spacing: Option<u32>,
    /// This style's extra space before a paragraph, mirroring `Paragraph.space_before`. Only
    /// meaningful for [`StyleKind::Paragraph`].
    pub space_before: Option<u32>,
    /// This style's extra space after a paragraph, mirroring `Paragraph.space_after`. Only
    /// meaningful for [`StyleKind::Paragraph`].
    pub space_after: Option<u32>,
    /// This style's paragraph background shading color, mirroring `Paragraph.shading_color`.
    /// Distinct from `shading_color` above (that one mirrors `Run.shading_color`, a run-level
    /// `w:shd` inside `w:rPr`) — this is the paragraph-level `w:shd` inside `w:pPr`; a paragraph
    /// style can carry both at once (default run shading AND a paragraph background), which is why
    /// they need separate fields. Only meaningful for [`StyleKind::Paragraph`].
    pub paragraph_shading_color: Option<String>,
    /// Whether this style draws a border around the paragraph, mirroring `Paragraph.border`.
    /// Distinct from `text_border` above for the same reason as `paragraph_shading_color` vs.
    /// `shading_color` — a paragraph-level `w:pBdr` inside `w:pPr`, not the run-level `w:bdr`
    /// inside `w:rPr`. Only meaningful for [`StyleKind::Paragraph`].
    pub paragraph_border: bool,
    /// This style's keep-with-next setting, mirroring `Paragraph.keep_with_next`. Only meaningful
    /// for [`StyleKind::Paragraph`] — commonly set directly on a built-in "Heading" style rather
    /// than on every individual heading paragraph.
    pub keep_with_next: bool,
    /// This style's keep-lines-together setting, mirroring `Paragraph.keep_lines_together`. Only
    /// meaningful for [`StyleKind::Paragraph`].
    pub keep_lines_together: bool,
    /// This style's page-break-before setting, mirroring `Paragraph.page_break_before`. Only
    /// meaningful for [`StyleKind::Paragraph`].
    pub page_break_before: bool,
    /// This style's custom tab stops, mirroring `Paragraph.tabs`. Only meaningful for
    /// [`StyleKind::Paragraph`].
    pub tabs: Vec<TabStop>,
    /// This style's contextual-spacing setting, mirroring `Paragraph.contextual_spacing`. Only
    /// meaningful for [`StyleKind::Paragraph`] — this is exactly the property Word's own built-in
    /// "List Paragraph" style sets, so consecutive list items don't get extra gaps between them.
    pub contextual_spacing: bool,
}

/// Which kind of content a [`Style`] applies to (`ST_StyleType`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StyleKind {
    /// Applies to a whole paragraph (`Paragraph.style_id`).
    Paragraph,
    /// Applies to a run (`Run.style_id`).
    Character,
}

impl StyleKind {
    /// This kind's `w:type` attribute value (`ST_StyleType`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            StyleKind::Paragraph => "paragraph",
            StyleKind::Character => "character",
        }
    }
}

/// A numbering (list) definition declared in `word/numbering.xml`, referenced from paragraphs
/// (`Paragraph.numbering_id`) by id.
///
/// WordprocessingML actually splits a list definition into two linked elements: `w:abstractNum`
/// (the real level formatting, `CT_AbstractNum`) and `w:num` (`CT_Num`, a thin indirection
/// paragraphs reference by `numId`, pointing at an `abstractNumId`) — this indirection exists so
/// several `w:num` entries can share one `w:abstractNum`, which real Word documents do use, but
/// which this crate doesn't need for the common case of one standalone list. So this type collapses
/// both into one value: `id` corresponds to `w:num`'s `numId` (what a paragraph actually
/// references), and a dedicated `w:abstractNum` is always written alongside it internally — see
/// `writer.rs`. Reading back a real, externally-authored document that DOES share one
/// `w:abstractNum` across several `w:num` entries still works (each `w:num` becomes its own
/// [`NumberingDefinition`], with its `levels` resolved through whichever `w:abstractNum` it points
/// to), just without preserving that sharing structure on a round trip.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumberingDefinition {
    /// This definition's id (`w:num`'s `w:numId`), referenced by `Paragraph.numbering_id`.
    pub id: u32,
    /// The formatting for each indent level this list defines, in order (index 0 is the outermost
    /// level, `w:lvl`'s `ilvl="0"`). WordprocessingML allows up to 9 (`ilvl` 0-8); most real lists
    /// only need 1-3.
    pub levels: Vec<ListLevel>,
}

/// A single indent level of a [`NumberingDefinition`] (`w:lvl`, `CT_Lvl`).
///
/// Only the handful of properties needed to produce a correctly-formatted, correctly-indented list
/// are modeled (`numFmt`, `lvlText`, and the indentation `CT_Lvl`'s own `pPr` sets) — not `pStyle`
/// (a paragraph style tied to the level), `lvlPicBulletId` (a picture bullet), `lvlJc`
/// (WordprocessingML lets a level's own number/bullet be right/center aligned within its indent —
/// always left here, matching the common case), `suff` (what follows the number: tab/space/nothing
/// — always a tab, Word's default), or per-level run formatting (`rPr`) — a deliberately plain
/// bullet/number, styled the same as the surrounding text, rather than needing this crate to also
/// model fonts just to reproduce Word's own Wingdings/Symbol-font bullet glyphs.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ListLevel {
    /// How this level's number/bullet is formatted (`w:numFmt`).
    pub format: NumberFormat,
    /// The level's number/bullet template (`w:lvlText`'s `val`) — a literal bullet character for
    /// [`NumberFormat::Bullet`] (e.g. `"•"`), or a placeholder template for the numbered formats,
    /// where `%1` is this level's own counter and `%2`/`%3`/. refer to ancestor levels' counters
    /// (e.g. `"%1."` for a simple "1.", or `"%1.%2."` for a second level that repeats its parent's
    /// number, matching Word's own default multilevel numbering).
    pub text: String,
    /// This level's left indent, in twips (1/20 pt) — `w:pPr/w:ind`'s `left` attribute.
    pub indent_twips: i32,
    /// How far the number/bullet hangs to the left of the following text's left edge, in twips —
    /// `w:pPr/w:ind`'s `hanging` attribute. Word's own default lists always use `360` regardless of
    /// level.
    pub hanging_twips: i32,
}

/// How a [`ListLevel`]'s number/bullet is formatted (`w:numFmt`, `ST_NumberFormat`).
///
/// `ST_NumberFormat` defines dozens of values (`chicago`, `hex`, `ideographDigital`, several
/// locale-specific numbering systems..); only the handful in everyday use in Word's own list
/// gallery are modeled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumberFormat {
    /// An unordered (bulleted) list.
    Bullet,
    /// "1, 2, 3..".
    Decimal,
    /// "a, b, c..".
    LowerLetter,
    /// "A, B, C..".
    UpperLetter,
    /// "i, ii, iii..".
    LowerRoman,
    /// "I, II, III..".
    UpperRoman,
}

impl NumberFormat {
    /// This format's `w:numFmt`/`val` value (`ST_NumberFormat`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            NumberFormat::Bullet => "bullet",
            NumberFormat::Decimal => "decimal",
            NumberFormat::LowerLetter => "lowerLetter",
            NumberFormat::UpperLetter => "upperLetter",
            NumberFormat::LowerRoman => "lowerRoman",
            NumberFormat::UpperRoman => "upperRoman",
        }
    }
}

/// A reference to a footnote or endnote (`<w:footnoteReference>`/ `<w:endnoteReference>`, both
/// `CT_FtnEdnRef`), placed in the document body to point at a [`Note`] declared in
/// `Document.footnotes`/ `Document.endnotes` by id.
///
/// Unlike [`Hyperlink`] or [`Field`], this genuinely is run content in the underlying XML —
/// `footnoteReference`/`endnoteReference` are members of `EG_RunInnerContent`, the same group `w:t`
/// belongs to, so no wrapping element is needed around the run.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoteReference {
    /// References a footnote by id (`Document.footnotes`).
    Footnote(u32),
    /// References an endnote by id (`Document.endnotes`).
    Endnote(u32),
}

/// Which kind of note a [`RunContent::NoteMarker`] renders the number of
/// (`<w:footnoteRef/>`/`<w:endnoteRef/>`, both `CT_Empty`).
///
/// Used as the first run of a footnote/endnote's own first paragraph, to render its own number
/// inline with its text — e.g. the superscript "1" at the very start of a footnote's text. Distinct
/// from [`NoteReference`], which is what goes in the document body to point *at* a note; this is
/// what goes *inside* the note itself, rendering its own number.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NoteKind {
    Footnote,
    Endnote,
}

/// A single footnote or endnote's content (`CT_FtnEdn`) — the same block-level content model as the
/// document body (`EG_BlockLevelElts`, the same group `w:body`/[`HeaderFooter`] use), referenced
/// from the body by id via [`NoteReference`].
///
/// Only `type="normal"` notes are modeled. Real Word documents also always carry two boilerplate
/// notes per part (`type="separator"`/ `type="continuationSeparator"`, the horizontal rule Word
/// draws above its footnotes) — this crate never writes them; Word simply falls back to its own
/// built-in default separator when they're absent. Any such special notes found when reading an
/// existing document are silently skipped rather than exposed here.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Note {
    /// This note's id, referenced by [`NoteReference`].
    pub id: u32,
    /// The blocks that make up this note's content, in order.
    pub blocks: Vec<Block>,
}

/// A single comment's content (`<w:comment>`, `CT_Comment`), declared in `word/comments.xml` and
/// anchored to a range of the body via `Run.comment_ids` — see that field's doc comment for how the
/// underlying `w:commentRangeStart`/`w:commentRangeEnd`/`w:commentReference` markers are derived
/// automatically rather than modeled here.
///
/// `CT_Comment` extends `CT_TrackChange` (`id`, `author`, `date`) and adds `initials`, plus the
/// same block-level content model as the document body (`EG_BlockLevelElts`, like
/// [`Note`]/[`HeaderFooter`]). A `<w:annotationRef/>` (`CT_Empty`) may optionally mark this
/// comment's own reference mark inside its content — not modeled: ECMA-376 §2.13.4.1 explicitly
/// allows omitting it ("an annotation reference mark may be added. by the consumer"), and Word's
/// Reviewing pane balloon already shows `author`/`date`/`initials` from this element's own
/// attributes without needing it, unlike a footnote/endnote's number marker (`NoteMarker`), which
/// genuinely is the only thing that renders the note's number at all.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Comment {
    /// This comment's id, referenced by `Run.comment_ids`.
    pub id: u32,
    /// The comment's author (`w:author`), shown in Word's Reviewing pane.
    pub author: Option<String>,
    /// The author's initials (`w:initials`), shown next to the comment's reference mark in the
    /// body.
    pub initials: Option<String>,
    /// When the comment was made (`w:date`), stored verbatim as a plain `xs:dateTime` string (e.g.
    /// `"2024-01-01T12:00:00Z"`) rather than parsed into a real date/time type — this crate doesn't
    /// otherwise need a date/time dependency, so round-tripping this one attribute as text avoids
    /// adding one just for this. The caller is responsible for a valid `xs:dateTime` value if
    /// Word's own date display matters.
    pub date: Option<String>,
    /// The blocks that make up this comment's content, in order.
    pub blocks: Vec<Block>,
}

/// A block-level structured document tag / content control (`<w:sdt>`, `CT_SdtBlock`), wrapping one
/// or more paragraphs/tables — one of the three alternatives `EG_ContentBlockContent` allows
/// anywhere a [`Block`] can appear (body, header/footer, table cell content, a note's or comment's
/// own content..), hence a [`Block`] variant rather than its own separate top-level list the way
/// [`Note`]/[`Comment`] are.
///
/// WordprocessingML defines a dozen-plus specific content-control "types" (plain text, rich text,
/// date picker, drop-down list, combo box, picture, citation, group, bibliography, equation,
/// built-in document part..) via `w:sdtPr`'s `text`/`richText`/`date`/`dropDownList`/. child
/// (`CT_SdtPr`'s own inner `choice`) — none of these are modeled here, only the type-agnostic
/// identifying metadata (`id`/`tag`/`alias`) and the content itself. SDTs remain a niche,
/// fast-evolving corner of the format with little real demand seen yet for anything beyond
/// read-only handling, so unlike every other feature in this crate there is deliberately no
/// *creation*/write API for SDTs at all. Omitting the type indicator entirely is schema-valid
/// regardless (`CT_SdtPr`'s inner `choice` has `minOccurs="0"`): Word treats a content control with
/// no declared type as a generic one, still fully functional.
///
/// Only the block-level form (`CT_SdtBlock`, wherever a [`Block`] can appear) is modeled —
/// WordprocessingML also defines inline-level (wrapping run content inside a paragraph), row-level
/// and cell-level variants (`CT_SdtRun`/`CT_SdtRow`/`CT_SdtCell`), none of which are supported yet.
/// A block-level content control *can* appear inside a table cell, though — since
/// [`TableCell::blocks`] is `Vec<Block>`, the same as everywhere else a [`Block`] is valid — it's
/// specifically the dedicated `CT_SdtCell` form (matching the cell's own boundaries rather than
/// wrapping arbitrary content within it) that isn't modeled.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct StructuredDocumentTag {
    /// A unique identifier Word assigns the control (`w:sdtPr/w:id`, `CT_DecimalNumber` — signed
    /// per the schema, though Word's own generator only ever produces positive values in practice).
    pub id: Option<i32>,
    /// The programmatic tag (`w:sdtPr/w:tag`) — the id automation code (VBA, the OpenXML SDK..)
    /// uses to find this control by, distinct from the human-facing `alias`.
    pub tag: Option<String>,
    /// The friendly/display name (`w:sdtPr/w:alias`) shown in Word's UI (e.g. the control's tab on
    /// the Developer ribbon) — distinct from `tag`.
    pub alias: Option<String>,
    /// The blocks that make up this control's content, in order.
    pub blocks: Vec<Block>,
}

/// A document's theme (`word/theme/theme1.xml`, `CT_OfficeStyleSheet`, root element `<a:theme>`) —
/// the combination of color scheme and font scheme behind Word's own "Theme Colors"/"Theme Fonts"
/// palettes, and behind what Word's built-in heading styles (Heading 1-9, Title..) resolve to,
/// since those are defined in terms of theme slots inside Word's own built-in style definitions
/// rather than anything in `Document.styles`. This crate's own [`Style`]/[`Run`] formatting never
/// references a theme slot — `color`/`highlight`/`underline_color` are always literal values, never
/// `w:themeColor` — so a [`Theme`] mainly matters for controlling those built-in styles' appearance
/// and for round-tripping a document's existing theme unchanged.
///
/// A theme part also requires `fmtScheme` (a fill/line/effect "style matrix", `CT_StyleMatrix` —
/// `CT_BaseStyles`'s three children, `clrScheme`/`fontScheme`/`fmtScheme`, are all
/// `minOccurs="1"`), which is relevant almost entirely to DrawingML shapes/charts, out of scope for
/// `word-ooxml` entirely (see [`Image`]'s doc comment on what DrawingML content this crate does
/// support). It is always written as a fixed copy of Office's own built-in default rather than also
/// modeled here: each of `fmtScheme`'s four lists (`fillStyleLst`/`lnStyleLst`/`effectStyleLst`/
/// `bgFillStyleLst`) is a `minOccurs="3" maxOccurs="3"` sequence of DrawingML fill/line/effect
/// definitions, non-trivial to also expose as configurable, and no real need for that has come up —
/// the same deliberate scope limit as the fixed default `w:sectPr` written since.
/// `objectDefaults`/`extraClrSchemeLst` (both `minOccurs="0"` on `CT_OfficeStyleSheet` itself) are
/// omitted entirely rather than also given a fixed default, since omitting them outright is simpler
/// and just as schema-valid.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Theme {
    /// The theme's name (`<a:theme name="..">`), shown in Word's Design > Themes gallery. Also
    /// reused, unchanged, as the `name` attribute of the nested `<a:clrScheme>`/`<a:fontScheme>`
    /// elements when writing — real Word-authored themes usually give all three the same name (e.g.
    /// `"Office"`), and this crate doesn't model them separately.
    pub name: String,
    /// The theme's 12-color palette.
    pub colors: ColorScheme,
    /// The theme's heading/body typefaces.
    pub fonts: FontScheme,
}

/// A theme's 12-color palette (`<a:clrScheme>`, `CT_ColorScheme`): two dark/ light pairs, six
/// accents, and two hyperlink colors — the palette behind Word's "Theme Colors" swatches and
/// `w:themeColor`-based direct formatting (`CT_Color`'s theme-color choice, not modeled on [`Run`]/
/// [`Style`] itself, which only ever carry literal RGB colors).
///
/// Every slot is stored as a plain 6-digit RGB hex string (no leading `#`, e.g. `"4F81BD"`),
/// written as `<a:srgbClr val="..">`. `CT_Color`'s other choice, `<a:sysClr>` (binding a slot to a
/// live Windows system color, with a fallback RGB for non-Windows renderers) — what Word's own
/// default theme actually uses for `dk1`/`lt1` (bound to `windowText`/`window`) — is not modeled
/// for writing; a plain `srgbClr` is schema-valid in its place and renders identically outside of
/// that live system-color binding, which this crate has no way to honor anyway (a document it
/// writes isn't tied to any running Windows session). Reading back a real, externally-authored
/// theme that does use `<a:sysClr>` for a slot still works: its fallback RGB (`lastClr`) is
/// captured instead of the live binding, which is lost on a round trip — see `reader.rs`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ColorScheme {
    pub dark1: String,
    pub light1: String,
    pub dark2: String,
    pub light2: String,
    pub accent1: String,
    pub accent2: String,
    pub accent3: String,
    pub accent4: String,
    pub accent5: String,
    pub accent6: String,
    pub hyperlink: String,
    pub followed_hyperlink: String,
}

/// A theme's font scheme (`<a:fontScheme>`, `CT_FontScheme`): a heading ("major") and body
/// ("minor") typeface, behind Word's "Theme Fonts" and built-in heading styles.
///
/// Only the Latin typeface of each is modeled (`<a:latin typeface="..">`). `CT_FontCollection` also
/// requires an East Asian and complex-script typeface (`ea`/`cs`, each `minOccurs="1"`) and allows
/// a further list of per-script fallback typefaces (`font`, e.g. `script="Jpan"`) — the writer
/// always emits `ea`/`cs` with an empty `typeface=""` (schema-valid, and exactly what a Latin-only
/// real Word theme does) and omits the per-script fallback list entirely (its own `minOccurs="0"`,
/// so this is valid too); Word simply falls back to its own built-in per-script defaults. Reading a
/// real theme that does declare `ea`/`cs`/per-script fonts silently ignores them, same scope limit
/// as writing.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FontScheme {
    pub major_latin: String,
    pub minor_latin: String,
}

/// A run's text highlight color (`<w:highlight w:val="..">`, `CT_Highlight`, `ST_HighlightColor`) —
/// a fixed palette of "highlighter" colors applied as a background behind a run's text, distinct
/// from `Run.color` (an arbitrary literal RGB text color) and from an arbitrary shaded background
/// fill (`w:shd`, not modeled).
///
/// `ST_HighlightColor` also defines the value `"none"`, explicitly clearing any inherited
/// highlighting — not modeled as its own variant here, since `Run.highlight: Option<Highlight>`
/// already expresses "no highlight" via `None` (omitting `w:highlight` entirely achieves the same
/// visual result for a run with nothing to inherit from).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Highlight {
    Black,
    Blue,
    Cyan,
    DarkBlue,
    DarkCyan,
    DarkGray,
    DarkGreen,
    DarkMagenta,
    DarkRed,
    DarkYellow,
    Green,
    LightGray,
    Magenta,
    Red,
    White,
    Yellow,
}

impl Highlight {
    /// This highlight's `w:highlight`/`val` value (`ST_HighlightColor`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            Highlight::Black => "black",
            Highlight::Blue => "blue",
            Highlight::Cyan => "cyan",
            Highlight::DarkBlue => "darkBlue",
            Highlight::DarkCyan => "darkCyan",
            Highlight::DarkGray => "darkGray",
            Highlight::DarkGreen => "darkGreen",
            Highlight::DarkMagenta => "darkMagenta",
            Highlight::DarkRed => "darkRed",
            Highlight::DarkYellow => "darkYellow",
            Highlight::Green => "green",
            Highlight::LightGray => "lightGray",
            Highlight::Magenta => "magenta",
            Highlight::Red => "red",
            Highlight::White => "white",
            Highlight::Yellow => "yellow",
        }
    }

    /// Parses a `w:highlight`/`val` value (`ST_HighlightColor`) back into a [`Highlight`], or
    /// `None` for `"none"` or an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "black" => Some(Highlight::Black),
            "blue" => Some(Highlight::Blue),
            "cyan" => Some(Highlight::Cyan),
            "darkBlue" => Some(Highlight::DarkBlue),
            "darkCyan" => Some(Highlight::DarkCyan),
            "darkGray" => Some(Highlight::DarkGray),
            "darkGreen" => Some(Highlight::DarkGreen),
            "darkMagenta" => Some(Highlight::DarkMagenta),
            "darkRed" => Some(Highlight::DarkRed),
            "darkYellow" => Some(Highlight::DarkYellow),
            "green" => Some(Highlight::Green),
            "lightGray" => Some(Highlight::LightGray),
            "magenta" => Some(Highlight::Magenta),
            "red" => Some(Highlight::Red),
            "white" => Some(Highlight::White),
            "yellow" => Some(Highlight::Yellow),
            _ => None,
        }
    }
}

/// A run's vertical alignment (`<w:vertAlign w:val="..">`, `CT_VerticalAlignRun`,
/// `ST_VerticalAlignRun`) — superscript or subscript text, rendered smaller and shifted above/below
/// the normal baseline without otherwise altering the run's own font size.
///
/// `ST_VerticalAlignRun` also defines the value `"baseline"`, the normal, non-shifted position —
/// not modeled as its own variant here, since `Run.vertical_align: Option<VerticalAlign>` already
/// expresses "normal position" via `None` (omitting `w:vertAlign` entirely achieves the same visual
/// result for a run with nothing to inherit from), same convention as [`Highlight`]'s own `"none"`
/// value.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerticalAlign {
    Superscript,
    Subscript,
}

impl VerticalAlign {
    /// This vertical alignment's `w:vertAlign`/`val` value (`ST_VerticalAlignRun`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            VerticalAlign::Superscript => "superscript",
            VerticalAlign::Subscript => "subscript",
        }
    }

    /// Parses a `w:vertAlign`/`val` value (`ST_VerticalAlignRun`) back into a [`VerticalAlign`], or
    /// `None` for `"baseline"` or an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "superscript" => Some(VerticalAlign::Superscript),
            "subscript" => Some(VerticalAlign::Subscript),
            _ => None,
        }
    }
}

/// A run's underline style (`<w:u w:val="..">`, `CT_Underline`, `ST_Underline`) — the pattern of
/// the line drawn beneath a run's text (single, double, thick, dotted, dashed, wavy, and
/// combinations of those), distinct from `Run.underline_color` (the line's color, a separate
/// attribute on the same `w:u` element).
///
/// `ST_Underline` also defines the value `"none"`, explicitly clearing any inherited underline —
/// not modeled as its own variant here, since `Run.underline: Option<UnderlineStyle>` already
/// expresses "no underline" via `None` (omitting `w:u` entirely achieves the same visual result for
/// a run with nothing to inherit from), same convention as [`Highlight`]'s own `"none"` value and
/// [`VerticalAlign`]'s `"baseline"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnderlineStyle {
    Single,
    Words,
    Double,
    Thick,
    Dotted,
    DottedHeavy,
    Dash,
    DashedHeavy,
    DashLong,
    DashLongHeavy,
    DotDash,
    DashDotHeavy,
    DotDotDash,
    DashDotDotHeavy,
    Wave,
    WavyHeavy,
    WavyDouble,
}

impl UnderlineStyle {
    /// This underline style's `w:u`/`val` value (`ST_Underline`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            UnderlineStyle::Single => "single",
            UnderlineStyle::Words => "words",
            UnderlineStyle::Double => "double",
            UnderlineStyle::Thick => "thick",
            UnderlineStyle::Dotted => "dotted",
            UnderlineStyle::DottedHeavy => "dottedHeavy",
            UnderlineStyle::Dash => "dash",
            UnderlineStyle::DashedHeavy => "dashedHeavy",
            UnderlineStyle::DashLong => "dashLong",
            UnderlineStyle::DashLongHeavy => "dashLongHeavy",
            UnderlineStyle::DotDash => "dotDash",
            UnderlineStyle::DashDotHeavy => "dashDotHeavy",
            UnderlineStyle::DotDotDash => "dotDotDash",
            UnderlineStyle::DashDotDotHeavy => "dashDotDotHeavy",
            UnderlineStyle::Wave => "wave",
            UnderlineStyle::WavyHeavy => "wavyHeavy",
            UnderlineStyle::WavyDouble => "wavyDouble",
        }
    }

    /// Parses a `w:u`/`val` value (`ST_Underline`) back into an [`UnderlineStyle`], or `None` for
    /// `"none"` or an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "single" => Some(UnderlineStyle::Single),
            "words" => Some(UnderlineStyle::Words),
            "double" => Some(UnderlineStyle::Double),
            "thick" => Some(UnderlineStyle::Thick),
            "dotted" => Some(UnderlineStyle::Dotted),
            "dottedHeavy" => Some(UnderlineStyle::DottedHeavy),
            "dash" => Some(UnderlineStyle::Dash),
            "dashedHeavy" => Some(UnderlineStyle::DashedHeavy),
            "dashLong" => Some(UnderlineStyle::DashLong),
            "dashLongHeavy" => Some(UnderlineStyle::DashLongHeavy),
            "dotDash" => Some(UnderlineStyle::DotDash),
            "dashDotHeavy" => Some(UnderlineStyle::DashDotHeavy),
            "dotDotDash" => Some(UnderlineStyle::DotDotDash),
            "dashDotDotHeavy" => Some(UnderlineStyle::DashDotDotHeavy),
            "wave" => Some(UnderlineStyle::Wave),
            "wavyHeavy" => Some(UnderlineStyle::WavyHeavy),
            "wavyDouble" => Some(UnderlineStyle::WavyDouble),
            _ => None,
        }
    }
}

/// The content of a [`Run`]: text, a single inline image, a field (e.g. a page number), a reference
/// to a footnote/endnote, or a footnote/endnote's own number marker.
///
/// WordprocessingML's `EG_RunInnerContent` technically allows a run to mix several kinds of content
/// (e.g. text followed by a line break followed by more text), but that generality isn't modeled
/// yet — a run is either all text, a single image, a single field, a single note reference/marker,
/// or a single break. Split content across multiple runs (e.g. one text run, then a break run, then
/// another text run) if that's needed — this crate always represents a break as a run of its own,
/// rather than mixing content kinds within a single run. Note that a [`Field`] is, strictly, not
/// really "inside" a run in the underlying XML (`<w:fldSimple>` is a sibling of `<w:r>`, wrapping
/// its own inner run) — it is modeled here as run content anyway, for a simpler, more consistent
/// public API; see `writer.rs`'s `write_field` for how this is reconciled when serializing.
/// `NoteReference`/`NoteMarker`/`Break`/ `CarriageReturn`, by contrast, really are plain run
/// content (`EG_RunInnerContent` members), no reconciliation needed.
#[derive(Debug, Clone, PartialEq)]
pub enum RunContent {
    Text(String),
    /// An inline image. Boxed for the same reason as `Chart` below — once `Chart` was boxed,
    /// clippy's `large_enum_variant` moved on to flag this as the new largest variant (an `Image`
    /// carries its own encoded bytes plus shape-formatting fields).
    Image(Box<Image>),
    Field(Field),
    NoteReference(NoteReference),
    NoteMarker(NoteKind),
    /// An embedded chart (`<w:drawing><wp:inline>` wrapping a `<c:chart r:id="..">` graphic frame
    /// instead of a picture). See [`EmbeddedChart`]'s doc comment. Boxed for the same reason as
    /// `powerpoint-ooxml`'s `Shape::Chart` — a chart's own nested `ChartSpace` otherwise forces
    /// every `RunContent`, whatever its real kind, to pay for the largest variant's size.
    Chart(Box<EmbeddedChart>),
    /// An explicit page/column/line break (`<w:br>`, `CT_Br`). See [`BreakKind`]'s doc comment.
    Break(BreakKind),
    /// A simple carriage return / line break (`<w:cr/>`, `CT_Empty`) — distinct from
    /// `Break(BreakKind::TextWrapping)`: both produce a line break, but `w:cr` is
    /// WordprocessingML's older, simpler element for it (no `type`/`clear` attributes at all),
    /// while `w:br` with `type="textWrapping"` is the modern, more general one. This crate writes
    /// whichever the caller explicitly asks for; both round-trip back to their own distinct variant
    /// when read.
    CarriageReturn,
}

impl Default for RunContent {
    fn default() -> Self {
        RunContent::Text(String::new())
    }
}

/// The kind of an explicit break (`<w:br w:type="..">`, `CT_Br`, `ST_BrType`), see
/// [`RunContent::Break`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BreakKind {
    /// Forces a page break at this point in the text.
    Page,
    /// Forces a column break (only meaningful in a multi-column section, see
    /// [`PageSetup::columns`]).
    Column,
    /// A line break within the same paragraph (the text continues on the next line without starting
    /// a new paragraph) — `ST_BrType`'s default value when `w:br`'s `type` attribute is omitted
    /// entirely.
    TextWrapping,
}

impl BreakKind {
    /// This break kind's `w:br`/`type` value (`ST_BrType`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            BreakKind::Page => "page",
            BreakKind::Column => "column",
            BreakKind::TextWrapping => "textWrapping",
        }
    }

    /// Parses a `w:br`/`type` value (`ST_BrType`) back into a [`BreakKind`], defaulting to
    /// `TextWrapping` for a missing/ unrecognized value — matching `ST_BrType`'s own documented
    /// default for an omitted `type` attribute.
    pub fn from_attribute_value(value: Option<&str>) -> Self {
        match value {
            Some("page") => BreakKind::Page,
            Some("column") => BreakKind::Column,
            _ => BreakKind::TextWrapping,
        }
    }
}

/// A WordprocessingML "simple field" (`<w:fldSimple w:instr="..">`, `CT_SimpleField`) — a value
/// Word computes and keeps up to date, most commonly a page number.
///
/// Only the two most common, simplest field codes are modeled. WordprocessingML supports many more
/// (`DATE`, `AUTHOR`, `TOC`..), most of which need the more elaborate "complex field" construct
/// (`w:fldChar` begin/separate/end, spanning several runs) rather than `fldSimple` to update
/// correctly in Word, so they are out of scope for now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Field {
    /// The current page number (`PAGE` field code).
    PageNumber,
    /// The total number of pages in the document (`NUMPAGES` field code).
    TotalPages,
}

impl Field {
    /// The field's instruction text (`w:instr`, `CT_SimpleField`'s required attribute).
    pub fn instruction(self) -> &'static str {
        match self {
            Field::PageNumber => "PAGE",
            Field::TotalPages => "NUMPAGES",
        }
    }
}

/// An inline image (`<w:drawing><wp:inline>..`), embedded in a run.
///
/// Structure is a minimal `wp:inline`/`pic:pic` skeleton (no rotation, cropping or other DrawingML
/// effects yet).
#[derive(Debug, Clone, PartialEq)]
pub struct Image {
    /// The raw, encoded image bytes (e.g. the bytes of a `.png` file).
    pub data: Vec<u8>,
    /// The image's encoding, also used to pick the media part's extension and content type.
    pub format: ImageFormat,
    /// The width the image is displayed at, in EMUs (English Metric Units; 914,400 EMU per inch —
    /// `CT_PositiveSize2D`'s `cx`). Display size, not necessarily the image's native pixel size.
    pub width_emu: i64,
    /// The height the image is displayed at, in EMUs (`cy`).
    pub height_emu: i64,
    /// Alt text / description (`wp:docPr`'s `descr` attribute). May be empty.
    pub description: String,
    /// Additional shape formatting (fill/line/rotation) for the picture's own `pic:spPr`. `None`
    /// (the only value this crate produced before this point existed) preserves the exact
    /// fixed-rectangle geometry `writer.rs::write_drawing` always wrote; `Some` enriches that
    /// `spPr` with the given content (reusing
    /// `drawing::write_shape_properties`/`drawing::read_shape_properties`) without changing the
    /// fixed `a:xfrm`/size handling, which stays governed by `width_emu`/`height_emu` as before.
    /// Purely additive: no existing round-trip test is affected since none of them ever set this
    /// field.
    pub shape_properties: Option<drawing::ShapeProperties>,
}

/// The number of EMUs (English Metric Units) per inch, used to convert pixel dimensions to the EMU
/// units WordprocessingML expects.
pub const EMU_PER_INCH: i64 = 914_400;

/// An image's file format, also determining its media content type.
///
/// Only the handful of raster formats Word natively displays inline are modeled; vector formats
/// (e.g. EMF/WMF metafiles) and other DrawingML content (shapes, charts) are out of scope for now.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImageFormat {
    Png,
    Jpeg,
    Gif,
    Bmp,
}

/// A table: a sequence of rows.
///
/// Column count is always derived from the widest row (accounting for `TableCell.horizontal_span`),
/// never stored explicitly. Column WIDTHS default to equal, fixed widths (see `writer.rs`'s
/// `DEFAULT_COLUMN_WIDTH_TWIPS`) unless `column_widths` overrides them.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Table {
    /// The rows that make up this table, in order.
    pub rows: Vec<TableRow>,
    /// Per-column preferred widths, in twips (twentieths of a point, `w:gridCol/@w`'s own unit —
    /// see `Run.character_spacing`'s doc comment for the same "expose the raw unit, no conversion"
    /// convention used throughout this crate), one entry per grid column in order. Left empty (the
    /// default) to keep the writer's previous behavior: every column gets the same fixed default
    /// width. When non-empty, entries beyond the table's real column count are simply unused, and a
    /// real column count exceeding `column_widths.len()` falls back to the default width for the
    /// remaining columns — not validated or required to match exactly, same "best-effort, not
    /// strictly enforced" policy as `Paragraph.numbering_id`/`style_id` referencing a declaration
    /// that may or may not actually exist.
    ///
    /// Setting this also makes the writer emit `<w:tblLayout w:type="fixed"/>`
    /// (`CT_TblLayoutType`'s two values are `fixed`/ `autofit`, `autofit` being Word's default when
    /// the element is omitted entirely). This matters a lot in practice: under the default
    /// `autofit` layout, Word treats `tblGrid`'s widths as mere starting suggestions and actively
    /// reflows columns based on cell content ("the presence of long non-breaking content can widen
    /// a column, proportionally shrinking the others" — ECMA-376's own worked example for
    /// `ST_TblLayoutType`) — so explicit widths would often be silently overridden without `fixed`
    /// layout forcing Word to honor them regardless of content.
    pub column_widths: Vec<u32>,
    /// The color of the table's own border lines (`w:tblBorders`'s sides' `color` attribute, a
    /// plain 6-digit RGB hex string), or `None` to use the fixed `"auto"` (black) this crate has
    /// always used. Overrides all six sides (`top`/`left`/`bottom`/`right`/`insideH`/`insideV`)
    /// uniformly — WordprocessingML allows each side its own independent color, but a single
    /// uniform color covers the common case and matches the fixed-appearance convention already
    /// used for `Paragraph.border`/`Run.text_border`/`TableCell.border`.
    pub border_color: Option<String>,
    /// The table's own horizontal alignment/positioning on the page (`w:tblPr/w:jc`, `CT_JcTable`)
    /// — where the whole table sits relative to the page margins, distinct from
    /// `Paragraph.alignment` (which aligns text within a paragraph). `None` leaves it unspecified
    /// (Word's default, effectively left-aligned). Reuses [`Alignment`] even though `CT_JcTable`'s
    /// own enumeration (`ST_JcTable`) is actually a different, smaller type than `ST_Jc` (no
    /// `distribute`, but it does still cover `left`/`center`/`right`/`both`) — the values this
    /// crate models for `Alignment` (`Left`/`Center`/`Right`/`Justify`) all happen to also be valid
    /// `ST_JcTable` values, so sharing the type avoids a near-duplicate enum.
    pub alignment: Option<Alignment>,
    /// The table's indentation from the leading margin, in twips (`w:tblPr/w:tblInd`,
    /// `CT_TblWidth`, always written with `w:type="dxa"`), or `None` to leave it unspecified (no
    /// extra indentation).
    pub indent_twips: Option<u32>,
    /// The id of a table-type named style to apply (`w:tblPr/w:tblStyle`), or `None`. Unlike
    /// `Paragraph.style_id`/`Run.style_id`, this crate does not model *declaring* a table style in
    /// `Document.styles` (`CT_Style`'s `table`-kind styles carry their own rich conditional
    /// formatting — `CT_TblStylePr` per table region: first row, banding, corner cells. — a large
    /// surface with no real need seen yet, matching the scope reduction already applied to
    /// `StyleKind`, which only models `paragraph`/`character`). Referencing one of Word's built-in
    /// table style ids (e.g. `"TableGrid"`, `"LightList-Accent1"`) still works perfectly well
    /// without a local declaration, the same way referencing a built-in paragraph style like
    /// `"Heading1"` does — Word resolves those from its own built-in style set when the document
    /// doesn't declare them itself.
    pub style_id: Option<String>,
}

/// A table row: a sequence of cells.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TableRow {
    /// The cells that make up this row, in order.
    pub cells: Vec<TableCell>,
    /// Whether this row repeats as a header row on every page the table spans
    /// (`w:trPr/w:tblHeader`, `CT_OnOff`) — only meaningful, per ECMA-376, when set on one or more
    /// of the table's topmost rows (Word stops honoring it on the first row where it isn't set);
    /// not validated here, same "caller's responsibility" convention as `Paragraph.numbering_id`
    /// referencing a declared list.
    pub repeat_as_header_row: bool,
    /// This row's height, in twips (`w:trPr/w:trHeight/@w:val`), or `None` to leave it unspecified
    /// (Word sizes the row to fit its content). Always written with `w:hRule="atLeast"`
    /// (`ST_HeightRule`'s other values, `exact` — which can clip content taller than the given
    /// height — and `auto` — equivalent to omitting the element entirely — aren't modeled), meaning
    /// this is a *minimum* height Word may still exceed for taller content, never a hard cap.
    pub height_twips: Option<u32>,
    /// Whether this row is prevented from splitting across a page break (`w:trPr/w:cantSplit`,
    /// `CT_OnOff`) — when `true`, Word moves the whole row to the next page rather than breaking it
    /// mid-row.
    pub cant_split: bool,
}

/// A table cell: a sequence of blocks (paragraphs, and optionally a nested table). `CT_Tc` reuses
/// the same block-level content model as the document body — `w:tbl` is a valid child of `w:tc` per
/// the schema — so a [`Block::Table`] here nests a table inside the cell, and a
/// [`Block::StructuredDocumentTag`] wraps more blocks the same way it does anywhere else a `Block`
/// is valid.
///
/// WordprocessingML requires every cell's content to actually END with a paragraph — not just
/// contain one somewhere (`CT_Tc`'s block-level content group has `minOccurs="1"`, but real Word
/// additionally expects the *last* child to be `w:p`, even after a nested table; violating this
/// causes Word's repair prompt on open, the same class of "schema-valid but not what Word actually
/// wants" bug this project has been bitten by before). The writer enforces this automatically —
/// appending an empty trailing paragraph whenever `blocks` is empty, or its last entry isn't
/// already a [`Block::Paragraph`] — so any [`TableCell`] is always valid to write regardless of
/// what the caller put in `blocks`.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct TableCell {
    /// The blocks that make up this cell's content, in order.
    pub blocks: Vec<Block>,
    /// How many grid columns this cell spans, for a horizontal merge (`w:gridSpan`,
    /// `CT_DecimalNumber`) — `None` (or `Some(1)`, treated identically) means an ordinary, unmerged
    /// cell occupying exactly one column; `Some(n)` with `n > 1` means this cell visually replaces
    /// `n` consecutive cells in the row, which must NOT also be present in `TableRow.cells` (this
    /// crate follows WordprocessingML's own model: a horizontally merged row simply has fewer
    /// `w:tc` elements than the table's column count, not extra "merged-away" cells to skip — this
    /// leaves column-counting entirely up to the caller).
    pub horizontal_span: Option<u32>,
    /// This cell's role in a vertical merge (`w:vMerge`, `CT_VMerge`), or `None` for a cell that
    /// isn't part of any vertical merge (and, per ECMA-376, closes any vertically merged group of
    /// *preceding* cells in the same column). See [`VerticalMerge`]'s doc comment for how a
    /// vertical merge spanning several rows is actually expressed: unlike a horizontal merge, EVERY
    /// row still needs one `TableCell` per column — there's no way to omit a cell vertically, only
    /// mark it as continuing the merge above it.
    pub vertical_merge: Option<VerticalMerge>,
    /// Whether this cell has a border around it (`w:tcPr/w:tcBorders`), mirroring
    /// `Paragraph.border`/`Run.text_border`'s fixed on/off appearance (`val="single" sz="4"
    /// space="0" color="auto"` on all four sides). `CT_TcBorders`'s `insideH`/`insideV` (only
    /// meaningful when a cell's borders are set individually across a merged region) and
    /// `tl2br`/`tr2bl` (diagonal lines) aren't modeled, same scope reduction as `Run.text_border`
    /// not exposing `CT_Border`'s full richness.
    pub border: bool,
    /// This cell's own background shading color (`w:tcPr/w:shd`), as a plain 6-digit RGB hex
    /// string, mirroring `Run.shading_color`/ `Paragraph.shading_color` — same fixed
    /// `val="clear"`/`color="auto"` pair, just written inside `w:tcPr` instead of `w:rPr`/`w:pPr`.
    /// `None` leaves the cell's background unset (inherits the table's/row's own shading, if any —
    /// not modeled at those levels here).
    pub shading_color: Option<String>,
    /// This cell's vertical alignment of its content within the cell's full height
    /// (`w:tcPr/w:vAlign`), or `None` to leave it unspecified (Word's default, effectively
    /// top-aligned). See [`CellVerticalAlign`]'s doc comment.
    pub vertical_alignment: Option<CellVerticalAlign>,
    /// This cell's top margin override, in twips (`w:tcPr/w:tcMar/w:top`, always written with
    /// `w:type="dxa"`), or `None` to use the table's own default cell margins (Word's built-in
    /// default, since this crate doesn't model table-wide `w:tblCellMar` either). See
    /// `margin_left_twips` for why these are four separate fields rather than one struct.
    pub margin_top_twips: Option<u32>,
    /// This cell's left margin override, in twips, mirroring `margin_top_twips`. Four separate
    /// `Option<u32>` fields (rather than a single small struct) match this crate's existing
    /// convention for `Paragraph.space_before`/`space_after` — plain, independently optional fields
    /// rather than introducing a new small aggregate type for four numbers.
    pub margin_left_twips: Option<u32>,
    /// This cell's bottom margin override, in twips, mirroring `margin_top_twips`.
    pub margin_bottom_twips: Option<u32>,
    /// This cell's right margin override, in twips, mirroring `margin_top_twips`.
    pub margin_right_twips: Option<u32>,
    /// This cell's text flow direction (`w:tcPr/w:textDirection`), or `None` for the normal,
    /// horizontal left-to-right flow (`ST_TextDirection`'s `lrTb`, Word's default when the element
    /// is omitted). See [`TextDirection`]'s doc comment for which rotated values are modeled.
    pub text_direction: Option<TextDirection>,
}

/// A table cell's role in a vertical merge (`w:vMerge`, `CT_VMerge`'s `val` attribute, `ST_Merge` —
/// exactly 2 values).
///
/// A vertical merge spanning several rows is expressed as ONE cell per row, all in the same column,
/// not a single cell with a "row span" count the way `horizontal_span` works for a horizontal merge
/// — WordprocessingML has no row-span concept at all, only this restart/continue chain: the topmost
/// cell of the merged group is [`VerticalMerge::Restart`], and every cell directly below it, for as
/// many rows as the merge covers, is [`VerticalMerge::Continue`]. Word derives the merge's actual
/// content from the `Restart` cell alone; a `Continue` cell's own paragraphs are conventionally
/// left empty (not enforced here) since they're never displayed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VerticalMerge {
    /// Starts a new vertically merged group of cells in this column.
    Restart,
    /// Continues the vertically merged group started by the nearest `Restart` cell above it in the
    /// same column.
    Continue,
}

impl VerticalMerge {
    /// This merge role's `w:val` attribute value (`ST_Merge`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            VerticalMerge::Restart => "restart",
            VerticalMerge::Continue => "continue",
        }
    }
}

/// A table cell's vertical alignment of its content (`w:tcPr/w:vAlign`, `CT_VerticalJc`,
/// `ST_VerticalJc`) — where the cell's paragraphs sit within the cell's full height, when that
/// height exceeds the content's natural height (e.g. because a neighboring cell in the same row is
/// taller, or `TableRow.height_twips` forces extra height). Distinct from
/// `Paragraph.alignment`/`Table.alignment` (both horizontal).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CellVerticalAlign {
    Top,
    Center,
    Bottom,
}

impl CellVerticalAlign {
    /// This vertical alignment's `w:vAlign`/`val` value (`ST_VerticalJc`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            CellVerticalAlign::Top => "top",
            CellVerticalAlign::Center => "center",
            CellVerticalAlign::Bottom => "bottom",
        }
    }

    /// Parses a `w:vAlign`/`val` value (`ST_VerticalJc`) back into a [`CellVerticalAlign`], or
    /// `None` for an unrecognized value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "top" => Some(CellVerticalAlign::Top),
            "center" => Some(CellVerticalAlign::Center),
            "bottom" => Some(CellVerticalAlign::Bottom),
            _ => None,
        }
    }
}

/// A table cell's text flow direction (`w:tcPr/w:textDirection`, `CT_TextDirection`,
/// `ST_TextDirection`) — used to rotate a cell's text 90 degrees, a common way to fit a narrow
/// column header (e.g. a label running down a data table's leftmost column).
///
/// `ST_TextDirection` actually defines many more values than these two (`lr`, `tb`, `lrV`, `tbV`,
/// `lrTb`, `tbRl`, `btLr`, `lrTbV`, `tbLrV`, `tbRlV` — a mix of modern WordprocessingML values and
/// legacy WordPerfect-compatibility ones); only the two rotated options exposed by Word's own
/// Table Properties dialog (under Text Direction) are modeled. The normal, non-rotated flow
/// (`lrTb`) isn't modeled as its own variant, since `TableCell.text_direction:
/// Option<TextDirection>` already expresses it via `None` (omitting `w:textDirection` entirely
/// achieves the same visual result), same convention as [`VerticalAlign`]'s
/// `"baseline"`/[`Highlight`]'s `"none"`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextDirection {
    /// Text reads top-to-bottom, columns flowing right-to-left — Word's "Rotate all text 90°"
    /// (`ST_TextDirection`'s `tbRl`).
    TopToBottom,
    /// Text reads bottom-to-top, columns flowing left-to-right — Word's "Rotate all text 270°"
    /// (`ST_TextDirection`'s `btLr`).
    BottomToTop,
}

impl TextDirection {
    /// This text direction's `w:textDirection`/`val` value (`ST_TextDirection`).
    pub fn attribute_value(self) -> &'static str {
        match self {
            TextDirection::TopToBottom => "tbRl",
            TextDirection::BottomToTop => "btLr",
        }
    }

    /// Parses a `w:textDirection`/`val` value (`ST_TextDirection`) back into a [`TextDirection`],
    /// or `None` for `"lrTb"` or any other unmodeled value.
    pub fn from_attribute_value(value: &str) -> Option<Self> {
        match value {
            "tbRl" => Some(TextDirection::TopToBottom),
            "btLr" => Some(TextDirection::BottomToTop),
            _ => None,
        }
    }
}

/// A paragraph's horizontal alignment (WordprocessingML `CT_Jc`/`ST_Jc`).
///
/// Only the four values Word's UI exposes directly are modeled; `ST_Jc` defines several more
/// (`distribute`, `thaiDistribute`, `mediumKashida`, `highKashida`, `lowKashida`, `numTab`), all
/// specialized enough to add later if/when a real need for them comes up.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alignment {
    Left,
    Center,
    Right,
    /// "Justify" in Word's UI; `w:val="both"` in the markup.
    Justify,
}

impl Document {
    /// Creates an empty document.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a paragraph block and returns the document for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a table block and returns the document for chaining.
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Appends a paragraph with the given text and returns a mutable reference to it, for further
    /// in-place styling (e.g. `document.add_paragraph("..").with_alignment(..)` isn't possible
    /// since `with_*` consumes `self` — reach for `paragraph.alignment =..` or
    /// `paragraph.runs.push(..)` on the returned reference instead). A `&mut self` counterpart to
    /// [`Self::with_paragraph`], for the common case of building a document by appending to it in a
    /// loop, where the consuming builder would otherwise force a `document =
    /// document.with_paragraph(..)` reassignment on every iteration.
    pub fn add_paragraph(&mut self, text: impl Into<String>) -> &mut Paragraph {
        self.blocks
            .push(Block::Paragraph(Paragraph::with_text(text)));
        let Some(Block::Paragraph(paragraph)) = self.blocks.last_mut() else {
            unreachable!("the block just pushed is always a Block::Paragraph")
        };
        paragraph
    }

    /// Iterates over the document's paragraphs only, skipping tables. A convenience for the common
    /// case of not caring about tables; use `blocks` directly to see paragraphs and tables in their
    /// actual reading order.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over the document's tables only, skipping paragraphs.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Sets the document's default header and returns it for chaining.
    pub fn with_header(mut self, header: HeaderFooter) -> Self {
        self.header = Some(header);
        self
    }

    /// Sets the document's default footer and returns it for chaining.
    pub fn with_footer(mut self, footer: HeaderFooter) -> Self {
        self.footer = Some(footer);
        self
    }

    /// Sets the document's first-page header and returns it for chaining. See `header_first`'s doc
    /// comment.
    pub fn with_header_first(mut self, header: HeaderFooter) -> Self {
        self.header_first = Some(header);
        self
    }

    /// Sets the document's first-page footer and returns it for chaining.
    pub fn with_footer_first(mut self, footer: HeaderFooter) -> Self {
        self.footer_first = Some(footer);
        self
    }

    /// Sets the document's even-page header and returns it for chaining. See `header_even`'s doc
    /// comment.
    pub fn with_header_even(mut self, header: HeaderFooter) -> Self {
        self.header_even = Some(header);
        self
    }

    /// Sets the document's even-page footer and returns it for chaining.
    pub fn with_footer_even(mut self, footer: HeaderFooter) -> Self {
        self.footer_even = Some(footer);
        self
    }

    /// Sets the document's page setup and returns it for chaining.
    pub fn with_page_setup(mut self, page_setup: PageSetup) -> Self {
        self.page_setup = page_setup;
        self
    }

    /// Appends a named style declaration and returns the document for chaining.
    pub fn with_style(mut self, style: Style) -> Self {
        self.styles.push(style);
        self
    }

    /// Appends a numbering (list) definition and returns the document for chaining.
    pub fn with_numbering_definition(mut self, definition: NumberingDefinition) -> Self {
        self.numbering_definitions.push(definition);
        self
    }

    /// Appends a footnote declaration and returns the document for chaining.
    pub fn with_footnote(mut self, note: Note) -> Self {
        self.footnotes.push(note);
        self
    }

    /// Appends an endnote declaration and returns the document for chaining.
    pub fn with_endnote(mut self, note: Note) -> Self {
        self.endnotes.push(note);
        self
    }

    /// Appends a comment declaration and returns the document for chaining.
    pub fn with_comment(mut self, comment: Comment) -> Self {
        self.comments.push(comment);
        self
    }

    /// Appends a structured document tag block and returns the document for chaining.
    pub fn with_structured_document_tag(mut self, sdt: StructuredDocumentTag) -> Self {
        self.blocks.push(Block::StructuredDocumentTag(sdt));
        self
    }

    /// Sets the document's theme and returns it for chaining.
    pub fn with_theme(mut self, theme: Theme) -> Self {
        self.theme = Some(theme);
        self
    }

    /// Sets whether Word should track changes made to this document from now on and returns it for
    /// chaining. See `track_changes`'s doc comment.
    pub fn with_track_changes(mut self, track_changes: bool) -> Self {
        self.track_changes = track_changes;
        self
    }

    /// Sets the document's core properties (title, author, etc.) and returns it for chaining. See
    /// [`DocumentProperties`]'s doc comment.
    pub fn with_properties(mut self, properties: DocumentProperties) -> Self {
        self.properties = properties;
        self
    }

    /// Sets which editing restrictions are enforced on the document and returns it for chaining.
    /// See [`ProtectionKind`]'s doc comment.
    pub fn with_protection(mut self, protection: ProtectionKind) -> Self {
        self.protection = Some(protection);
        self
    }

    /// Sets the document's extended properties (company/manager) and returns it for chaining. See
    /// [`ExtendedProperties`]'s doc comment.
    pub fn with_extended_properties(mut self, extended_properties: ExtendedProperties) -> Self {
        self.extended_properties = extended_properties;
        self
    }

    /// Appends a custom property (name/value pair) and returns the document for chaining. See
    /// `custom_properties`'s doc comment for why order matters here.
    pub fn with_custom_property(
        mut self,
        name: impl Into<String>,
        value: CustomPropertyValue,
    ) -> Self {
        self.custom_properties.push((name.into(), value));
        self
    }
}

impl DocumentProperties {
    /// Creates an empty set of document properties (every field `None`).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the document's title and returns it for chaining.
    pub fn with_title(mut self, title: impl Into<String>) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Sets the document's subject and returns it for chaining.
    pub fn with_subject(mut self, subject: impl Into<String>) -> Self {
        self.subject = Some(subject.into());
        self
    }

    /// Sets the document's author and returns it for chaining.
    pub fn with_creator(mut self, creator: impl Into<String>) -> Self {
        self.creator = Some(creator.into());
        self
    }

    /// Sets the document's search keywords and returns it for chaining.
    pub fn with_keywords(mut self, keywords: impl Into<String>) -> Self {
        self.keywords = Some(keywords.into());
        self
    }

    /// Sets the document's description and returns it for chaining. Shown as "Comments" in Word's
    /// own File > Info panel — see this field's doc comment.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = Some(description.into());
        self
    }

    /// Sets who last modified the document and returns it for chaining.
    pub fn with_last_modified_by(mut self, last_modified_by: impl Into<String>) -> Self {
        self.last_modified_by = Some(last_modified_by.into());
        self
    }

    /// Sets the document's revision number (as a string) and returns it for chaining.
    pub fn with_revision(mut self, revision: impl Into<String>) -> Self {
        self.revision = Some(revision.into());
        self
    }

    /// Sets when the document was created (a W3CDTF string, e.g. `"2026-07-17T10:00:00Z"`) and
    /// returns it for chaining. Not validated — see this struct's doc comment.
    pub fn with_created(mut self, created: impl Into<String>) -> Self {
        self.created = Some(created.into());
        self
    }

    /// Sets when the document was last modified (a W3CDTF string), mirroring `with_created`, and
    /// returns it for chaining.
    pub fn with_modified(mut self, modified: impl Into<String>) -> Self {
        self.modified = Some(modified.into());
        self
    }

    /// Sets the document's category and returns it for chaining.
    pub fn with_category(mut self, category: impl Into<String>) -> Self {
        self.category = Some(category.into());
        self
    }

    /// Sets the document's content status (e.g. `"Draft"`, `"Final"`) and returns it for chaining.
    pub fn with_content_status(mut self, content_status: impl Into<String>) -> Self {
        self.content_status = Some(content_status.into());
        self
    }
}

impl HeaderFooter {
    /// Creates an empty header/footer.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a paragraph block and returns it for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a table block and returns it for chaining.
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Appends a structured document tag block and returns it for chaining.
    pub fn with_structured_document_tag(mut self, sdt: StructuredDocumentTag) -> Self {
        self.blocks.push(Block::StructuredDocumentTag(sdt));
        self
    }

    /// Iterates over this header/footer's paragraphs only, skipping tables.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over this header/footer's tables only, skipping paragraphs.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }
}

impl Note {
    /// Creates an empty note with the given id.
    pub fn new(id: u32) -> Self {
        Self {
            id,
            blocks: Vec::new(),
        }
    }

    /// A ready-made footnote: a single paragraph starting with the footnote's own number marker, a
    /// space, then the given text — the same shape a real Word-authored footnote uses (see
    /// [`Note`]'s doc comment). Use [`Note::new`] plus `with_paragraph`/`with_table` instead for
    /// full control (e.g. a note spanning several paragraphs).
    pub fn footnote_with_text(id: u32, text: impl Into<String>) -> Self {
        Self::with_marker_and_text(id, NoteKind::Footnote, text)
    }

    /// A ready-made endnote, mirroring [`Note::footnote_with_text`].
    pub fn endnote_with_text(id: u32, text: impl Into<String>) -> Self {
        Self::with_marker_and_text(id, NoteKind::Endnote, text)
    }

    fn with_marker_and_text(id: u32, kind: NoteKind, text: impl Into<String>) -> Self {
        Self {
            id,
            blocks: vec![Block::Paragraph(
                Paragraph::new()
                    .with_run(Run::with_note_marker(kind))
                    .with_run(Run::new(" "))
                    .with_run(Run::new(text)),
            )],
        }
    }

    /// Appends a paragraph block and returns the note for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a table block and returns the note for chaining.
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Iterates over this note's paragraphs only, skipping tables.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over this note's tables only, skipping paragraphs.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }
}

impl Comment {
    /// Creates an empty comment with the given id and no author/initials/ date set.
    pub fn new(id: u32) -> Self {
        Self {
            id,
            ..Self::default()
        }
    }

    /// A ready-made comment: a single paragraph with the given text. Use [`Comment::new`] plus
    /// `with_paragraph`/`with_table` instead for full control (e.g. a comment spanning several
    /// paragraphs). Unlike [`Note::footnote_with_text`], no marker run is needed at the start — see
    /// [`Comment`]'s doc comment for why `annotationRef` isn't modeled.
    pub fn with_text(id: u32, text: impl Into<String>) -> Self {
        Self {
            id,
            blocks: vec![Block::Paragraph(Paragraph::with_text(text))],
            ..Self::default()
        }
    }

    /// Sets the comment's author and returns it for chaining.
    pub fn with_author(mut self, author: impl Into<String>) -> Self {
        self.author = Some(author.into());
        self
    }

    /// Sets the author's initials and returns it for chaining.
    pub fn with_initials(mut self, initials: impl Into<String>) -> Self {
        self.initials = Some(initials.into());
        self
    }

    /// Sets the comment's date (a plain `xs:dateTime` string, e.g. `"2024-01-01T12:00:00Z"` — see
    /// the field's doc comment) and returns it for chaining.
    pub fn with_date(mut self, date: impl Into<String>) -> Self {
        self.date = Some(date.into());
        self
    }

    /// Appends a paragraph block and returns the comment for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a table block and returns the comment for chaining.
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Iterates over this comment's paragraphs only, skipping tables.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over this comment's tables only, skipping paragraphs.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }
}

impl StructuredDocumentTag {
    /// Creates an empty structured document tag with no id/tag/alias set.
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the control's id and returns it for chaining.
    pub fn with_id(mut self, id: i32) -> Self {
        self.id = Some(id);
        self
    }

    /// Sets the control's programmatic tag and returns it for chaining.
    pub fn with_tag(mut self, tag: impl Into<String>) -> Self {
        self.tag = Some(tag.into());
        self
    }

    /// Sets the control's friendly/display name and returns it for chaining.
    pub fn with_alias(mut self, alias: impl Into<String>) -> Self {
        self.alias = Some(alias.into());
        self
    }

    /// Appends a paragraph block and returns the control for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a table block and returns the control for chaining.
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Iterates over this control's paragraphs only, skipping tables and nested structured document
    /// tags.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over this control's tables only, skipping paragraphs and nested structured document
    /// tags.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }
}

impl Theme {
    /// Creates a theme with the given name, colors and fonts.
    pub fn new(name: impl Into<String>, colors: ColorScheme, fonts: FontScheme) -> Self {
        Self {
            name: name.into(),
            colors,
            fonts,
        }
    }

    /// Office's own built-in default theme: its classic "Office" color palette and Cambria/Calibri
    /// heading/body fonts — the same theme a brand-new blank document uses.
    pub fn office_default() -> Self {
        Self::new(
            "Office",
            ColorScheme::office_default(),
            FontScheme::office_default(),
        )
    }
}

impl ColorScheme {
    /// Creates a color scheme from its 12 slots, each a 6-digit RGB hex string (no leading `#`).
    #[allow(clippy::too_many_arguments)]
    pub fn new(
        dark1: impl Into<String>,
        light1: impl Into<String>,
        dark2: impl Into<String>,
        light2: impl Into<String>,
        accent1: impl Into<String>,
        accent2: impl Into<String>,
        accent3: impl Into<String>,
        accent4: impl Into<String>,
        accent5: impl Into<String>,
        accent6: impl Into<String>,
        hyperlink: impl Into<String>,
        followed_hyperlink: impl Into<String>,
    ) -> Self {
        Self {
            dark1: dark1.into(),
            light1: light1.into(),
            dark2: dark2.into(),
            light2: light2.into(),
            accent1: accent1.into(),
            accent2: accent2.into(),
            accent3: accent3.into(),
            accent4: accent4.into(),
            accent5: accent5.into(),
            accent6: accent6.into(),
            hyperlink: hyperlink.into(),
            followed_hyperlink: followed_hyperlink.into(),
        }
    }

    /// Office's own built-in default 12-color palette (the classic "Office" theme colors:
    /// `dk1`/`lt1` as plain black/white rather than Word's own live `sysClr` binding — see
    /// [`ColorScheme`]'s doc comment).
    pub fn office_default() -> Self {
        Self::new(
            "000000", "FFFFFF", "1F497D", "EEECE1", "4F81BD", "C0504D", "9BBB59", "8064A2",
            "4BACC6", "F79646", "0000FF", "800080",
        )
    }
}

impl FontScheme {
    /// Creates a font scheme with the given heading ("major") and body ("minor") Latin typefaces.
    pub fn new(major_latin: impl Into<String>, minor_latin: impl Into<String>) -> Self {
        Self {
            major_latin: major_latin.into(),
            minor_latin: minor_latin.into(),
        }
    }

    /// Office's own built-in default fonts: Cambria for headings, Calibri for body text.
    pub fn office_default() -> Self {
        Self::new("Cambria", "Calibri")
    }
}

impl Paragraph {
    /// Creates an empty paragraph.
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a paragraph containing a single run with the given text.
    pub fn with_text(text: impl Into<String>) -> Self {
        Self {
            runs: vec![Run::new(text)],
            ..Self::default()
        }
    }

    /// Appends a run and returns the paragraph for chaining.
    pub fn with_run(mut self, run: Run) -> Self {
        self.runs.push(run);
        self
    }

    /// Sets the paragraph's alignment and returns it for chaining.
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = Some(alignment);
        self
    }

    /// Sets the paragraph style to apply (by id) and returns it for chaining.
    pub fn with_style_id(mut self, style_id: impl Into<String>) -> Self {
        self.style_id = Some(style_id.into());
        self
    }

    /// Makes this paragraph an item of `numbering_id`'s list, at the given indent level
    /// (0-indexed), and returns it for chaining.
    pub fn with_numbering(mut self, numbering_id: u32, level: u8) -> Self {
        self.numbering_id = Some(numbering_id);
        self.numbering_level = level;
        self
    }

    /// Sets the paragraph's line spacing (in `w:spacing`'s "auto" units — `240` is single, `360` is
    /// 1.5 lines, `480` is double) and returns it for chaining.
    pub fn with_line_spacing(mut self, line_spacing: u32) -> Self {
        self.line_spacing = Some(line_spacing);
        self
    }

    /// Sets extra space before this paragraph, in twips, and returns it for chaining.
    pub fn with_space_before(mut self, space_before: u32) -> Self {
        self.space_before = Some(space_before);
        self
    }

    /// Sets extra space after this paragraph, in twips, and returns it for chaining.
    pub fn with_space_after(mut self, space_after: u32) -> Self {
        self.space_after = Some(space_after);
        self
    }

    /// Sets the paragraph's background shading color and returns it for chaining.
    pub fn with_shading_color(mut self, shading_color: impl Into<String>) -> Self {
        self.shading_color = Some(shading_color.into());
        self
    }

    /// Sets whether this paragraph has a border around it and returns it for chaining.
    pub fn with_border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    /// Sets whether this paragraph stays on the same page as the one following it and returns it
    /// for chaining. See `keep_with_next`'s doc comment.
    pub fn with_keep_with_next(mut self, keep_with_next: bool) -> Self {
        self.keep_with_next = keep_with_next;
        self
    }

    /// Sets whether every line of this paragraph must stay together on the same page and returns it
    /// for chaining. See `keep_lines_together`'s doc comment.
    pub fn with_keep_lines_together(mut self, keep_lines_together: bool) -> Self {
        self.keep_lines_together = keep_lines_together;
        self
    }

    /// Sets whether this paragraph always starts on a new page and returns it for chaining. See
    /// `page_break_before`'s doc comment.
    pub fn with_page_break_before(mut self, page_break_before: bool) -> Self {
        self.page_break_before = page_break_before;
        self
    }

    /// Appends a custom tab stop and returns the paragraph for chaining.
    pub fn with_tab(mut self, tab: TabStop) -> Self {
        self.tabs.push(tab);
        self
    }

    /// Sets whether to ignore spacing above/below this paragraph when adjacent to a paragraph of
    /// the same style, and returns it for chaining. See `contextual_spacing`'s doc comment.
    pub fn with_contextual_spacing(mut self, contextual_spacing: bool) -> Self {
        self.contextual_spacing = contextual_spacing;
        self
    }

    /// The paragraph's text: the concatenation of its text runs' text. Image and field runs
    /// contribute nothing (not even a placeholder character).
    pub fn text(&self) -> String {
        self.runs.iter().filter_map(Run::text).collect()
    }
}

impl Run {
    /// Creates a text run with the given text and no formatting.
    pub fn new(text: impl Into<String>) -> Self {
        Self {
            content: RunContent::Text(text.into()),
            ..Self::default()
        }
    }

    /// Creates a run containing a single inline image.
    pub fn with_image(image: Image) -> Self {
        Self {
            content: RunContent::Image(Box::new(image)),
            ..Self::default()
        }
    }

    /// Creates a run containing a single embedded chart.
    pub fn with_chart(chart: EmbeddedChart) -> Self {
        Self {
            content: RunContent::Chart(Box::new(chart)),
            ..Self::default()
        }
    }

    /// Creates a run containing a single field (e.g. a page number).
    pub fn with_field(field: Field) -> Self {
        Self {
            content: RunContent::Field(field),
            ..Self::default()
        }
    }

    /// Creates a run whose content is a single explicit break (`w:br`, page/column/line). See
    /// [`BreakKind`]'s doc comment.
    pub fn with_break(kind: BreakKind) -> Self {
        Self {
            content: RunContent::Break(kind),
            ..Self::default()
        }
    }

    /// Creates a run whose content is a single carriage return (`w:cr`). See
    /// `RunContent::CarriageReturn`'s doc comment for how this differs from
    /// `with_break(BreakKind::TextWrapping)`.
    pub fn with_carriage_return() -> Self {
        Self {
            content: RunContent::CarriageReturn,
            ..Self::default()
        }
    }

    /// This run's text, or `None` if it is an image, chart, field, note, break or carriage return
    /// run.
    pub fn text(&self) -> Option<&str> {
        match &self.content {
            RunContent::Text(text) => Some(text.as_str()),
            RunContent::Image(_)
            | RunContent::Chart(_)
            | RunContent::Field(_)
            | RunContent::NoteReference(_)
            | RunContent::NoteMarker(_)
            | RunContent::Break(_)
            | RunContent::CarriageReturn => None,
        }
    }

    /// This run's image, or `None` if it isn't an image run.
    pub fn image(&self) -> Option<&Image> {
        match &self.content {
            RunContent::Image(image) => Some(image.as_ref()),
            RunContent::Text(_)
            | RunContent::Chart(_)
            | RunContent::Field(_)
            | RunContent::NoteReference(_)
            | RunContent::NoteMarker(_)
            | RunContent::Break(_)
            | RunContent::CarriageReturn => None,
        }
    }

    /// This run's chart, or `None` if it isn't a chart run.
    pub fn chart(&self) -> Option<&EmbeddedChart> {
        match &self.content {
            RunContent::Chart(chart) => Some(chart.as_ref()),
            RunContent::Text(_)
            | RunContent::Image(_)
            | RunContent::Field(_)
            | RunContent::NoteReference(_)
            | RunContent::NoteMarker(_)
            | RunContent::Break(_)
            | RunContent::CarriageReturn => None,
        }
    }

    /// This run's field, or `None` if it isn't a field run.
    pub fn field(&self) -> Option<Field> {
        match &self.content {
            RunContent::Field(field) => Some(*field),
            RunContent::Text(_)
            | RunContent::Image(_)
            | RunContent::Chart(_)
            | RunContent::NoteReference(_)
            | RunContent::NoteMarker(_)
            | RunContent::Break(_)
            | RunContent::CarriageReturn => None,
        }
    }

    /// Sets whether the run is bold and returns it for chaining.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    /// Sets whether the run is italic and returns it for chaining.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Sets the run's underline style and returns it for chaining.
    pub fn with_underline(mut self, underline: UnderlineStyle) -> Self {
        self.underline = Some(underline);
        self
    }

    /// Sets the color of the run's underline (a 6-digit RGB hex string, no leading `#`) and returns
    /// it for chaining. Only meaningful once `with_underline` has also been called.
    pub fn with_underline_color(mut self, underline_color: impl Into<String>) -> Self {
        self.underline_color = Some(underline_color.into());
        self
    }

    /// Sets the run's text color (a 6-digit RGB hex string, no leading `#`) and returns it for
    /// chaining.
    pub fn with_color(mut self, color: impl Into<String>) -> Self {
        self.color = Some(color.into());
        self
    }

    /// Sets the run's font size in whole points and returns it for chaining.
    pub fn with_font_size(mut self, font_size: u16) -> Self {
        self.font_size = Some(font_size);
        self
    }

    /// Sets the run's font family/typeface and returns it for chaining.
    pub fn with_font_family(mut self, font_family: impl Into<String>) -> Self {
        self.font_family = Some(font_family.into());
        self
    }

    /// Sets the run's highlight color and returns it for chaining.
    pub fn with_highlight(mut self, highlight: Highlight) -> Self {
        self.highlight = Some(highlight);
        self
    }

    /// Sets whether the run is struck through and returns it for chaining.
    pub fn with_strike(mut self, strike: bool) -> Self {
        self.strike = strike;
        self
    }

    /// Sets the run's vertical alignment (superscript/subscript) and returns it for chaining.
    pub fn with_vertical_align(mut self, vertical_align: VerticalAlign) -> Self {
        self.vertical_align = Some(vertical_align);
        self
    }

    /// Sets whether the run is displayed as small caps and returns it for chaining.
    pub fn with_small_caps(mut self, small_caps: bool) -> Self {
        self.small_caps = small_caps;
        self
    }

    /// Sets whether the run is displayed as all caps and returns it for chaining.
    pub fn with_all_caps(mut self, all_caps: bool) -> Self {
        self.all_caps = all_caps;
        self
    }

    /// Sets the run's background shading color (a 6-digit RGB hex string, no leading `#`) and
    /// returns it for chaining.
    pub fn with_shading_color(mut self, shading_color: impl Into<String>) -> Self {
        self.shading_color = Some(shading_color.into());
        self
    }

    /// Sets whether the run has a border around its text and returns it for chaining.
    pub fn with_text_border(mut self, text_border: bool) -> Self {
        self.text_border = text_border;
        self
    }

    /// Sets the run's character spacing adjustment, in twips, and returns it for chaining.
    pub fn with_character_spacing(mut self, character_spacing: i16) -> Self {
        self.character_spacing = Some(character_spacing);
        self
    }

    /// Sets the run's vertical position, raised or lowered from the baseline, in half-points, and
    /// returns it for chaining.
    pub fn with_vertical_position(mut self, vertical_position: i16) -> Self {
        self.vertical_position = Some(vertical_position);
        self
    }

    /// Sets whether the run's text is hidden and returns it for chaining.
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets the character style to apply (by id) and returns it for chaining.
    pub fn with_style_id(mut self, style_id: impl Into<String>) -> Self {
        self.style_id = Some(style_id.into());
        self
    }

    /// Sets the hyperlink to apply to this run and returns it for chaining.
    pub fn with_hyperlink(mut self, hyperlink: Hyperlink) -> Self {
        self.hyperlink = Some(hyperlink);
        self
    }

    /// Marks this run as falling inside the given [`Comment`]'s range (see `comment_ids`'s doc
    /// comment) and returns it for chaining. Call repeatedly to place a run inside several
    /// overlapping comments' ranges at once.
    pub fn with_comment(mut self, comment_id: u32) -> Self {
        self.comment_ids.push(comment_id);
        self
    }

    /// Marks this run as falling inside the given [`Bookmark`]'s range (see `bookmarks`'s doc
    /// comment) and returns it for chaining. Call repeatedly to place a run inside several
    /// overlapping bookmarks' ranges at once, or on consecutive runs to span a bookmark across more
    /// than one run — repeat the exact same `Bookmark` (same id, same name) on every run the
    /// bookmark should cover.
    pub fn with_bookmark(mut self, bookmark: Bookmark) -> Self {
        self.bookmarks.push(bookmark);
        self
    }

    /// Creates a run referencing a footnote/endnote (`<w:footnoteReference>`/
    /// `<w:endnoteReference>`), to be placed in the document body.
    ///
    /// Word always renders this reference in the "FootnoteReference"/ "EndnoteReference" built-in
    /// character style (a superscript number) — real Word documents rely on Word's own built-in
    /// latent style definitions for these well-known style ids, with no need to declare a matching
    /// [`Style`] in `Document.styles`, so this constructor sets `style_id` accordingly. Override it
    /// afterwards (`with_style_id`) if a different style is genuinely needed.
    pub fn with_note_reference(reference: NoteReference) -> Self {
        let style_id = match reference {
            NoteReference::Footnote(_) => "FootnoteReference",
            NoteReference::Endnote(_) => "EndnoteReference",
        };
        Self {
            content: RunContent::NoteReference(reference),
            style_id: Some(style_id.to_string()),
            ..Self::default()
        }
    }

    /// Creates a run rendering a footnote/endnote's own number marker
    /// (`<w:footnoteRef/>`/`<w:endnoteRef/>`) — meant to be the first run of the note's own first
    /// paragraph (see [`Note::footnote_with_text`]/ [`Note::endnote_with_text`] for a convenience
    /// that builds this automatically). Sets `style_id` the same way [`Run::with_note_reference`]
    /// does, for the same reason.
    pub fn with_note_marker(kind: NoteKind) -> Self {
        let style_id = match kind {
            NoteKind::Footnote => "FootnoteReference",
            NoteKind::Endnote => "EndnoteReference",
        };
        Self {
            content: RunContent::NoteMarker(kind),
            style_id: Some(style_id.to_string()),
            ..Self::default()
        }
    }
}

impl Image {
    /// Creates an image with an explicit display size in EMUs.
    pub fn new(
        data: impl Into<Vec<u8>>,
        format: ImageFormat,
        width_emu: i64,
        height_emu: i64,
    ) -> Self {
        Self {
            data: data.into(),
            format,
            width_emu,
            height_emu,
            description: String::new(),
            shape_properties: None,
        }
    }

    /// Creates an image with its display size given in pixels, converted to EMUs assuming 96 DPI (a
    /// common screen resolution default, and Word's own default when it can't otherwise determine
    /// an image's intended size).
    pub fn from_pixels(
        data: impl Into<Vec<u8>>,
        format: ImageFormat,
        width_px: u32,
        height_px: u32,
    ) -> Self {
        const DEFAULT_DPI: i64 = 96;
        Self::new(
            data,
            format,
            (i64::from(width_px) * EMU_PER_INCH) / DEFAULT_DPI,
            (i64::from(height_px) * EMU_PER_INCH) / DEFAULT_DPI,
        )
    }

    /// Sets the image's alt text / description and returns it for chaining.
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Sets additional shape formatting (fill/line/rotation) for this picture's own `pic:spPr` and
    /// returns it for chaining. See [`Image::shape_properties`]'s doc comment.
    pub fn with_shape_properties(mut self, shape_properties: drawing::ShapeProperties) -> Self {
        self.shape_properties = Some(shape_properties);
        self
    }
}

impl ImageFormat {
    /// The file extension used for this format's media part (e.g. `word/media/image1.png`), without
    /// the leading dot.
    pub fn extension(self) -> &'static str {
        match self {
            ImageFormat::Png => "png",
            ImageFormat::Jpeg => "jpg",
            ImageFormat::Gif => "gif",
            ImageFormat::Bmp => "bmp",
        }
    }

    /// The media part's content type (`[Content_Types].xml` `Override` value).
    pub fn content_type(self) -> &'static str {
        match self {
            ImageFormat::Png => "image/png",
            ImageFormat::Jpeg => "image/jpeg",
            ImageFormat::Gif => "image/gif",
            ImageFormat::Bmp => "image/bmp",
        }
    }

    /// Guesses the format from a part name's or file name's extension (case-insensitive), or `None`
    /// if it isn't one of the formats we support.
    pub fn from_extension(name: &str) -> Option<Self> {
        match name.rsplit('.').next()?.to_lowercase().as_str() {
            "png" => Some(ImageFormat::Png),
            "jpg" | "jpeg" => Some(ImageFormat::Jpeg),
            "gif" => Some(ImageFormat::Gif),
            "bmp" => Some(ImageFormat::Bmp),
            _ => None,
        }
    }
}

// ============================================================================,: an embedded chart,
// inline in a run. ============================================================================

/// An inline chart (`<w:drawing><wp:inline>..`), embedded in a run — [`RunContent::Chart`]'s
/// payload. Structurally the same `wp:inline` skeleton as [`Image`] (`wp:extent`/`wp:docPr`,
/// wrapping an `a:graphic`/`a:graphicData`), but the `a:graphicData` wraps a `<c:chart r:id="..">`
/// graphic frame instead of a `pic:pic` (see `writer.rs::write_embedded_chart`) — its own
/// graphic-frame wiring rather than a picture's, even though both live under `wp:inline` on the
/// Word side.
///
/// A deliberate scope decision, since chart-in-document support is still an evolving corner of the
/// format: **cached values only**, no embedded `.xlsx` workbook as a data source. This crate's
/// `chart::ChartSpace` already carries every series' cached values directly
/// (`chart::NumericDataSource`/`StringDataSource`), so a Word chart embedded this way renders
/// correctly in Word without any companion workbook part — it just can't be "edited" via Word's
/// "Edit Data in Excel" feature the way a real Word-native chart (created through Word's own UI)
/// can.
#[derive(Debug, Clone, PartialEq)]
pub struct EmbeddedChart {
    pub chart_space: chart::ChartSpace,
    /// The width the chart is displayed at, in EMUs (`wp:extent`'s `cx`).
    pub width_emu: i64,
    /// The height the chart is displayed at, in EMUs (`cy`).
    pub height_emu: i64,
    /// Alt text / description (`wp:docPr`'s `descr`/`name` attributes). May be empty.
    pub name: String,
}

impl EmbeddedChart {
    /// Creates an embedded chart with an explicit display size in EMUs.
    pub fn new(chart_space: chart::ChartSpace, width_emu: i64, height_emu: i64) -> Self {
        Self {
            chart_space,
            width_emu,
            height_emu,
            name: String::new(),
        }
    }

    /// Sets the chart's alt text / name and returns it for chaining.
    pub fn with_name(mut self, name: impl Into<String>) -> Self {
        self.name = name.into();
        self
    }
}

impl Table {
    /// Creates an empty table.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a row and returns the table for chaining.
    pub fn with_row(mut self, row: TableRow) -> Self {
        self.rows.push(row);
        self
    }

    /// Sets this table's per-column preferred widths (in twips, one entry per grid column) and
    /// returns it for chaining. See `column_widths`'s doc comment for how this also switches the
    /// table to a fixed (rather than autofit) layout.
    pub fn with_column_widths(mut self, column_widths: Vec<u32>) -> Self {
        self.column_widths = column_widths;
        self
    }

    /// Sets this table's border color and returns it for chaining. See `border_color`'s doc
    /// comment.
    pub fn with_border_color(mut self, border_color: impl Into<String>) -> Self {
        self.border_color = Some(border_color.into());
        self
    }

    /// Sets this table's own horizontal alignment/positioning and returns it for chaining. See
    /// `alignment`'s doc comment.
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = Some(alignment);
        self
    }

    /// Sets this table's indentation, in twips, and returns it for chaining. See `indent_twips`'s
    /// doc comment.
    pub fn with_indent_twips(mut self, indent_twips: u32) -> Self {
        self.indent_twips = Some(indent_twips);
        self
    }

    /// Sets the id of a named table style to apply and returns it for chaining. See `style_id`'s
    /// doc comment.
    pub fn with_style_id(mut self, style_id: impl Into<String>) -> Self {
        self.style_id = Some(style_id.into());
        self
    }
}

impl TableRow {
    /// Creates an empty row.
    pub fn new() -> Self {
        Self::default()
    }

    /// Appends a cell and returns the row for chaining.
    pub fn with_cell(mut self, cell: TableCell) -> Self {
        self.cells.push(cell);
        self
    }

    /// Marks this row as repeating as a header row on every page and returns it for chaining. See
    /// `repeat_as_header_row`'s doc comment.
    pub fn with_repeat_as_header_row(mut self, repeat_as_header_row: bool) -> Self {
        self.repeat_as_header_row = repeat_as_header_row;
        self
    }

    /// Sets this row's height, in twips, and returns it for chaining. See `height_twips`'s doc
    /// comment.
    pub fn with_height_twips(mut self, height_twips: u32) -> Self {
        self.height_twips = Some(height_twips);
        self
    }

    /// Marks this row as unable to split across a page break and returns it for chaining. See
    /// `cant_split`'s doc comment.
    pub fn with_cant_split(mut self, cant_split: bool) -> Self {
        self.cant_split = cant_split;
        self
    }
}

impl TableCell {
    /// Creates an empty cell (still valid to write: the writer emits a single empty paragraph for
    /// it, as WordprocessingML requires).
    pub fn new() -> Self {
        Self::default()
    }

    /// Creates a cell containing a single paragraph with the given text.
    pub fn with_text(text: impl Into<String>) -> Self {
        Self {
            blocks: vec![Block::Paragraph(Paragraph::with_text(text))],
            ..Self::default()
        }
    }

    /// Appends a paragraph block and returns the cell for chaining.
    pub fn with_paragraph(mut self, paragraph: Paragraph) -> Self {
        self.blocks.push(Block::Paragraph(paragraph));
        self
    }

    /// Appends a nested table block and returns the cell for chaining.
    ///
    /// WordprocessingML (`CT_Tc`) allows a `w:tbl` inside a cell's content. The writer
    /// automatically appends a trailing empty paragraph after the nested table if this cell doesn't
    /// already end with one, since Word requires cell content to end in a paragraph (see
    /// [`TableCell`]'s doc comment).
    pub fn with_table(mut self, table: Table) -> Self {
        self.blocks.push(Block::Table(table));
        self
    }

    /// Iterates over this cell's paragraphs only, skipping any nested table.
    pub fn paragraphs(&self) -> impl Iterator<Item = &Paragraph> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Paragraph(paragraph) => Some(paragraph),
            Block::Table(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Iterates over this cell's nested tables only, skipping paragraphs.
    pub fn tables(&self) -> impl Iterator<Item = &Table> {
        self.blocks.iter().filter_map(|block| match block {
            Block::Table(table) => Some(table),
            Block::Paragraph(_) | Block::StructuredDocumentTag(_) => None,
        })
    }

    /// Sets how many grid columns this cell spans (for a horizontal merge) and returns it for
    /// chaining. See `horizontal_span`'s doc comment for how this interacts with `TableRow.cells`.
    pub fn with_horizontal_span(mut self, horizontal_span: u32) -> Self {
        self.horizontal_span = Some(horizontal_span);
        self
    }

    /// Sets this cell's role in a vertical merge and returns it for chaining.
    pub fn with_vertical_merge(mut self, vertical_merge: VerticalMerge) -> Self {
        self.vertical_merge = Some(vertical_merge);
        self
    }

    /// Sets whether this cell has a border around it and returns it for chaining. See `border`'s
    /// doc comment.
    pub fn with_border(mut self, border: bool) -> Self {
        self.border = border;
        self
    }

    /// Sets this cell's background shading color and returns it for chaining. See `shading_color`'s
    /// doc comment.
    pub fn with_shading_color(mut self, shading_color: impl Into<String>) -> Self {
        self.shading_color = Some(shading_color.into());
        self
    }

    /// Sets this cell's vertical alignment and returns it for chaining. See `vertical_alignment`'s
    /// doc comment.
    pub fn with_vertical_alignment(mut self, vertical_alignment: CellVerticalAlign) -> Self {
        self.vertical_alignment = Some(vertical_alignment);
        self
    }

    /// Sets this cell's margin overrides (top/left/bottom/right, in twips) and returns it for
    /// chaining. See `margin_top_twips`'s doc comment.
    pub fn with_margins_twips(mut self, top: u32, left: u32, bottom: u32, right: u32) -> Self {
        self.margin_top_twips = Some(top);
        self.margin_left_twips = Some(left);
        self.margin_bottom_twips = Some(bottom);
        self.margin_right_twips = Some(right);
        self
    }

    /// Sets this cell's text flow direction and returns it for chaining. See `text_direction`'s doc
    /// comment.
    pub fn with_text_direction(mut self, text_direction: TextDirection) -> Self {
        self.text_direction = Some(text_direction);
        self
    }

    /// The cell's text: its paragraphs' text, joined with newlines. Any nested table's text is not
    /// included — use [`TableCell::tables`] to reach it.
    pub fn text(&self) -> String {
        self.paragraphs()
            .map(Paragraph::text)
            .collect::<Vec<_>>()
            .join("\n")
    }
}

impl Style {
    /// Creates a style with the given id, display name and kind, and no formatting.
    pub fn new(id: impl Into<String>, name: impl Into<String>, kind: StyleKind) -> Self {
        Self {
            id: id.into(),
            name: name.into(),
            kind,
            based_on: None,
            bold: false,
            italic: false,
            underline: None,
            underline_color: None,
            color: None,
            font_size: None,
            font_family: None,
            highlight: None,
            strike: false,
            vertical_align: None,
            small_caps: false,
            all_caps: false,
            shading_color: None,
            text_border: false,
            character_spacing: None,
            vertical_position: None,
            hidden: false,
            alignment: None,
            line_spacing: None,
            space_before: None,
            space_after: None,
            paragraph_shading_color: None,
            paragraph_border: false,
            keep_with_next: false,
            keep_lines_together: false,
            page_break_before: false,
            tabs: Vec::new(),
            contextual_spacing: false,
        }
    }

    /// Sets the style this one inherits from (by id) and returns it for chaining.
    pub fn with_based_on(mut self, style_id: impl Into<String>) -> Self {
        self.based_on = Some(style_id.into());
        self
    }

    /// Sets whether text in this style is bold and returns it for chaining.
    pub fn with_bold(mut self, bold: bool) -> Self {
        self.bold = bold;
        self
    }

    /// Sets whether text in this style is italic and returns it for chaining.
    pub fn with_italic(mut self, italic: bool) -> Self {
        self.italic = italic;
        self
    }

    /// Sets this style's underline style and returns it for chaining.
    pub fn with_underline(mut self, underline: UnderlineStyle) -> Self {
        self.underline = Some(underline);
        self
    }

    /// Sets the color of this style's underline (a 6-digit RGB hex string, no leading `#`) and
    /// returns it for chaining. Only meaningful once `with_underline` has also been called.
    pub fn with_underline_color(mut self, underline_color: impl Into<String>) -> Self {
        self.underline_color = Some(underline_color.into());
        self
    }

    /// Sets this style's text color (a 6-digit RGB hex string, no leading `#`) and returns it for
    /// chaining.
    pub fn with_color(mut self, color: impl Into<String>) -> Self {
        self.color = Some(color.into());
        self
    }

    /// Sets this style's font size in whole points and returns it for chaining.
    pub fn with_font_size(mut self, font_size: u16) -> Self {
        self.font_size = Some(font_size);
        self
    }

    /// Sets this style's font family/typeface and returns it for chaining.
    pub fn with_font_family(mut self, font_family: impl Into<String>) -> Self {
        self.font_family = Some(font_family.into());
        self
    }

    /// Sets this style's highlight color and returns it for chaining.
    pub fn with_highlight(mut self, highlight: Highlight) -> Self {
        self.highlight = Some(highlight);
        self
    }

    /// Sets whether text in this style is struck through and returns it for chaining.
    pub fn with_strike(mut self, strike: bool) -> Self {
        self.strike = strike;
        self
    }

    /// Sets this style's vertical alignment (superscript/subscript) and returns it for chaining.
    pub fn with_vertical_align(mut self, vertical_align: VerticalAlign) -> Self {
        self.vertical_align = Some(vertical_align);
        self
    }

    /// Sets whether text in this style is displayed as small caps and returns it for chaining.
    pub fn with_small_caps(mut self, small_caps: bool) -> Self {
        self.small_caps = small_caps;
        self
    }

    /// Sets whether text in this style is displayed as all caps and returns it for chaining.
    pub fn with_all_caps(mut self, all_caps: bool) -> Self {
        self.all_caps = all_caps;
        self
    }

    /// Sets this style's background shading color (a 6-digit RGB hex string, no leading `#`) and
    /// returns it for chaining.
    pub fn with_shading_color(mut self, shading_color: impl Into<String>) -> Self {
        self.shading_color = Some(shading_color.into());
        self
    }

    /// Sets whether text in this style has a border and returns it for chaining.
    pub fn with_text_border(mut self, text_border: bool) -> Self {
        self.text_border = text_border;
        self
    }

    /// Sets this style's character spacing adjustment, in twips, and returns it for chaining.
    pub fn with_character_spacing(mut self, character_spacing: i16) -> Self {
        self.character_spacing = Some(character_spacing);
        self
    }

    /// Sets this style's vertical position, raised or lowered from the baseline, in half-points,
    /// and returns it for chaining.
    pub fn with_vertical_position(mut self, vertical_position: i16) -> Self {
        self.vertical_position = Some(vertical_position);
        self
    }

    /// Sets whether text in this style is hidden and returns it for chaining.
    pub fn with_hidden(mut self, hidden: bool) -> Self {
        self.hidden = hidden;
        self
    }

    /// Sets this style's paragraph alignment and returns it for chaining. Only meaningful for
    /// [`StyleKind::Paragraph`] — see the field's doc comment.
    pub fn with_alignment(mut self, alignment: Alignment) -> Self {
        self.alignment = Some(alignment);
        self
    }

    /// Sets this style's line spacing (in `w:spacing`'s "auto" units — see
    /// `Paragraph.line_spacing`'s doc comment) and returns it for chaining. Only meaningful for
    /// [`StyleKind::Paragraph`].
    pub fn with_line_spacing(mut self, line_spacing: u32) -> Self {
        self.line_spacing = Some(line_spacing);
        self
    }

    /// Sets this style's extra space before a paragraph, in twips, and returns it for chaining.
    /// Only meaningful for [`StyleKind::Paragraph`].
    pub fn with_space_before(mut self, space_before: u32) -> Self {
        self.space_before = Some(space_before);
        self
    }

    /// Sets this style's extra space after a paragraph, in twips, and returns it for chaining. Only
    /// meaningful for [`StyleKind::Paragraph`].
    pub fn with_space_after(mut self, space_after: u32) -> Self {
        self.space_after = Some(space_after);
        self
    }

    /// Sets this style's paragraph background shading color and returns it for chaining. Only
    /// meaningful for [`StyleKind::Paragraph`] — see `paragraph_shading_color`'s doc comment for
    /// how this differs from `with_shading_color`.
    pub fn with_paragraph_shading_color(
        mut self,
        paragraph_shading_color: impl Into<String>,
    ) -> Self {
        self.paragraph_shading_color = Some(paragraph_shading_color.into());
        self
    }

    /// Sets whether this style draws a border around the paragraph and returns it for chaining.
    /// Only meaningful for [`StyleKind::Paragraph`] — see `paragraph_border`'s doc comment for how
    /// this differs from `with_text_border`.
    pub fn with_paragraph_border(mut self, paragraph_border: bool) -> Self {
        self.paragraph_border = paragraph_border;
        self
    }

    /// Sets whether this style keeps its paragraph on the same page as the one following it and
    /// returns it for chaining. Only meaningful for [`StyleKind::Paragraph`]. See
    /// `keep_with_next`'s doc comment.
    pub fn with_keep_with_next(mut self, keep_with_next: bool) -> Self {
        self.keep_with_next = keep_with_next;
        self
    }

    /// Sets whether this style keeps its paragraph's lines together on the same page and returns it
    /// for chaining. Only meaningful for [`StyleKind::Paragraph`]. See `keep_lines_together`'s doc
    /// comment.
    pub fn with_keep_lines_together(mut self, keep_lines_together: bool) -> Self {
        self.keep_lines_together = keep_lines_together;
        self
    }

    /// Sets whether this style forces a page break before its paragraph and returns it for
    /// chaining. Only meaningful for [`StyleKind::Paragraph`]. See `page_break_before`'s doc
    /// comment.
    pub fn with_page_break_before(mut self, page_break_before: bool) -> Self {
        self.page_break_before = page_break_before;
        self
    }

    /// Appends a custom tab stop and returns this style for chaining. Only meaningful for
    /// [`StyleKind::Paragraph`]. See `tabs`'s doc comment.
    pub fn with_tab(mut self, tab: TabStop) -> Self {
        self.tabs.push(tab);
        self
    }

    /// Sets whether this style ignores spacing above/below when adjacent to a paragraph sharing the
    /// same style and returns it for chaining. Only meaningful for [`StyleKind::Paragraph`]. See
    /// `contextual_spacing`'s doc comment.
    pub fn with_contextual_spacing(mut self, contextual_spacing: bool) -> Self {
        self.contextual_spacing = contextual_spacing;
        self
    }
}

impl NumberingDefinition {
    /// Creates a numbering definition with the given id and levels (fully custom — see
    /// [`NumberingDefinition::bullet`]/ [`NumberingDefinition::decimal`] for ready-made common
    /// cases).
    pub fn new(id: u32, levels: Vec<ListLevel>) -> Self {
        Self { id, levels }
    }

    /// A ready-made 3-level bulleted (unordered) list, using the same bullet characters, format and
    /// indentation Word's own default "Bullets" gallery entry uses when it doesn't need to fall
    /// back to a Wingdings/Symbol-font glyph — this crate doesn't model fonts, so plain Unicode
    /// bullet characters are used instead of Word's own Wingdings/Symbol ones (which would render
    /// as the wrong glyph without the matching font declared on the run).
    pub fn bullet(id: u32) -> Self {
        Self::new(
            id,
            vec![
                ListLevel::new(NumberFormat::Bullet, "\u{2022}", 720, 360), //                ListLevel::new(NumberFormat::Bullet, "\u{25E6}", 1440, 360), //                ListLevel::new(NumberFormat::Bullet, "\u{25AA}", 2160, 360), //            ],
        )
    }

    /// A ready-made 3-level numbered (ordered) list, using the same cumulative numbering (each
    /// level repeats its ancestors' counters, e.g. "1.1.1.") and indentation Word's own default
    /// "Numbering" gallery entry uses.
    pub fn decimal(id: u32) -> Self {
        Self::new(
            id,
            vec![
                ListLevel::new(NumberFormat::Decimal, "%1.", 360, 360),
                ListLevel::new(NumberFormat::Decimal, "%1.%2.", 792, 432),
                ListLevel::new(NumberFormat::Decimal, "%1.%2.%3.", 1224, 504),
            ],
        )
    }
}

impl ListLevel {
    /// Creates a single indent level with explicit formatting and indentation.
    pub fn new(
        format: NumberFormat,
        text: impl Into<String>,
        indent_twips: i32,
        hanging_twips: i32,
    ) -> Self {
        Self {
            format,
            text: text.into(),
            indent_twips,
            hanging_twips,
        }
    }
}