znote 1.0.0

A lightweight desktop editor for Typst with live preview, built with Tauri
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
//! Word: text that flows and looks like the page. The structure (headings, lists, tables, links,
//! equations) comes from the page compiled for Typst's HTML target; how each piece of text looks
//! and where it sits comes from the laid-out page, matched by span. Pages that are designed rather
//! than written (a cover) are copied as they are, and every other page's header, footer and
//! background become the Word header of its section.

mod drawing;
mod fonts;
mod paged;

use std::collections::{HashMap, HashSet};
use std::fmt::Write as _;
use std::io::{Cursor, Write};

use typst::introspection::{Location, Tag};
use typst::layout::{Abs, Frame, FrameItem, Point, Rect};
use typst::syntax::Span;
use typst::text::FontInstance;
use typst::utils::hash128;
use typst::visualize::Image;
use typst_html::{HtmlDocument, HtmlElement, HtmlFrame, HtmlNode};
use typst_layout::PagedDocument;
use zip::ZipWriter;
use zip::write::SimpleFileOptions;

use self::drawing::{Field, twips};
use self::paged::{Look, Paged};
use super::layout::{Layers, layers, lines, paragraphs};
use super::math::{self, Equations, attribute, name};
use super::{Media, OFFICE, XML, escape, media, png, relationships};

pub use self::paged::text_width;

/// The class of the `hr` that a page break becomes in the HTML compile (see `prelude`).
pub const PAGE_BREAK: &str = "znote-page-break";

const MAIN: &str = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
const DRAWING: &str = "http://schemas.openxmlformats.org/drawingml/2006/main";
const PLACEMENT: &str = "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing";
const COMPATIBILITY: &str = "http://schemas.openxmlformats.org/markup-compatibility/2006";
const WORD: &str = "application/vnd.openxmlformats-officedocument.wordprocessingml";
/// Where Word puts the baseline in a line of exact height, as a share of that height from the top.
const BASELINE: f64 = 0.8;
/// An empty paragraph one point high, to hold drawings or a section's end.
const TINY: &str =
    r#"<w:pPr><w:spacing w:before="0" w:after="0" w:line="20" w:lineRule="exact"/></w:pPr>"#;

fn namespaces() -> String {
    format!(
        r#"xmlns:w="{MAIN}" xmlns:r="{OFFICE}" xmlns:m="{}" xmlns:wp="{PLACEMENT}" xmlns:a="{DRAWING}" xmlns:pic="{}" xmlns:wps="{}" xmlns:mc="{COMPATIBILITY}""#,
        math::NAMESPACE,
        drawing::PICTURE,
        drawing::SHAPE
    )
}

/// What the parts of the file share: pictures, drawing ids and the fonts in use.
pub struct Parts {
    media: Vec<(String, Vec<u8>)>,
    ids: usize,
    faces: fonts::Faces,
}

fn link(links: &mut Vec<(&'static str, String)>, kind: &'static str, target: String) -> String {
    links.push((kind, target));
    format!("rId{}", links.len())
}

impl Parts {
    fn id(&mut self) -> usize {
        self.ids += 1;
        self.ids
    }

    fn picture(&mut self, links: &mut Vec<(&'static str, String)>, media: Media) -> String {
        let file = format!("image{}.{}", self.media.len() + 1, media.extension);
        self.media.push((file.clone(), media.bytes));
        link(links, "image", format!("media/{file}"))
    }

    fn font(&mut self, family: &str, bold: bool, italic: bool, font: &FontInstance) {
        self.faces.entry(family.to_string()).or_default()[fonts::slot(bold, italic)]
            .get_or_insert_with(|| font.clone());
    }
}

#[derive(Clone, Default)]
struct Format {
    bold: bool,
    italic: bool,
    underline: bool,
    strike: bool,
    small_caps: bool,
    highlight: bool,
    code: bool,
    link: bool,
    script: Option<&'static str>,
    colour: Option<String>,
}

/// Where a paragraph sits, for its style.
#[derive(Clone, Copy, PartialEq)]
enum Role {
    /// 0 is the title.
    Heading(usize),
    Caption,
    Quote,
    Code,
    Figure,
}

struct List {
    /// The numbering instance, or none for a list without markers (such as an outline).
    number: Option<usize>,
    /// Where the text of its items starts.
    text: Option<f64>,
}

/// One line of a paragraph on the laid-out page.
#[derive(Clone, Copy)]
struct Line {
    page: usize,
    baseline: f64,
    left: f64,
    right: f64,
    size: f64,
}

/// Where a paragraph's lines are on the laid-out page.
struct Geometry {
    lines: Vec<Line>,
    pitch: Option<f64>,
}

impl Geometry {
    fn first(&self) -> Line {
        self.lines[0]
    }

    fn last(&self) -> Line {
        self.lines[self.lines.len() - 1]
    }
}

/// A paragraph or table of the body, with the page it is on.
struct Out {
    xml: String,
    page: Option<usize>,
    page_break: bool,
}

/// A table cell as written, before the table knows its columns.
struct Cell {
    row: usize,
    column: usize,
    wide: usize,
    tall: usize,
    content: String,
    found: Vec<usize>,
}

struct Writer<'a> {
    paged: &'a Paged,
    parts: &'a mut Parts,
    links: Vec<(&'static str, String)>,
    out: Vec<Out>,
    runs: String,
    /// Occurrences of the paragraph being written; and of the table cell, if in one.
    found: Vec<usize>,
    cell: Option<Vec<usize>>,
    cursor: usize,
    /// The last run's occurrence and look, and whether its text ended in a space.
    previous_run: Option<usize>,
    look: Option<Look>,
    spaced: bool,
    /// Something in the paragraph that a fixed line height would cut off.
    tall: bool,
    /// The last paragraph's last line and line height.
    previous: Option<(Line, f64)>,
    leading: f64,
    roles: Vec<Role>,
    headings: Vec<(Location, usize)>,
    heading_looks: [Option<Look>; 7],
    lists: Vec<List>,
    item: bool,
    bookmarks: Vec<String>,
    marks: usize,
    numbers: Vec<usize>,
    /// Outline entries: the heading the entry links to, and its page number.
    outline: bool,
    target: Option<String>,
    targets: HashMap<String, u64>,
    leader: bool,
    room: f64,
    /// The span of the image whose frame comes next, and how often each image was placed.
    placed: HashMap<Span, usize>,
    justified: bool,
    /// An occurrence only partly written yet, and what of its text is left.
    partial: Option<(usize, String)>,
    /// Footnote texts by the id Typst links them with; and the footnotes written so far, with
    /// their own relationships.
    notes: HashMap<String, HtmlElement>,
    footnotes: Vec<String>,
    note_links: Vec<(&'static str, String)>,
    in_note: bool,
    /// The figure whose content comes next, and how often each figure was taken from its page.
    figure: Option<u128>,
    figures_seen: HashMap<u128, usize>,
    document: &'a PagedDocument,
    /// The space above each kind of paragraph (style and size), learned where Typst set one
    /// below another on the same page.
    spacing: HashMap<String, f64>,
    /// The paragraph being written holds a picture.
    drawing: bool,
    /// Centre the next paragraph whatever its lines say (a display formula, whose lines are only
    /// partly known).
    centre: bool,
}

fn bookmark(id: &str) -> String {
    let name: String = id
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .take(39)
        .collect();
    format!("_{name}")
}

fn css(element: &HtmlElement) -> String {
    let mut css = element.css.to_inline().to_string();
    if let Some(style) = attribute(element, "style") {
        css.push(';');
        css.push_str(style);
    }
    css.replace(' ', "")
}

fn cells(row: &HtmlElement) -> Vec<&HtmlElement> {
    row.children
        .iter()
        .filter_map(|node| match node {
            HtmlNode::Element(cell) if matches!(&*name(cell), "td" | "th") => Some(cell),
            _ => None,
        })
        .collect()
}

/// The span of the first image or shape in a frame, to find where Typst put it.
fn drawn(frame: &Frame) -> Option<Span> {
    frame.items().find_map(|(_, item)| match item {
        FrameItem::Image(_, _, span) | FrameItem::Shape(_, span) if !span.is_detached() => {
            Some(*span)
        }
        FrameItem::Group(group) => drawn(&group.frame),
        _ => None,
    })
}

/// Whether HTML nodes hold anything to show: text, a picture, a table, a formula.
fn holds(nodes: &[HtmlNode]) -> bool {
    nodes.iter().any(|node| match node {
        HtmlNode::Text(text, _) => !text.trim().is_empty(),
        HtmlNode::Frame(_) => true,
        HtmlNode::Element(element) => {
            matches!(&*name(element), "table" | "img" | "math" | "hr") || holds(&element.children)
        }
        HtmlNode::Tag(_) => false,
    })
}

fn single_image(frame: &Frame) -> Option<(&Image, typst::layout::Size)> {
    let mut found = None;
    for (_, item) in frame.items() {
        match item {
            FrameItem::Image(image, size, _) if found.is_none() => found = Some((image, *size)),
            FrameItem::Group(group) if found.is_none() => found = Some(single_image(&group.frame)?),
            FrameItem::Tag(_) => {}
            _ => return None,
        }
    }
    found
}

/// The spans of all text in the HTML compile.
fn spans(nodes: &[HtmlNode], found: &mut HashSet<Span>) {
    for node in nodes {
        match node {
            HtmlNode::Text(_, span) if !span.is_detached() => {
                found.insert(*span);
            }
            HtmlNode::Element(element) => spans(&element.children, found),
            _ => {}
        }
    }
}

fn first_span(nodes: &[HtmlNode]) -> Option<Span> {
    nodes.iter().find_map(|node| match node {
        HtmlNode::Text(text, span) if !span.is_detached() && !text.trim().is_empty() => Some(*span),
        HtmlNode::Element(element) => first_span(&element.children),
        _ => None,
    })
}

/// The footnote texts Typst puts at the end of the HTML, by id.
fn notes(nodes: &[HtmlNode]) -> HashMap<String, HtmlElement> {
    let mut found = HashMap::new();
    for node in nodes {
        let HtmlNode::Element(element) = node else {
            continue;
        };
        if attribute(element, "role") == Some("doc-endnotes") {
            let mut items = Vec::new();
            collect(&element.children, "li", &mut items);
            for item in items {
                if let Some(id) = attribute(item, "id") {
                    found.insert(id.to_string(), item.clone());
                }
            }
        } else {
            found.extend(notes(&element.children));
        }
    }
    found
}

fn collect<'a>(nodes: &'a [HtmlNode], tag: &str, found: &mut Vec<&'a HtmlElement>) {
    for node in nodes {
        if let HtmlNode::Element(element) = node {
            if &*name(element) == tag {
                found.push(element);
            } else {
                collect(&element.children, tag, found);
            }
        }
    }
}

/// The page number of everything with an `id`, for an outline's page numbers. An element without
/// text of its own (a page break that took a heading's id) gets the page of the text after it.
fn targets(
    nodes: &[HtmlNode],
    paged: &Paged,
    waiting: &mut Vec<String>,
    found: &mut HashMap<String, u64>,
) {
    for node in nodes {
        let HtmlNode::Element(element) = node else {
            continue;
        };
        if let Some(id) = attribute(element, "id") {
            waiting.push(id.to_string());
        }
        if !waiting.is_empty()
            && let Some(span) = first_span(&element.children)
            && let Some(occurrence) = paged.heading(span)
        {
            let number = paged.sheets[paged.occurrences[occurrence].page].number;
            for id in waiting.drain(..) {
                found.insert(id, number);
            }
        }
        targets(&element.children, paged, waiting, found);
    }
}

fn colour([red, green, blue]: [u8; 3]) -> String {
    format!("{red:02X}{green:02X}{blue:02X}")
}

impl<'a> Writer<'a> {
    fn region(&self, page: usize) -> Rect {
        let sheet = &self.paged.sheets[page];
        sheet.body.unwrap_or(Rect::new(
            Point::zero(),
            Point::new(Abs::pt(sheet.width), Abs::pt(sheet.height)),
        ))
    }

    /// The smallest filled area on `page` around `point`: a table cell's background.
    fn fill_at(&self, page: usize, point: Point) -> Option<&paged::Fill> {
        self.paged.sheets[page]
            .fills
            .iter()
            .filter(|fill| {
                fill.rect.min.x <= point.x
                    && point.x <= fill.rect.max.x
                    && fill.rect.min.y <= point.y
                    && point.y <= fill.rect.max.y
            })
            .min_by(|a, b| paged::surface(&a.rect).total_cmp(&paged::surface(&b.rect)))
    }

    fn run_properties(&mut self, look: Option<&Look>, format: &Format, extra: f64) -> String {
        let mut xml = String::new();
        if look.is_none() && format.link {
            xml.push_str(r#"<w:rStyle w:val="Hyperlink"/>"#);
        } else if look.is_none() && format.code {
            xml.push_str(r#"<w:rStyle w:val="VerbatimChar"/>"#);
        }
        let (bold, italic) = look.map_or((format.bold, format.italic), |look| {
            (look.bold, look.italic)
        });
        if let Some(look) = look {
            self.parts
                .font(&look.family, look.bold, look.italic, &look.font);
            let family = escape(&look.family);
            let _ = write!(
                xml,
                r#"<w:rFonts w:ascii="{family}" w:hAnsi="{family}" w:eastAsia="{family}" w:cs="{family}"/>"#
            );
        }
        if bold {
            xml.push_str("<w:b/>");
        }
        if italic {
            xml.push_str("<w:i/>");
        }
        if format.small_caps {
            xml.push_str("<w:smallCaps/>");
        }
        if format.strike {
            xml.push_str("<w:strike/>");
        }
        match (look, &format.colour) {
            (Some(look), _) => {
                let _ = write!(xml, r#"<w:color w:val="{}"/>"#, colour(look.colour));
            }
            (None, Some(own)) => {
                let _ = write!(xml, r#"<w:color w:val="{own}"/>"#);
            }
            _ => {}
        }
        let spacing = look.map_or(0.0, |look| look.tracking) + extra;
        if spacing.abs() >= 0.05 {
            let _ = write!(xml, r#"<w:spacing w:val="{}"/>"#, twips(spacing));
        }
        if let Some(look) = look.filter(|_| format.script.is_none()) {
            let size = (look.size * 2.0).round() as i64;
            let _ = write!(xml, r#"<w:sz w:val="{size}"/><w:szCs w:val="{size}"/>"#);
        }
        if format.highlight {
            xml.push_str(r#"<w:highlight w:val="yellow"/>"#);
        }
        if format.underline {
            xml.push_str(r#"<w:u w:val="single"/>"#);
        }
        if let Some(script) = format.script {
            let _ = write!(xml, r#"<w:vertAlign w:val="{script}"/>"#);
        }
        if xml.is_empty() {
            xml
        } else {
            format!("<w:rPr>{xml}</w:rPr>")
        }
    }

    fn geometry(&self) -> Option<Geometry> {
        let paged = self.paged;
        let mut counts: HashMap<usize, usize> = HashMap::new();
        for &occurrence in &self.found {
            if let Some(block) = paged.occurrences[occurrence].block {
                *counts.entry(block).or_default() += 1;
            }
        }
        let block = counts
            .into_iter()
            .max_by_key(|(block, count)| (*count, usize::MAX - block))
            .map(|(block, _)| block);
        let occurrences = match block {
            Some(block) => &paged.blocks[block].occurrences,
            None => &self.found,
        };
        let mut lines: Vec<Line> = Vec::new();
        let mut sorted: Vec<&paged::Occurrence> = occurrences
            .iter()
            .map(|&index| &paged.occurrences[index])
            .filter(|occurrence| !occurrence.chrome)
            .collect();
        sorted.sort_by(|a, b| {
            a.page
                .cmp(&b.page)
                .then(a.baseline.total_cmp(&b.baseline))
                .then(a.x.total_cmp(&b.x))
        });
        for occurrence in sorted {
            // Raised or lowered text (a footnote marker) sits on the line it is in.
            match lines.last_mut() {
                Some(line)
                    if line.page == occurrence.page
                        && (line.baseline - occurrence.baseline).abs()
                            < 0.5 * line.size.max(occurrence.look.size) =>
                {
                    line.left = line.left.min(occurrence.x);
                    line.right = line.right.max(occurrence.right);
                    if occurrence.look.size > line.size {
                        line.baseline = occurrence.baseline;
                        line.size = occurrence.look.size;
                    }
                }
                _ => lines.push(Line {
                    page: occurrence.page,
                    baseline: occurrence.baseline,
                    left: occurrence.x,
                    right: occurrence.right,
                    size: occurrence.look.size,
                }),
            }
        }
        // Only the lines from this paragraph's first text to its last: a block can hold more (a
        // list's item tag covers the whole list).
        let place = |index: &usize| {
            let occurrence = &paged.occurrences[*index];
            (occurrence.page, (occurrence.baseline * 2.0).round() as i64)
        };
        if let (Some(from), Some(to)) = (
            self.found.iter().map(place).min(),
            self.found.iter().map(place).max(),
        ) {
            lines.retain(|line| {
                let at = (line.page, (line.baseline * 2.0).round() as i64);
                from <= at && at <= to
            });
        }
        if lines.is_empty() {
            return None;
        }
        let mut pitches: Vec<f64> = lines
            .windows(2)
            .filter(|pair| pair[0].page == pair[1].page)
            .map(|pair| pair[1].baseline - pair[0].baseline)
            .filter(|pitch| *pitch > 0.0)
            .collect();
        pitches.sort_by(f64::total_cmp);
        Some(Geometry {
            pitch: pitches.get(pitches.len() / 2).copied(),
            lines,
        })
    }

    /// Alignment and indents from where the lines sit in `region`.
    fn arrangement(geometry: &Geometry, region: Rect) -> (&'static str, f64, f64, f64) {
        let (left, right) = (region.min.x.to_pt(), region.max.x.to_pt());
        let centre = (left + right) / 2.0;
        let lines: Vec<&Line> = geometry
            .lines
            .iter()
            .filter(|line| line.page == geometry.first().page)
            .collect();
        let widest = lines.iter().map(|line| line.right).fold(left, f64::max);
        let centred = |line: &&Line| ((line.left + line.right) / 2.0 - centre).abs() < 1.5;
        let starts = lines
            .iter()
            .map(|line| line.left)
            .fold(f64::INFINITY, f64::min);
        if lines.len() > 1 {
            let rest = lines[1..]
                .iter()
                .map(|line| line.left)
                .fold(f64::INFINITY, f64::min);
            let first_line = lines[0].left - rest;
            let indent = (rest - left).max(0.0);
            // Justified: every line but the last ends at the same place, give or take punctuation
            // that Typst lets hang into the margin.
            let mut ends: Vec<f64> = lines[..lines.len() - 1]
                .iter()
                .map(|line| line.right)
                .collect();
            ends.sort_by(f64::total_cmp);
            let end = ends[ends.len() / 2];
            let full = ends.iter().all(|right| (right - end).abs() < 3.0);
            if full && lines[lines.len() - 1].right < end - 3.0 {
                return ("both", indent, first_line, (right - end).max(0.0));
            }
            let lefts_differ = lines.iter().any(|line| (line.left - starts).abs() > 1.5);
            if lefts_differ && lines.iter().all(centred) {
                return ("center", 0.0, 0.0, 0.0);
            }
            if lefts_differ && lines.iter().all(|line| widest - line.right < 1.5) {
                return ("right", 0.0, 0.0, (right - widest).max(0.0));
            }
            return ("left", indent, first_line, 0.0);
        }
        let line = lines[0];
        let (before, after) = (line.left - left, right - line.right);
        // A line across most of the width (an outline entry with its leader) is not aligned
        // anywhere but left.
        if line.right - line.left > 0.6 * (right - left) {
            return ("left", before.max(0.0), 0.0, 0.0);
        }
        if before > 3.0 && centred(&line) {
            ("center", 0.0, 0.0, 0.0)
        } else if before > 3.0 && after < 1.5 {
            ("right", 0.0, 0.0, 0.0)
        } else if before > 0.3 * (right - left) && after < before / 3.0 {
            // Set against the right, inside a block that keeps it off the edge (a quote's
            // attribution).
            ("right", 0.0, 0.0, after.max(0.0))
        } else {
            ("left", before.max(0.0), 0.0, 0.0)
        }
    }

    fn style(&self) -> Option<String> {
        if self.in_note {
            return Some("FootnoteText".into());
        }
        let heading = self.headings.last().map(|(_, level)| *level).or_else(|| {
            self.roles.iter().rev().find_map(|role| match role {
                Role::Heading(level) => Some(*level),
                _ => None,
            })
        });
        match (heading, self.roles.last()) {
            (Some(0), _) => Some("Title".into()),
            (Some(level), _) => Some(format!("Heading{level}")),
            (_, Some(Role::Caption)) => Some("Caption".into()),
            (_, Some(Role::Quote)) => Some("Quote".into()),
            (_, Some(Role::Code)) => Some("SourceCode".into()),
            _ if !self.lists.is_empty() => Some("ListParagraph".into()),
            _ => None,
        }
    }

    fn heading(&self) -> Option<usize> {
        self.headings.last().map(|(_, level)| *level).or_else(|| {
            self.roles.iter().rev().find_map(|role| match role {
                Role::Heading(level) => Some(*level),
                _ => None,
            })
        })
    }

    /// The paragraph properties, from the paragraph's place on the laid-out page.
    fn properties(&mut self, geometry: Option<&Geometry>) -> String {
        let mut xml = String::new();
        if let Some(style) = self.style() {
            let _ = write!(xml, r#"<w:pStyle w:val="{style}"/>"#);
        }
        let in_cell = self.cell.is_some();
        let region = geometry.map(|geometry| {
            let first = geometry.first();
            if in_cell {
                self.fill_at(
                    first.page,
                    Point::new(Abs::pt(first.left + 0.5), Abs::pt(first.baseline - 1.0)),
                )
                .map_or_else(|| self.region(first.page), |fill| fill.rect)
            } else {
                self.region(first.page)
            }
        });
        let numbered =
            self.heading().is_none() && self.lists.last().is_some_and(|list| list.number.is_some());
        let mut indent = String::new();
        if self.heading().is_none()
            && let Some(list) = self.lists.last()
            && list.number.is_some()
        {
            let level = (self.lists.len() - 1).min(8);
            // Where the item's own text starts, not its marker.
            let text = geometry.and_then(|geometry| {
                let first = geometry.first();
                self.found
                    .iter()
                    .map(|&index| &self.paged.occurrences[index])
                    .filter(|found| {
                        found.page == first.page && (found.baseline - first.baseline).abs() < 0.5
                    })
                    .map(|found| found.x)
                    .reduce(f64::min)
            });
            let marker = self
                .lists
                .iter()
                .rev()
                .nth(1)
                .and_then(|parent| parent.text)
                .or(region.map(|region| region.min.x.to_pt()));
            let left = text
                .zip(region)
                .map(|(text, region)| text - region.min.x.to_pt());
            let hanging = text
                .zip(marker)
                .map(|(text, marker)| (text - marker).max(9.0));
            if self.item {
                let _ = write!(
                    xml,
                    r#"<w:numPr><w:ilvl w:val="{level}"/><w:numId w:val="{}"/></w:numPr>"#,
                    list.number.unwrap_or(1)
                );
            }
            match (left, hanging) {
                (Some(left), Some(hanging)) if self.item => {
                    indent = format!(
                        r#"<w:ind w:left="{}" w:hanging="{}"/>"#,
                        twips(left),
                        twips(hanging)
                    );
                }
                (Some(left), _) => indent = format!(r#"<w:ind w:left="{}"/>"#, twips(left)),
                _ => indent = format!(r#"<w:ind w:left="{}"/>"#, 720 * (level + 1)),
            }
            if let (Some(list), Some(text)) = (self.lists.last_mut(), text)
                && list.text.is_none()
            {
                list.text = Some(text);
            }
        }
        if self.outline && self.target.is_some() {
            let leader = if self.leader {
                r#" w:leader="dot""#
            } else {
                ""
            };
            let stop = region.map_or(self.room, |region| (region.max.x - region.min.x).to_pt());
            let _ = write!(
                xml,
                r#"<w:tabs><w:tab w:val="right"{leader} w:pos="{}"/></w:tabs>"#,
                twips(stop)
            );
        }
        let Some(geometry) = geometry else {
            let _ = write!(
                xml,
                r#"<w:spacing w:before="{}" w:after="0"/>{indent}"#,
                twips(6.0)
            );
            if self.roles.contains(&Role::Figure) {
                xml.push_str(r#"<w:jc w:val="center"/>"#);
            }
            return format!("<w:pPr>{xml}</w:pPr>");
        };
        let region = region.unwrap_or(Rect::new(Point::zero(), Point::zero()));
        let first = geometry.first();
        let mut line = geometry.pitch.unwrap_or(first.size * self.leading);
        // The space above this kind of paragraph where Typst had one above it on the same page.
        let kind = format!("{:?}{}", self.style(), (first.size * 2.0).round());
        // Not seen yet: about a line of its size above a heading, half that above other text.
        let learned = self.spacing.get(&kind).copied().or_else(|| {
            let share = if self.heading().is_some() { 1.0 } else { 0.5 };
            Some(share * first.size)
        });
        // Room from the line above (or the top of the body) down to this baseline.
        let room = match self.previous {
            Some((previous, height)) if previous.page == first.page => {
                Some(first.baseline - previous.baseline - (1.0 - BASELINE) * height)
            }
            _ if in_cell || self.in_note => None,
            // Typst moved it to a new page with room left on the last one (to keep a heading with
            // what follows): Word may not, so it gets the space it has elsewhere. On a full page
            // Word breaks too, and the space is the top of the page.
            Some((previous, _))
                if self.region(previous.page).max.y.to_pt() - previous.baseline > line =>
            {
                learned.map(|before| before + BASELINE * line)
            }
            _ => Some(first.baseline - region.min.y.to_pt()),
        };
        // Less room than the line needs (Typst has no space above a block at the top of a page):
        // a single line gets shorter instead, so its baseline still lands in place.
        if let Some(room) = room
            && room < BASELINE * line
            && geometry.pitch.is_none()
        {
            line = (room / BASELINE).max(line * 0.6);
        }
        let before = room.map_or(0.0, |room| room - BASELINE * line);
        if self
            .previous
            .is_some_and(|(previous, _)| previous.page == first.page)
            && !in_cell
            && !self.in_note
        {
            self.spacing.entry(kind).or_insert(before.max(0.0));
        }
        // A picture sits on the baseline of a line as tall as itself.
        let (rule, line) = if self.drawing {
            ("auto", line)
        } else if self.tall {
            ("atLeast", line)
        } else {
            ("exact", line)
        };
        let _ = write!(
            xml,
            r#"<w:spacing w:before="{}" w:after="0" w:line="{}" w:lineRule="{rule}"/>"#,
            twips(before.clamp(0.0, 400.0)),
            if rule == "auto" { 240 } else { twips(line) },
        );
        let (align, left, first_line, right) = if self.centre {
            ("center", 0.0, 0.0, 0.0)
        } else {
            Self::arrangement(geometry, region)
        };
        if !numbered && !in_cell {
            let mut attributes = String::new();
            if left > 1.0 {
                let _ = write!(attributes, r#" w:left="{}""#, twips(left));
            }
            if right > 1.0 {
                let _ = write!(attributes, r#" w:right="{}""#, twips(right));
            }
            if first_line > 1.0 {
                let _ = write!(attributes, r#" w:firstLine="{}""#, twips(first_line));
            } else if first_line < -1.0 {
                let _ = write!(attributes, r#" w:hanging="{}""#, twips(-first_line));
            }
            if !attributes.is_empty() {
                indent = format!("<w:ind{attributes}/>");
            }
        }
        xml.push_str(&indent);
        if align != "left" {
            let _ = write!(xml, r#"<w:jc w:val="{align}"/>"#);
        }
        self.justified |= align == "both";
        self.previous = Some((geometry.last(), line));
        format!("<w:pPr>{xml}</w:pPr>")
    }

    fn marks(&mut self) -> String {
        let mut xml = String::new();
        for name in std::mem::take(&mut self.bookmarks) {
            self.marks += 1;
            let _ = write!(
                xml,
                r#"<w:bookmarkStart w:id="{0}" w:name="{name}"/><w:bookmarkEnd w:id="{0}"/>"#,
                self.marks
            );
        }
        xml
    }

    fn push(&mut self, xml: String, page: Option<usize>) {
        self.out.push(Out {
            xml,
            page,
            page_break: false,
        });
    }

    fn flush(&mut self) {
        if self.runs.is_empty() {
            return;
        }
        let geometry = self.geometry();
        if let Some(level) = self.heading()
            && self.heading_looks[level].is_none()
        {
            self.heading_looks[level] = self.look.clone();
        }
        let properties = self.properties(geometry.as_ref());
        let marks = self.marks();
        let mut runs = std::mem::take(&mut self.runs);
        if self.outline
            && let Some(target) = self.target.take()
        {
            let number = self
                .targets
                .get(&target)
                .map(u64::to_string)
                .unwrap_or_default();
            let properties =
                self.run_properties(self.look.clone().as_ref(), &Format::default(), 0.0);
            let _ = write!(
                runs,
                r#"<w:r>{properties}<w:tab/></w:r><w:fldSimple w:instr=" PAGEREF {} \h "><w:r>{properties}<w:t>{number}</w:t></w:r></w:fldSimple>"#,
                bookmark(&target)
            );
        }
        let page = geometry.map(|geometry| geometry.first().page);
        self.push(format!("<w:p>{properties}{marks}{runs}</w:p>"), page);
        self.found.clear();
        self.partial = None;
        self.previous_run = None;
        self.spaced = false;
        self.tall = false;
        self.item = false;
    }

    fn block(&mut self, role: Option<Role>, element: &HtmlElement, format: &Format) {
        self.flush();
        self.roles.extend(role);
        self.nodes(&element.children, format);
        self.flush();
        if role.is_some() {
            self.roles.pop();
        }
    }

    fn nodes(&mut self, nodes: &[HtmlNode], format: &Format) {
        for node in nodes {
            match node {
                HtmlNode::Tag(Tag::Start(content, _)) => {
                    let level = if content.is::<typst::model::HeadingElem>() {
                        match content.get_by_name("level") {
                            Ok(typst::foundations::Value::Int(level)) => {
                                Some(level.clamp(1, 6) as usize)
                            }
                            _ => Some(1),
                        }
                    } else if content.is::<typst::model::TitleElem>() {
                        Some(0)
                    } else {
                        None
                    };
                    if let Some(key) = paged::figure_key(content) {
                        self.figure = Some(key);
                    }
                    if let (Some(level), Some(location)) = (level, content.location()) {
                        self.flush();
                        self.headings.push((location, level));
                    }
                }
                HtmlNode::Tag(Tag::End(location, ..)) => {
                    if self
                        .headings
                        .last()
                        .is_some_and(|(open, _)| open == location)
                    {
                        self.flush();
                        self.headings.pop();
                    }
                }
                HtmlNode::Text(text, span) => self.text(text, *span, format),
                HtmlNode::Element(element) => self.element(element, format),
                HtmlNode::Frame(frame) => self.frame(frame),
            }
        }
    }

    /// The kinds of block the text being written is in.
    fn kinds(&self) -> &'static [&'static str] {
        if self.outline {
            &["entry"]
        } else if self.heading().is_some() {
            &["heading", "title"]
        } else if self.cell.is_some() {
            &["cell"]
        } else if self.roles.last() == Some(&Role::Caption) {
            &["caption"]
        } else {
            &[]
        }
    }

    /// The occurrence of a piece of text on the laid-out page: by its span, or else by its text.
    fn find(&mut self, span: Span, text: &str) -> Option<usize> {
        let kinds = self.kinds();
        let wanted: String = text.split_whitespace().collect::<Vec<_>>().join(" ");
        // The rest of a run Typst set in one piece and HTML in several ("Figure", " ", "1", ":").
        let rest = self.partial.as_ref().and_then(|(index, rest)| {
            (!wanted.is_empty() && rest.trim_start().starts_with(&wanted)).then_some(*index)
        });
        let found = rest
            .or_else(|| {
                (!span.is_detached())
                    .then(|| self.paged.find(span, self.cursor, kinds))
                    .flatten()
            })
            .or_else(|| self.paged.find_text(text, self.cursor, kinds));
        self.partial = found.and_then(|index| {
            let own: String = self.paged.occurrences[index]
                .text
                .split_whitespace()
                .collect::<Vec<_>>()
                .join(" ");
            let rest = match &self.partial {
                Some((at, rest)) if *at == index => rest.trim_start().to_string(),
                _ => own,
            };
            rest.strip_prefix(&wanted)
                .filter(|rest| !rest.trim().is_empty())
                .map(|rest| (index, rest.to_string()))
        });
        let found = found?;
        self.cursor = self.cursor.max(self.paged.order(found));
        let mut all = vec![found];
        if !span.is_detached() {
            all.extend(self.paged.continuation(found, span));
        }
        self.found.extend(&all);
        if let Some(cell) = &mut self.cell {
            cell.extend(&all);
        }
        Some(found)
    }

    fn text(&mut self, text: &str, span: Span, format: &Format) {
        if self.runs.is_empty() && text.trim().is_empty() && !self.roles.contains(&Role::Code) {
            return;
        }
        let found = if text.trim().is_empty() {
            None
        } else {
            self.find(span, text)
        };
        let paged = self.paged;
        if let Some(found) = found {
            self.look = Some(paged.occurrences[found].look.clone());
        }
        let look = self.look.clone();
        // Typst's own spacing (as between a heading's number and its text) is not text in HTML.
        if let (Some(found), Some(before)) = (found, self.previous_run) {
            let (now, then) = (&paged.occurrences[found], &paged.occurrences[before]);
            let gap = now.x - then.right;
            // A space already written counts for a quarter em.
            let written = if self.spaced || text.starts_with(char::is_whitespace) {
                0.25 * now.look.size
            } else {
                0.0
            };
            if now.page == then.page
                && (now.baseline - then.baseline).abs() < 0.5
                && gap - written > 0.2 * now.look.size
            {
                let extra = gap - written - 0.25 * now.look.size;
                let properties = self.run_properties(Some(&now.look), format, extra);
                let _ = write!(
                    self.runs,
                    r#"<w:r>{properties}<w:t xml:space="preserve"> </w:t></w:r>"#
                );
            }
        }
        let properties = self.run_properties(look.as_ref(), format, 0.0);
        for (index, line) in text.split('\n').enumerate() {
            if index > 0 {
                let _ = write!(self.runs, "<w:r>{properties}<w:br/></w:r>");
            }
            if !line.is_empty() {
                let _ = write!(
                    self.runs,
                    r#"<w:r>{properties}<w:t xml:space="preserve">{}</w:t></w:r>"#,
                    escape(line)
                );
            }
        }
        if found.is_some() {
            self.previous_run = found;
        }
        self.spaced = text.ends_with(char::is_whitespace);
    }

    fn frame(&mut self, frame: &HtmlFrame) {
        let picture = match single_image(&frame.inner) {
            Some((image, size)) => media(image, size).map(|media| {
                (
                    media,
                    size.x.to_pt(),
                    size.y.to_pt(),
                    image.alt().map(str::to_string),
                )
            }),
            None => png(&frame.inner, 2.0).map(|bytes| {
                let size = frame.inner.size();
                let media = Media {
                    bytes,
                    extension: "png",
                };
                (media, size.x.to_pt(), size.y.to_pt(), None)
            }),
        };
        // A picture that cannot be drawn is left out rather than failing the whole file.
        let Ok((media, width, height, alt)) = picture else {
            return;
        };
        if width <= 0.0 || height <= 0.0 {
            return;
        }
        // Where Typst put the image: its page, size and place.
        let paged = self.paged;
        let placement = drawn(&frame.inner).and_then(|span| {
            let seen = self.placed.entry(span).or_default();
            *seen += 1;
            paged.image(span, *seen - 1)
        });
        if placement.is_some_and(|placement| paged.sheets[placement.page].designed) {
            return;
        }
        self.picture(media, (width, height), alt.as_deref(), placement);
    }

    /// The figure with `key` as Typst drew it, cut from its page.
    fn drawing_of_figure(&mut self, key: u128) {
        let paged = self.paged;
        let seen = self.figures_seen.entry(key).or_default();
        *seen += 1;
        let Some(placement) = paged.figure(key, *seen - 1) else {
            return;
        };
        if paged.sheets[placement.page].designed {
            return;
        }
        // A little room around it, for strokes that reach past the shapes they outline.
        let room = Point::splat(Abs::pt(2.0));
        let rect = Rect::new(placement.rect.min - room, placement.rect.max + room);
        let placement = paged::Placement::at(placement.page, rect);
        let placement = &placement;
        let size = typst::layout::Size::new(rect.max.x - rect.min.x, rect.max.y - rect.min.y);
        let mut frame = Frame::soft(size);
        frame.push(
            Point::zero() - rect.min,
            FrameItem::Group(typst::layout::GroupItem::new(
                self.document.pages()[placement.page].frame.clone(),
            )),
        );
        let Ok(bytes) = png(&frame, 2.0) else {
            return;
        };
        let media = Media {
            bytes,
            extension: "png",
        };
        self.picture(
            media,
            (size.x.to_pt(), size.y.to_pt()),
            None,
            Some(placement),
        );
    }

    /// A picture in a paragraph of its own, sized and spaced as Typst placed it if known.
    fn picture(
        &mut self,
        media: Media,
        (width, height): (f64, f64),
        alt: Option<&str>,
        placement: Option<&paged::Placement>,
    ) {
        let (width, height) = placement.map_or((width, height), |placement| {
            let rect = placement.rect;
            (
                (rect.max.x - rect.min.x).to_pt(),
                (rect.max.y - rect.min.y).to_pt(),
            )
        });
        let scale = (self.room / width).min(1.0);
        self.flush();
        self.roles.push(Role::Figure);
        let link = self.parts.picture(&mut self.links, media);
        let id = self.parts.id();
        let picture = drawing::inline_picture(id, &link, width * scale, height * scale, alt);
        self.drawing = true;
        let geometry = placement.map(|placement| Geometry {
            lines: vec![Line {
                page: placement.page,
                baseline: placement.rect.max.y.to_pt(),
                left: placement.rect.min.x.to_pt(),
                right: placement.rect.max.x.to_pt(),
                size: height,
            }],
            // Word sets a picture on the baseline: its line reaches from its top to the baseline.
            pitch: Some(height / BASELINE),
        });
        let properties = self.properties(geometry.as_ref());
        if let Some((line, _)) = self.previous.filter(|_| placement.is_some()) {
            self.previous = Some((line, 0.0));
        }
        self.drawing = false;
        let page = placement.map(|placement| placement.page);
        self.push(format!("<w:p>{properties}{picture}</w:p>"), page);
        self.roles.pop();
    }

    /// A Word footnote for Typst's footnote `id`, written where its marker is.
    fn footnote(&mut self, id: &str) -> bool {
        let Some(note) = self.notes.get(id).cloned() else {
            return false;
        };
        let number = self.footnotes.len() + 1;
        // The note's text is written on its own, then everything is put back.
        let runs = std::mem::take(&mut self.runs);
        let found = std::mem::take(&mut self.found);
        let out = std::mem::take(&mut self.out);
        let previous = self.previous.take();
        let lists = std::mem::take(&mut self.lists);
        let roles = std::mem::take(&mut self.roles);
        let headings = std::mem::take(&mut self.headings);
        let (previous_run, look, spaced, partial, item) = (
            self.previous_run.take(),
            self.look.clone(),
            self.spaced,
            self.partial.take(),
            self.item,
        );
        std::mem::swap(&mut self.links, &mut self.note_links);
        self.in_note = true;
        self.footnotes.push(String::new());
        let content: Vec<HtmlNode> = note
            .children
            .iter()
            .filter(|node| {
                !matches!(node, HtmlNode::Element(child) if attribute(child, "role") == Some("doc-backlink"))
            })
            .cloned()
            .collect();
        self.nodes(&content, &Format::default());
        self.flush();
        let mut xml: String = std::mem::take(&mut self.out)
            .into_iter()
            .map(|out| out.xml)
            .collect();
        let mark =
            r#"<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteRef/></w:r>"#;
        match xml.find("</w:pPr>") {
            Some(at) if xml.starts_with("<w:p><w:pPr>") => {
                xml.insert_str(at + "</w:pPr>".len(), mark)
            }
            _ => {
                xml = format!(
                    r#"<w:p><w:pPr><w:pStyle w:val="FootnoteText"/></w:pPr>{mark}</w:p>{xml}"#
                )
            }
        }
        self.footnotes[number - 1] = format!(r#"<w:footnote w:id="{number}">{xml}</w:footnote>"#);
        self.in_note = false;
        std::mem::swap(&mut self.links, &mut self.note_links);
        self.runs = runs;
        self.found = found;
        self.out = out;
        self.previous = previous;
        self.lists = lists;
        self.roles = roles;
        self.headings = headings;
        self.previous_run = previous_run;
        self.look = look;
        self.spaced = spaced;
        self.partial = partial;
        self.item = item;
        let _ = write!(
            self.runs,
            r#"<w:r><w:rPr><w:rStyle w:val="FootnoteReference"/></w:rPr><w:footnoteReference w:id="{number}"/></w:r>"#
        );
        true
    }

    fn list(&mut self, element: &HtmlElement, format: &Format) {
        self.flush();
        let plain = css(element).contains("list-style-type:none");
        let number = if plain {
            None
        } else if &*name(element) == "ol" {
            let start = attribute(element, "start")
                .and_then(|start| start.parse().ok())
                .unwrap_or(1);
            self.numbers.push(start);
            Some(self.numbers.len() + 1)
        } else {
            Some(1)
        };
        self.lists.push(List { number, text: None });
        self.nodes(&element.children, format);
        self.flush();
        self.lists.pop();
    }

    fn table(&mut self, element: &HtmlElement, format: &Format) {
        self.flush();
        let mut rows: Vec<(&HtmlElement, bool)> = Vec::new();
        for node in &element.children {
            let HtmlNode::Element(child) = node else {
                continue;
            };
            match &*name(child) {
                "tr" => rows.push((child, false)),
                group @ ("thead" | "tbody" | "tfoot") => rows.extend(
                    child
                        .children
                        .iter()
                        .filter_map(|node| match node {
                            HtmlNode::Element(row) if &*name(row) == "tr" => Some(row),
                            _ => None,
                        })
                        .map(|row| (row, group == "thead")),
                ),
                _ => {}
            }
        }
        let span = |cell: &HtmlElement, key: &str| {
            attribute(cell, key)
                .and_then(|span| span.parse::<usize>().ok())
                .unwrap_or(1)
                .max(1)
        };
        let columns = rows
            .iter()
            .map(|(row, _)| cells(row).iter().map(|cell| span(cell, "colspan")).sum())
            .max()
            .unwrap_or(1)
            .max(1);

        // Write every cell first: where their text sits on the page gives the columns.
        let outer = std::mem::take(&mut self.out);
        let previous = self.previous.take();
        let mut written: Vec<Cell> = Vec::new();
        let mut covered = vec![0_usize; columns];
        for (row_index, (row, _)) in rows.iter().enumerate() {
            let mut at = 0;
            for cell in cells(row) {
                while at < columns && covered[at] > 0 {
                    at += 1;
                }
                if at >= columns {
                    break;
                }
                let wide = span(cell, "colspan").min(columns - at);
                let tall = span(cell, "rowspan");
                covered[at..at + wide].fill(tall);
                let mut inside = format.clone();
                inside.bold |= &*name(cell) == "th";
                self.cell = Some(Vec::new());
                self.previous = None;
                self.nodes(&cell.children, &inside);
                self.flush();
                let found = self.cell.take().unwrap_or_default();
                let content: String = std::mem::take(&mut self.out)
                    .into_iter()
                    .map(|out| out.xml)
                    .collect();
                written.push(Cell {
                    row: row_index,
                    column: at,
                    wide,
                    tall,
                    content,
                    found,
                });
                at += wide;
            }
            for count in &mut covered {
                *count = count.saturating_sub(1);
            }
        }
        self.out = outer;
        self.previous = previous;

        let paged = self.paged;
        let first = written
            .iter()
            .find_map(|cell| cell.found.first().copied())
            .map(|found| &paged.occurrences[found]);
        let page = first.map(|first| first.page);
        let region = page.map_or_else(
            || Rect::new(Point::zero(), Point::with_x(Abs::pt(self.room))),
            |page| self.region(page),
        );
        let fill_of = |cell: &Cell| {
            let found = &paged.occurrences[*cell.found.first()?];
            self.fill_at(
                found.page,
                Point::new(Abs::pt(found.x + 0.5), Abs::pt(found.baseline - 1.0)),
            )
        };
        // Columns: from the cells' backgrounds, or else from where their text starts.
        let mut lefts: Vec<Option<f64>> = vec![None; columns + 1];
        let mut padding: Option<(f64, f64, f64)> = None;
        for cell in written.iter().filter(|cell| cell.wide == 1) {
            if let Some(fill) = fill_of(cell) {
                let (left, right) = (fill.rect.min.x.to_pt(), fill.rect.max.x.to_pt());
                lefts[cell.column] =
                    Some(lefts[cell.column].map_or(left, |known: f64| known.min(left)));
                lefts[cell.column + 1] =
                    Some(lefts[cell.column + 1].map_or(right, |known: f64| known.max(right)));
                if padding.is_none()
                    && let Some(found) = cell.found.first().map(|&found| &paged.occurrences[found])
                {
                    // Word puts the cell's one line of `line` height between these margins, with its
                    // baseline where Typst has it.
                    let line = found.look.size * self.leading;
                    padding = Some((
                        found.x - left,
                        found.baseline - fill.rect.min.y.to_pt() - BASELINE * line,
                        fill.rect.max.y.to_pt() - found.baseline - (1.0 - BASELINE) * line,
                    ));
                }
            }
        }
        let inset = padding.map_or(5.0, |(side, _, _)| side.clamp(0.0, 30.0));
        for cell in written.iter().filter(|cell| cell.wide == 1) {
            if lefts[cell.column].is_none()
                && let Some(left) = cell
                    .found
                    .iter()
                    .map(|&found| paged.occurrences[found].x)
                    .reduce(f64::min)
            {
                lefts[cell.column] = Some(left - inset);
            }
        }
        if lefts[columns].is_none() {
            let right = written
                .iter()
                .flat_map(|cell| cell.found.iter())
                .map(|&found| paged.occurrences[found].right + inset)
                .fold(f64::MIN, f64::max)
                .min(region.max.x.to_pt());
            lefts[columns] = Some(right);
        }
        let start = lefts[0].unwrap_or(region.min.x.to_pt());
        lefts[0] = Some(start);
        let total = lefts[columns].unwrap_or(region.max.x.to_pt()) - start;
        let mut widths = Vec::with_capacity(columns);
        let mut known = start;
        for column in 0..columns {
            let next = (column + 1..=columns).find_map(|index| lefts[index]);
            let missing = (column + 1..=columns)
                .take_while(|index| lefts[*index].is_none())
                .count();
            let width = next.map_or(total / columns as f64, |next| {
                (next - known) / (missing + 1) as f64
            });
            widths.push(width.max(12.0));
            known += width;
        }

        // Lines: Typst draws them as separate strokes; Word wants borders.
        let area = Rect::new(
            Point::new(Abs::pt(start - 1.0), Abs::pt(f64::MIN)),
            Point::new(Abs::pt(start + total + 1.0), Abs::pt(f64::MAX)),
        );
        let strokes: Vec<&paged::Stroke> = page
            .map(|page| {
                let rows: Vec<f64> = written
                    .iter()
                    .flat_map(|cell| cell.found.iter())
                    .map(|&found| paged.occurrences[found].baseline)
                    .collect();
                let (top, bottom) = rows
                    .iter()
                    .fold((f64::MAX, f64::MIN), |(top, bottom), row| {
                        (top.min(*row), bottom.max(*row))
                    });
                paged.sheets[page]
                    .strokes
                    .iter()
                    .filter(|stroke| {
                        stroke.rect.max.x > area.min.x
                            && stroke.rect.min.x < area.max.x
                            && stroke.rect.max.y.to_pt() >= top - 40.0
                            && stroke.rect.min.y.to_pt() <= bottom + 40.0
                    })
                    .collect()
            })
            .unwrap_or_default();
        let border = |vertical: bool| {
            strokes
                .iter()
                .find(|stroke| {
                    let (width, height) = (
                        (stroke.rect.max.x - stroke.rect.min.x).to_pt(),
                        (stroke.rect.max.y - stroke.rect.min.y).to_pt(),
                    );
                    if vertical {
                        height > width
                    } else {
                        width >= height
                    }
                })
                .map_or_else(
                    || r#"w:val="nil""#.to_string(),
                    |stroke| {
                        format!(
                            r#"w:val="single" w:sz="{}" w:space="0" w:color="{}""#,
                            (stroke.thickness * 8.0).round().clamp(2.0, 96.0) as i64,
                            colour(stroke.colour)
                        )
                    },
                )
        };
        let (across, down) = (border(false), border(true));
        let (_, top, bottom) = padding.unwrap_or((inset, 2.0, 2.0));
        // Typst fits a line to its last hundredth of a point; Word measures a little wider. Room
        // on the right keeps a line that just fits in Typst from wrapping in Word.
        let trailing = inset / 3.0;
        let mut xml = format!(
            r#"<w:tbl><w:tblPr><w:tblStyle w:val="TableGrid"/><w:tblW w:w="{}" w:type="dxa"/><w:tblInd w:w="{}" w:type="dxa"/><w:tblBorders><w:top {across}/><w:left {down}/><w:bottom {across}/><w:right {down}/><w:insideH {across}/><w:insideV {down}/></w:tblBorders><w:tblLayout w:type="fixed"/><w:tblCellMar><w:top w:w="{}" w:type="dxa"/><w:left w:w="{}" w:type="dxa"/><w:bottom w:w="{}" w:type="dxa"/><w:right w:w="{}" w:type="dxa"/></w:tblCellMar><w:tblLook w:val="04A0" w:firstRow="1" w:lastRow="0" w:firstColumn="0" w:lastColumn="0" w:noHBand="0" w:noVBand="1"/></w:tblPr><w:tblGrid>"#,
            twips(total),
            twips(start - region.min.x.to_pt()),
            twips(top.clamp(0.0, 30.0)),
            twips(inset),
            twips(bottom.clamp(0.0, 30.0)),
            twips(trailing),
        );
        for width in &widths {
            let _ = write!(xml, r#"<w:gridCol w:w="{}"/>"#, twips(*width));
        }
        xml.push_str("</w:tblGrid>");
        // A row's baseline, for finding the background of a cell without text.
        let baselines: HashMap<usize, f64> = written
            .iter()
            .filter_map(|cell| Some((cell.row, paged.occurrences[*cell.found.first()?].baseline)))
            .collect();
        for (row, (_, header)) in rows.iter().enumerate() {
            xml.push_str("<w:tr>");
            if *header {
                xml.push_str("<w:trPr><w:tblHeader/></w:trPr>");
            }
            let mut column = 0;
            for cell in written.iter().filter(|cell| cell.row == row) {
                // Cells covered from a row above.
                while column < cell.column {
                    let _ = write!(
                        xml,
                        r#"<w:tc><w:tcPr><w:tcW w:w="{}" w:type="dxa"/><w:vMerge/></w:tcPr><w:p/></w:tc>"#,
                        twips(widths[column])
                    );
                    column += 1;
                }
                let width: f64 = widths[cell.column..cell.column + cell.wide].iter().sum();
                // Typst aligns a cell's text within the cell; Word wants that on the paragraph.
                let cell_left = start + widths[..cell.column].iter().sum::<f64>();
                let reach = cell
                    .found
                    .iter()
                    .map(|&found| &paged.occurrences[found])
                    .fold((f64::MAX, f64::MIN), |(left, right), found| {
                        (left.min(found.x), right.max(found.right))
                    });
                let align = if reach.0 > reach.1 {
                    None
                } else if ((reach.0 + reach.1) / 2.0 - (cell_left + width / 2.0)).abs() < 1.5
                    && reach.0 > cell_left + inset + 1.0
                {
                    Some("center")
                } else if (cell_left + width - inset - reach.1).abs() < 1.5
                    && reach.0 > cell_left + inset + 1.0
                {
                    Some("right")
                } else {
                    None
                };
                let content = match align {
                    Some(align) => cell
                        .content
                        .replace(r#"<w:jc w:val="center"/>"#, "")
                        .replace(r#"<w:jc w:val="right"/>"#, "")
                        .replace("</w:pPr>", &format!(r#"<w:jc w:val="{align}"/></w:pPr>"#)),
                    None => cell.content.clone(),
                };
                let fill = fill_of(cell).or_else(|| {
                    let page = page?;
                    let middle = lefts[cell.column]? + widths[cell.column] / 2.0;
                    self.fill_at(
                        page,
                        Point::new(Abs::pt(middle), Abs::pt(*baselines.get(&cell.row)? - 1.0)),
                    )
                });
                let shading = fill.map_or_else(String::new, |fill| {
                    format!(
                        r#"<w:shd w:val="clear" w:color="auto" w:fill="{}"/>"#,
                        colour(fill.colour)
                    )
                });
                let _ = write!(
                    xml,
                    r#"<w:tc><w:tcPr><w:tcW w:w="{}" w:type="dxa"/>{}{}{shading}</w:tcPr>{}</w:tc>"#,
                    twips(width),
                    if cell.wide > 1 {
                        format!(r#"<w:gridSpan w:val="{}"/>"#, cell.wide)
                    } else {
                        String::new()
                    },
                    if cell.tall > 1 {
                        r#"<w:vMerge w:val="restart"/>"#
                    } else {
                        ""
                    },
                    if content.is_empty() {
                        "<w:p/>"
                    } else {
                        &content
                    },
                );
                column = cell.column + cell.wide;
            }
            xml.push_str("</w:tr>");
        }
        xml.push_str("</w:tbl>");
        // Word has no space above a table: the paragraph before it takes Typst's gap below itself.
        let table_top = page.and_then(|page| {
            written
                .iter()
                .filter(|cell| cell.row == 0)
                .filter_map(|cell| fill_of(cell).map(|fill| fill.rect.min.y.to_pt()))
                .reduce(f64::min)
                .or_else(|| {
                    let found = &paged.occurrences[*written.first()?.found.first()?];
                    (found.page == page).then_some(found.baseline - found.ascent - top)
                })
        });
        if let (Some(table_top), Some((line, height))) = (table_top, previous)
            && Some(line.page) == page
            && let Some(before) = self.out.last_mut()
            && before.xml.starts_with("<w:p><w:pPr>")
        {
            let gap = table_top - line.baseline - (1.0 - BASELINE) * height;
            if gap > 0.5 {
                before.xml = before.xml.replacen(
                    r#"w:after="0""#,
                    &format!(r#"w:after="{}""#, twips(gap.min(200.0))),
                    1,
                );
            }
        }
        self.push(xml, page);
        // The text after the table is spaced from the table's bottom.
        let last = written
            .iter()
            .flat_map(|cell| cell.found.iter())
            .map(|&found| &paged.occurrences[found])
            .filter(|found| Some(found.page) == page)
            .max_by(|a, b| a.baseline.total_cmp(&b.baseline));
        if let Some(last) = last {
            let height = last.look.size * self.leading;
            let line = Line {
                page: last.page,
                baseline: last.baseline + (1.0 - BASELINE) * height + bottom.clamp(0.0, 30.0),
                left: last.x,
                right: last.right,
                size: last.look.size,
            };
            self.previous = Some((line, 0.0));
        }
    }

    fn element(&mut self, element: &HtmlElement, format: &Format) {
        let mut inner = format.clone();
        match &*name(element) {
            "head" | "style" | "script" | "meta" | "title" | "img" => {}
            "section"
                if attribute(element, "role") == Some("doc-endnotes") && !self.notes.is_empty() => {
            }
            "p" | "div" | "section" | "article" | "main" | "header" | "footer" | "aside"
            | "nav" | "address" | "body" | "html" => {
                let level = attribute(element, "aria-level")
                    .filter(|_| attribute(element, "role") == Some("heading"))
                    .and_then(|level| level.parse::<usize>().ok());
                if let Some(id) = attribute(element, "id") {
                    self.flush();
                    self.bookmarks.push(bookmark(id));
                }
                let outline = attribute(element, "role") == Some("doc-toc");
                self.outline |= outline;
                self.block(
                    level.map(|level| Role::Heading(level.saturating_sub(1).clamp(1, 6))),
                    element,
                    format,
                );
                if outline {
                    self.outline = false;
                }
            }
            heading @ ("h1" | "h2" | "h3" | "h4" | "h5" | "h6") => {
                let level = heading[1..].parse::<usize>().unwrap_or(2) - 1;
                if let Some(id) = attribute(element, "id") {
                    self.flush();
                    self.bookmarks.push(bookmark(id));
                }
                self.block(Some(Role::Heading(level)), element, format);
            }
            "figure" => {
                // Content HTML has no form for (a diagram drawn with `layout`) comes out empty:
                // the figure is then taken from the page as a picture.
                let key = self.figure.take();
                let shown = element.children.iter().any(|node| match node {
                    HtmlNode::Element(child) if &*name(child) == "figcaption" => false,
                    other => holds(std::slice::from_ref(other)),
                });
                if !shown && let Some(key) = key {
                    self.flush();
                    self.drawing_of_figure(key);
                }
                self.block(Some(Role::Figure), element, format)
            }
            "figcaption" => self.block(Some(Role::Caption), element, format),
            "blockquote" => self.block(Some(Role::Quote), element, format),
            "pre" => self.block(Some(Role::Code), element, format),
            // Typst sets a term and its description on one line.
            "dt" => {
                self.flush();
                inner.bold = true;
                self.nodes(&element.children, &inner);
            }
            "dd" => {
                self.nodes(&element.children, format);
                self.flush();
            }
            "dl" => self.block(None, element, format),
            "ul" | "ol" | "menu" => self.list(element, format),
            "li" => {
                self.flush();
                if let Some(id) = attribute(element, "id") {
                    self.bookmarks.push(bookmark(id));
                }
                self.item = true;
                self.nodes(&element.children, format);
                self.flush();
                self.item = false;
            }
            "table" => self.table(element, format),
            "hr" => {
                self.flush();
                if let Some(id) = attribute(element, "id") {
                    self.bookmarks.push(bookmark(id));
                }
                if attribute(element, "class") == Some(PAGE_BREAK) {
                    self.out.push(Out {
                        xml: r#"<w:p><w:r><w:br w:type="page"/></w:r></w:p>"#.into(),
                        page: None,
                        page_break: true,
                    });
                    self.previous = None;
                } else {
                    self.push(
                        r#"<w:p><w:pPr><w:pBdr><w:bottom w:val="single" w:sz="6" w:space="1" w:color="auto"/></w:pBdr></w:pPr></w:p>"#.into(),
                        None,
                    );
                }
            }
            "br" => {
                let properties = self.run_properties(self.look.clone().as_ref(), format, 0.0);
                let _ = write!(self.runs, "<w:r>{properties}<w:br/></w:r>");
            }
            "math" => {
                let start = self.found.len();
                let mut spans = HashSet::new();
                self::spans(&element.children, &mut spans);
                if let Some(span) = first_span(&element.children) {
                    self.find(span, "");
                }
                let look = self
                    .found
                    .get(start)
                    .map(|&found| self.paged.occurrences[found].look.clone());
                let run = match look.as_ref().or(self.look.as_ref()) {
                    Some(look) => format!(
                        r#"<w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/><w:color w:val="{}"/><w:sz w:val="{1}"/><w:szCs w:val="{1}"/></w:rPr>"#,
                        colour(look.colour),
                        (look.size * 2.0).round() as i64
                    ),
                    None => r#"<w:rPr><w:rFonts w:ascii="Cambria Math" w:hAnsi="Cambria Math"/></w:rPr>"#.into(),
                };
                let omml = math::omml(element, &run);
                if attribute(element, "display") == Some("block") {
                    let found = self.found.split_off(start);
                    self.flush();
                    self.found = found;
                    self.tall = true;
                    self.centre = true;
                    let geometry = self.geometry();
                    let properties = self.properties(geometry.as_ref());
                    self.centre = false;
                    let marks = self.marks();
                    let page = geometry.map(|geometry| geometry.first().page);
                    self.push(
                        format!("<w:p>{properties}{marks}<m:oMathPara>{omml}</m:oMathPara></w:p>"),
                        page,
                    );
                    self.found.clear();
                    self.tall = false;
                } else {
                    self.tall = true;
                    // An empty run first, so a paragraph that opens with a formula is not skipped.
                    self.runs.push_str("<w:r/>");
                    self.runs.push_str(&omml);
                    self.previous_run = None;
                    self.spaced = false;
                }
            }
            "a" => {
                inner.link = true;
                let start = self.runs.len();
                let target = attribute(element, "href").unwrap_or_default();
                if self.outline
                    && let Some(anchor) = target.strip_prefix('#')
                {
                    self.target = Some(anchor.to_string());
                }
                self.nodes(&element.children, &inner);
                let content = self.runs.split_off(start.min(self.runs.len()));
                let opening = match target.strip_prefix('#') {
                    Some(anchor) => format!(r#"<w:hyperlink w:anchor="{}">"#, bookmark(anchor)),
                    None if !target.is_empty() => {
                        format!(
                            r#"<w:hyperlink r:id="{}">"#,
                            link(&mut self.links, "hyperlink", target.to_string())
                        )
                    }
                    None => String::new(),
                };
                if opening.is_empty() {
                    self.runs.push_str(&content);
                } else {
                    let _ = write!(self.runs, "{opening}{content}</w:hyperlink>");
                }
            }
            "sup" if attribute(element, "role") == Some("doc-noteref") => {
                let mut links = Vec::new();
                collect(&element.children, "a", &mut links);
                let id = links
                    .first()
                    .and_then(|link| attribute(link, "href"))
                    .and_then(|href| href.strip_prefix('#'))
                    .map(str::to_string);
                if !id.is_some_and(|id| self.footnote(&id)) {
                    inner.script = Some("superscript");
                    self.nodes(&element.children, &inner);
                }
            }
            other => {
                let css = css(element);
                match other {
                    "strong" | "b" => inner.bold = true,
                    "em" | "i" | "cite" | "dfn" | "var" => inner.italic = true,
                    "u" | "ins" => inner.underline = true,
                    "s" | "del" | "strike" => inner.strike = true,
                    "sub" => inner.script = Some("subscript"),
                    "sup" => inner.script = Some("superscript"),
                    "code" | "kbd" | "samp" => inner.code = true,
                    "mark" => inner.highlight = true,
                    _ => {}
                }
                inner.underline |= css.contains("text-decoration:underline");
                inner.strike |= css.contains("text-decoration:line-through");
                inner.small_caps |= css.contains("small-caps");
                if let Some(colour) = css
                    .split(';')
                    .find_map(|rule| rule.strip_prefix("color:#"))
                    .filter(|colour| colour.len() >= 6)
                {
                    inner.colour = Some(colour[..6].to_ascii_uppercase());
                }
                if css.contains("display:block") {
                    self.block(None, element, &inner);
                } else {
                    self.nodes(&element.children, &inner);
                }
            }
        }
    }
}

/// The look most of the body text has.
fn body_look(paged: &Paged) -> Option<Look> {
    // Per family, size, weight, slant and colour: how wide its text runs, and one example.
    type Kind = (String, i64, bool, bool, [u8; 3]);
    let mut counts: HashMap<Kind, (f64, usize)> = HashMap::new();
    for (index, occurrence) in paged.occurrences.iter().enumerate() {
        if occurrence.chrome || paged.sheets[occurrence.page].designed {
            continue;
        }
        let look = &occurrence.look;
        let key = (
            look.family.clone(),
            (look.size * 10.0).round() as i64,
            look.bold,
            look.italic,
            look.colour,
        );
        let entry = counts.entry(key).or_insert((0.0, index));
        entry.0 += occurrence.right - occurrence.x;
    }
    counts
        .into_values()
        .max_by(|a, b| a.0.total_cmp(&b.0))
        .map(|(_, index)| paged.occurrences[index].look.clone())
}

/// Baseline distance over font size, for paragraphs of one line.
fn leading(paged: &Paged) -> f64 {
    let mut ratios: Vec<f64> = Vec::new();
    for block in &paged.blocks {
        let mut baselines: Vec<(usize, f64, f64)> = block
            .occurrences
            .iter()
            .map(|&index| &paged.occurrences[index])
            .filter(|occurrence| !occurrence.chrome)
            .map(|occurrence| (occurrence.page, occurrence.baseline, occurrence.look.size))
            .collect();
        baselines.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.total_cmp(&b.1)));
        baselines.dedup_by(|a, b| a.0 == b.0 && (a.1 - b.1).abs() < 0.5);
        ratios.extend(
            baselines
                .windows(2)
                .filter(|pair| pair[0].0 == pair[1].0 && pair[1].1 > pair[0].1)
                .map(|pair| (pair[1].1 - pair[0].1) / pair[0].2),
        );
    }
    ratios.sort_by(f64::total_cmp);
    ratios
        .get(ratios.len() / 2)
        .copied()
        .unwrap_or(1.3)
        .clamp(1.0, 2.5)
}

fn styles(body: Option<&Look>, headings: &[Option<Look>; 7], language: &str) -> String {
    let properties = |look: &Look| {
        drawing::run_properties(&look.family, look.size, look.bold, look.italic, look.colour)
    };
    // Kerning on, as Typst does; Word leaves it off unless asked.
    let defaults = body
        .map(properties)
        .unwrap_or_default()
        .replace("<w:sz ", r#"<w:kern w:val="2"/><w:sz "#);
    let mut xml = format!(
        r#"{XML}<w:styles xmlns:w="{MAIN}"><w:docDefaults><w:rPrDefault><w:rPr>{defaults}<w:lang w:val="{}"/></w:rPr></w:rPrDefault><w:pPrDefault><w:pPr><w:spacing w:after="0" w:line="264" w:lineRule="auto"/></w:pPr></w:pPrDefault></w:docDefaults><w:style w:type="paragraph" w:default="1" w:styleId="Normal"><w:name w:val="Normal"/><w:qFormat/></w:style>"#,
        escape(language)
    );
    for (level, look) in headings.iter().enumerate() {
        let (id, name) = if level == 0 {
            ("Title".to_string(), "Title".to_string())
        } else {
            (format!("Heading{level}"), format!("heading {level}"))
        };
        let outline = if level == 0 {
            String::new()
        } else {
            format!(r#"<w:outlineLvl w:val="{}"/>"#, level - 1)
        };
        let font = match (look, body) {
            (Some(look), _) => properties(look),
            (None, Some(body)) => drawing::run_properties(
                &body.family,
                body.size * [2.0, 1.6, 1.35, 1.2, 1.1, 1.0, 1.0][level],
                true,
                false,
                body.colour,
            ),
            _ => String::new(),
        };
        let _ = write!(
            xml,
            r#"<w:style w:type="paragraph" w:styleId="{id}"><w:name w:val="{name}"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:uiPriority w:val="{}"/><w:qFormat/><w:pPr><w:keepNext/><w:keepLines/>{outline}</w:pPr><w:rPr>{font}</w:rPr></w:style>"#,
            if level == 0 { 10 } else { 9 },
        );
    }
    xml.push_str(r#"<w:style w:type="paragraph" w:styleId="Caption"><w:name w:val="caption"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/></w:style><w:style w:type="paragraph" w:styleId="Quote"><w:name w:val="Quote"/><w:basedOn w:val="Normal"/><w:next w:val="Normal"/><w:qFormat/></w:style><w:style w:type="paragraph" w:styleId="SourceCode"><w:name w:val="Source Code"/><w:basedOn w:val="Normal"/></w:style><w:style w:type="paragraph" w:styleId="ListParagraph"><w:name w:val="List Paragraph"/><w:basedOn w:val="Normal"/><w:uiPriority w:val="34"/><w:qFormat/></w:style><w:style w:type="paragraph" w:styleId="FootnoteText"><w:name w:val="footnote text"/><w:basedOn w:val="Normal"/></w:style><w:style w:type="character" w:styleId="FootnoteReference"><w:name w:val="footnote reference"/><w:rPr><w:vertAlign w:val="superscript"/></w:rPr></w:style><w:style w:type="character" w:styleId="VerbatimChar"><w:name w:val="Verbatim Char"/><w:rPr><w:rFonts w:ascii="Consolas" w:hAnsi="Consolas"/></w:rPr></w:style><w:style w:type="character" w:styleId="Hyperlink"><w:name w:val="Hyperlink"/><w:rPr><w:color w:val="0563C1"/><w:u w:val="single"/></w:rPr></w:style><w:style w:type="table" w:styleId="TableGrid"><w:name w:val="Table Grid"/><w:pPr><w:spacing w:after="0"/></w:pPr></w:style></w:styles>"#);
    xml
}

fn numbering(starts: &[usize]) -> String {
    let level = |kind: &str, level: usize, text: String| {
        format!(
            r#"<w:lvl w:ilvl="{level}"><w:start w:val="1"/><w:numFmt w:val="{kind}"/><w:lvlText w:val="{text}"/><w:lvlJc w:val="left"/><w:pPr><w:ind w:left="{}" w:hanging="360"/></w:pPr></w:lvl>"#,
            720 * (level + 1)
        )
    };
    // Typst's own markers.
    let bullets: String = (0..9)
        .map(|depth| level("bullet", depth, ["•", "‣", "–"][depth % 3].to_string()))
        .collect();
    let numbers: String = (0..9)
        .map(|depth| level("decimal", depth, format!("%{}.", depth + 1)))
        .collect();
    let mut xml = format!(
        r#"{XML}<w:numbering xmlns:w="{MAIN}"><w:abstractNum w:abstractNumId="0"><w:multiLevelType w:val="hybridMultilevel"/>{bullets}</w:abstractNum><w:abstractNum w:abstractNumId="1"><w:multiLevelType w:val="hybridMultilevel"/>{numbers}</w:abstractNum><w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>"#
    );
    // Each ordered list counts from its own start, at whatever depth it sits.
    for (index, start) in starts.iter().enumerate() {
        let overrides: String = (0..9)
            .map(|depth| {
                format!(
                    r#"<w:lvlOverride w:ilvl="{depth}"><w:startOverride w:val="{start}"/></w:lvlOverride>"#
                )
            })
            .collect();
        let _ = write!(
            xml,
            r#"<w:num w:numId="{}"><w:abstractNumId w:val="1"/>{overrides}</w:num>"#,
            index + 2
        );
    }
    xml.push_str("</w:numbering>");
    xml
}

/// A run of pages Word shows with one header (or one designed page).
struct Section {
    pages: Vec<usize>,
    designed: bool,
}

/// The header, footer and background of a page, without its body.
struct Chrome {
    background: typst_layout::Page,
    layers: Layers,
}

fn chrome(document: &PagedDocument, paged: &Paged, index: usize) -> Result<Chrome, String> {
    let page = paged.chrome(&document.pages()[index], index);
    let (background, layers) = layers(&page, &Equations::new())?;
    Ok(Chrome { background, layers })
}

/// What tells one page's header apart from another's: the picture and the text, numbers aside.
fn signature(chrome: &Chrome) -> u128 {
    let texts: Vec<String> = chrome
        .layers
        .runs
        .iter()
        .map(|run| {
            run.text
                .chars()
                .map(|c| if c.is_ascii_digit() { '#' } else { c })
                .collect()
        })
        .collect();
    let mut page = chrome.background.clone();
    if page.fill == typst::foundations::Smart::Auto {
        page.fill = typst::foundations::Smart::Custom(None);
    }
    let pixels = typst_render::render(&page, &typst_render::RenderOptions::default());
    hash128(&(pixels.data(), texts))
}

/// Which numbers in the header of `section` are page numbers: those that differ from the next
/// page's in step with the page number.
fn fields(
    first: &Chrome,
    second: Option<&Chrome>,
    numbers: (u64, Option<u64>),
    pages: usize,
    total: usize,
) -> Vec<Vec<Option<Field>>> {
    let (Some(second), (number, Some(next))) = (second, numbers) else {
        return Vec::new();
    };
    let ours = paragraphs(lines(first.layers.runs.clone()));
    let theirs = paragraphs(lines(second.layers.runs.clone()));
    if ours.len() != theirs.len() {
        return Vec::new();
    }
    ours.iter()
        .zip(&theirs)
        .map(|(ours, theirs)| {
            let (a, b) = (drawing::numbers(ours), drawing::numbers(theirs));
            if a.len() != b.len() {
                return Vec::new();
            }
            let mut fields: Vec<Option<Field>> = a
                .iter()
                .zip(&b)
                .map(|(a, b)| {
                    (*a == number.to_string() && *b == next.to_string()).then_some(Field::Page)
                })
                .collect();
            if fields.contains(&Some(Field::Page)) {
                for (field, (a, b)) in fields.iter_mut().zip(a.iter().zip(&b)) {
                    if field.is_none() && a == b {
                        if *a == pages.to_string() {
                            *field = Some(Field::SectionPages);
                        } else if *a == total.to_string() {
                            *field = Some(Field::Pages);
                        }
                    }
                }
            }
            fields
        })
        .collect()
}

fn header(content: &str) -> String {
    format!(
        r#"{XML}<w:hdr {}><w:p>{TINY}{content}</w:p></w:hdr>"#,
        namespaces()
    )
}

fn section_properties(sheet: &paged::Sheet, designed: bool, header: &str) -> String {
    let orientation = if sheet.width > sheet.height {
        r#" w:orient="landscape""#
    } else {
        ""
    };
    let (top, right, bottom, left) = match sheet.body.filter(|_| !designed) {
        Some(body) => (
            body.min.y.to_pt(),
            sheet.width - body.max.x.to_pt(),
            sheet.height - body.max.y.to_pt(),
            body.min.x.to_pt(),
        ),
        None => (0.0, 0.0, 0.0, 0.0),
    };
    format!(
        r#"<w:sectPr><w:headerReference w:type="default" r:id="{header}"/><w:type w:val="nextPage"/><w:pgSz w:w="{}" w:h="{}"{orientation}/><w:pgMar w:top="{}" w:right="{}" w:bottom="{}" w:left="{}" w:header="0" w:footer="0" w:gutter="0"/><w:pgNumType w:start="{}"/></w:sectPr>"#,
        twips(sheet.width),
        twips(sheet.height),
        twips(top),
        twips(right),
        twips(bottom),
        twips(left),
        sheet.number,
    )
}

/// Ends a section in its last paragraph, or in one of its own after a table.
fn close(blocks: &mut Vec<String>, properties: &str) {
    match blocks.last_mut() {
        Some(last) if last.starts_with("<w:p><w:pPr>") => {
            let end = last.find("</w:pPr>").unwrap_or(last.len());
            last.insert_str(end, properties);
        }
        _ => blocks.push(format!(
            r#"<w:p><w:pPr><w:spacing w:before="0" w:after="0" w:line="20" w:lineRule="exact"/>{properties}</w:pPr></w:p>"#
        )),
    }
}

fn content_types(headers: usize, footnotes: bool) -> String {
    let mut xml = format!(
        r#"{XML}<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types"><Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/><Default Extension="xml" ContentType="application/xml"/><Default Extension="png" ContentType="image/png"/><Default Extension="jpg" ContentType="image/jpeg"/><Default Extension="gif" ContentType="image/gif"/><Default Extension="odttf" ContentType="application/vnd.openxmlformats-officedocument.obfuscatedFont"/><Override PartName="/word/document.xml" ContentType="{WORD}.document.main+xml"/><Override PartName="/word/styles.xml" ContentType="{WORD}.styles+xml"/><Override PartName="/word/numbering.xml" ContentType="{WORD}.numbering+xml"/><Override PartName="/word/settings.xml" ContentType="{WORD}.settings+xml"/><Override PartName="/word/fontTable.xml" ContentType="{WORD}.fontTable+xml"/>"#
    );
    for number in 1..=headers {
        let _ = write!(
            xml,
            r#"<Override PartName="/word/header{number}.xml" ContentType="{WORD}.header+xml"/>"#
        );
    }
    if footnotes {
        let _ = write!(
            xml,
            r#"<Override PartName="/word/footnotes.xml" ContentType="{WORD}.footnotes+xml"/>"#
        );
    }
    xml.push_str("</Types>");
    xml
}

/// Hyphenation on when Typst justified text, as it then hyphenates too.
fn settings(hyphenate: bool, footnotes: bool) -> String {
    let hyphenation = if hyphenate {
        "<w:autoHyphenation/>"
    } else {
        ""
    };
    let notes = if footnotes {
        r#"<w:footnotePr><w:footnote w:id="-1"/><w:footnote w:id="0"/></w:footnotePr>"#
    } else {
        ""
    };
    format!(
        r#"{XML}<w:settings xmlns:w="{MAIN}"><w:embedTrueTypeFonts/>{hyphenation}{notes}<w:compat><w:compatSetting w:name="compatibilityMode" w:uri="http://schemas.microsoft.com/office/word" w:val="15"/></w:compat></w:settings>"#
    )
}

pub fn docx(
    document: &PagedDocument,
    html: &HtmlDocument,
    equations: &Equations,
) -> Result<Vec<u8>, String> {
    let failed = |error: zip::result::ZipError| format!("The Word file could not be made: {error}");
    let mut found = HashSet::new();
    spans(&html.root().children, &mut found);
    let paged = Paged::new(document, &found);
    if paged.sheets.is_empty() {
        return Err("This page has nothing to export.".into());
    }
    let mut targets_found = HashMap::new();
    targets(
        &html.root().children,
        &paged,
        &mut Vec::new(),
        &mut targets_found,
    );
    let room = text_width(document).to_pt();
    let mut parts = Parts {
        media: Vec::new(),
        ids: 0,
        faces: fonts::Faces::new(),
    };
    // Dot leaders: Typst repeats a dot (or a few) between an outline entry and its page.
    let leader = paged
        .blocks
        .iter()
        .filter(|block| block.kind == "entry")
        .any(|block| {
            block
                .occurrences
                .iter()
                .filter(|&&index| paged.occurrences[index].dots)
                .count()
                >= 3
        });
    let mut writer = Writer {
        paged: &paged,
        parts: &mut parts,
        links: vec![
            ("styles", "styles.xml".into()),
            ("numbering", "numbering.xml".into()),
            ("settings", "settings.xml".into()),
            ("fontTable", "fontTable.xml".into()),
        ],
        out: Vec::new(),
        runs: String::new(),
        found: Vec::new(),
        cell: None,
        cursor: 0,
        previous_run: None,
        look: None,
        spaced: false,
        tall: false,
        previous: None,
        leading: leading(&paged),
        roles: Vec::new(),
        headings: Vec::new(),
        heading_looks: Default::default(),
        lists: Vec::new(),
        item: false,
        bookmarks: Vec::new(),
        marks: 0,
        numbers: Vec::new(),
        outline: false,
        target: None,
        targets: targets_found,
        leader,
        room,
        placed: HashMap::new(),
        justified: false,
        partial: None,
        notes: notes(&html.root().children),
        footnotes: Vec::new(),
        note_links: Vec::new(),
        in_note: false,
        centre: false,
        spacing: HashMap::new(),
        drawing: false,
        figure: None,
        figures_seen: HashMap::new(),
        document,
    };
    writer.nodes(&html.root().children, &Format::default());
    writer.flush();
    let Writer {
        mut links,
        out,
        numbers,
        heading_looks,
        justified,
        footnotes,
        note_links,
        ..
    } = writer;
    if !footnotes.is_empty() {
        link(&mut links, "footnotes", "footnotes.xml".into());
    }
    let language = attribute(html.root(), "lang").unwrap_or("en").to_string();

    // Sections: each designed page alone; runs of other pages with the same header together.
    let mut sections: Vec<Section> = Vec::new();
    let mut chromes: HashMap<usize, Chrome> = HashMap::new();
    let mut last_signature = None;
    for (index, sheet) in paged.sheets.iter().enumerate() {
        if sheet.designed {
            sections.push(Section {
                pages: vec![index],
                designed: true,
            });
            last_signature = None;
            continue;
        }
        let page_chrome = chrome(document, &paged, index)?;
        let signature = signature(&page_chrome);
        chromes.insert(index, page_chrome);
        match sections.last_mut() {
            Some(section) if !section.designed && last_signature == Some(signature) => {
                section.pages.push(index)
            }
            _ => sections.push(Section {
                pages: vec![index],
                designed: false,
            }),
        }
        last_signature = Some(signature);
    }
    let mut section_of = vec![0; paged.sheets.len()];
    for (index, section) in sections.iter().enumerate() {
        for &page in &section.pages {
            section_of[page] = index;
        }
    }

    // The body's paragraphs go to the section of their page, in order.
    let mut contents: Vec<Vec<Out>> = (0..sections.len()).map(|_| Vec::new()).collect();
    let mut current = sections
        .iter()
        .position(|section| !section.designed)
        .unwrap_or(0);
    for block in out {
        if let Some(page) = block.page {
            if paged.sheets[page].designed {
                continue;
            }
            current = current.max(section_of[page]);
        }
        contents[current].push(block);
    }

    let mut headers: Vec<(String, Vec<(&'static str, String)>)> = vec![(header(""), Vec::new())];
    let empty = link(&mut links, "header", "header1.xml".into());
    let mut body = String::new();
    let total = paged.sheets.len();
    let shown: Vec<usize> = (0..sections.len())
        .filter(|&index| {
            sections[index].designed || contents[index].iter().any(|block| !block.page_break)
        })
        .collect();
    for (position, &index) in shown.iter().enumerate() {
        let section = &sections[index];
        let first = section.pages[0];
        let sheet = &paged.sheets[first];
        let mut content: Vec<String> = Vec::new();
        let header_link = if section.designed {
            let mut anchors_links = std::mem::take(&mut links);
            let anchors = drawing::copy(
                &document.pages()[first],
                equations,
                &[],
                &mut parts,
                &mut anchors_links,
            )?;
            links = anchors_links;
            content.push(format!("<w:p>{TINY}{anchors}</w:p>"));
            empty.clone()
        } else {
            let blocks = &contents[index];
            // Page breaks only between paragraphs: a section starts on a new page anyway.
            for (at, block) in blocks.iter().enumerate() {
                let inside = blocks[..at].iter().any(|block| !block.page_break)
                    && blocks[at + 1..].iter().any(|block| !block.page_break);
                if !block.page_break || inside {
                    content.push(block.xml.clone());
                }
            }
            let ours = &chromes[&first];
            let next = section.pages.get(1).map(|page| &chromes[page]);
            let numbers = (
                sheet.number,
                section.pages.get(1).map(|page| paged.sheets[*page].number),
            );
            let fields = fields(ours, next, numbers, section.pages.len(), total);
            let mut header_links = Vec::new();
            let chrome = chromes
                .remove(&first)
                .ok_or("The header could not be read.")?;
            let mut background = chrome.background;
            let anchors = drawing::copy_layers(
                &mut background,
                chrome.layers,
                &fields,
                &mut parts,
                &mut header_links,
            )?;
            if anchors.is_empty() {
                empty.clone()
            } else {
                headers.push((header(&anchors), header_links));
                link(&mut links, "header", format!("header{}.xml", headers.len()))
            }
        };
        let properties = section_properties(sheet, section.designed, &header_link);
        if position + 1 == shown.len() {
            body.extend(content);
            body.push_str(&properties);
        } else {
            close(&mut content, &properties);
            body.extend(content);
        }
    }
    if shown.is_empty() {
        let _ = write!(
            body,
            "<w:p/>{}",
            section_properties(&paged.sheets[0], false, &empty)
        );
    }

    let embedded = fonts::embed(&parts.faces);
    let document_xml = format!(
        r#"{XML}<w:document {}><w:body>{body}</w:body></w:document>"#,
        namespaces()
    );
    let mut parts_xml = vec![
        (
            "[Content_Types].xml".to_string(),
            content_types(headers.len(), !footnotes.is_empty()),
        ),
        (
            "_rels/.rels".into(),
            relationships(&[("officeDocument", "word/document.xml".into())]),
        ),
        ("word/document.xml".into(), document_xml),
        (
            "word/styles.xml".into(),
            styles(body_look(&paged).as_ref(), &heading_looks, &language),
        ),
        ("word/numbering.xml".into(), numbering(&numbers)),
        (
            "word/settings.xml".into(),
            settings(justified, !footnotes.is_empty()),
        ),
        ("word/fontTable.xml".into(), embedded.table.clone()),
        (
            "word/_rels/fontTable.xml.rels".into(),
            relationships(&embedded.links),
        ),
        ("word/_rels/document.xml.rels".into(), relationships(&links)),
    ];
    if !footnotes.is_empty() {
        parts_xml.push((
            "word/footnotes.xml".into(),
            format!(
                r#"{XML}<w:footnotes {}><w:footnote w:type="separator" w:id="-1"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:separator/></w:r></w:p></w:footnote><w:footnote w:type="continuationSeparator" w:id="0"><w:p><w:pPr><w:spacing w:after="0" w:line="240" w:lineRule="auto"/></w:pPr><w:r><w:continuationSeparator/></w:r></w:p></w:footnote>{}</w:footnotes>"#,
                namespaces(),
                footnotes.concat()
            ),
        ));
        parts_xml.push((
            "word/_rels/footnotes.xml.rels".into(),
            relationships(&note_links),
        ));
    }
    for (index, (xml, header_links)) in headers.into_iter().enumerate() {
        let number = index + 1;
        parts_xml.push((format!("word/header{number}.xml"), xml));
        parts_xml.push((
            format!("word/_rels/header{number}.xml.rels"),
            relationships(&header_links),
        ));
    }

    let mut zip = ZipWriter::new(Cursor::new(Vec::new()));
    for (name, xml) in parts_xml {
        zip.start_file(name, SimpleFileOptions::default())
            .map_err(failed)?;
        zip.write_all(xml.as_bytes())
            .map_err(|error| failed(error.into()))?;
    }
    for (folder, files) in [("media", &parts.media), ("fonts", &embedded.files)] {
        for (file, bytes) in files {
            zip.start_file(
                format!("word/{folder}/{file}"),
                SimpleFileOptions::default(),
            )
            .map_err(failed)?;
            zip.write_all(bytes).map_err(|error| failed(error.into()))?;
        }
    }
    Ok(zip.finish().map_err(failed)?.into_inner())
}

#[cfg(test)]
mod tests {
    use std::io::Read;

    use typst::layout::Size;
    use zip::ZipArchive;

    use super::*;
    use crate::export::tests::{document, html, part};

    /// The Word file for `source`, with every XML part checked to be well formed.
    fn word(source: &str) -> ZipArchive<Cursor<Vec<u8>>> {
        let (html, _) = html(source);
        let bytes = docx(&document(source), &html, &math::equations(&html)).unwrap();
        let mut archive = ZipArchive::new(Cursor::new(bytes)).unwrap();
        for index in 0..archive.len() {
            let mut file = archive.by_index(index).unwrap();
            let name = file.name().unwrap().to_string();
            if name.ends_with(".xml") || name.ends_with(".rels") {
                let mut text = String::new();
                file.read_to_string(&mut text).unwrap();
                roxmltree::Document::parse(&text).unwrap_or_else(|error| panic!("{name}: {error}"));
            }
        }
        archive
    }

    fn body(archive: &mut ZipArchive<Cursor<Vec<u8>>>) -> String {
        part(archive, "word/document.xml")
    }

    #[test]
    fn structure_becomes_word_structure() {
        let source = "#set page(width: 300pt, height: 400pt, margin: 30pt)\n#set heading(numbering: \"1.\")\n= Known heading\nSome *bold* text with #\"A & B < C\" and #link(\"https://example.com\")[a link].\n\n== Smaller\n- one\n- two\n  + nested\n  + list\n\n#table(columns: 2, table.header[*Name*][*Value*], [a], [b], table.cell(colspan: 2)[wide])";
        let mut archive = word(source);
        let body = body(&mut archive);
        assert!(body.contains(r#"<w:pStyle w:val="Heading1"/>"#), "{body}");
        assert!(body.contains(r#"<w:pStyle w:val="Heading2"/>"#), "{body}");
        assert!(body.contains("A &amp; B &lt; C"), "{body}");
        assert!(body.contains("<w:hyperlink r:id="), "{body}");
        assert!(body.contains(r#"<w:numId w:val="1"/>"#), "{body}");
        assert!(
            body.contains(r#"<w:ilvl w:val="1"/><w:numId w:val="2"/>"#),
            "{body}"
        );
        assert!(
            body.contains("<w:tbl>") && body.contains("<w:tblHeader/>"),
            "{body}"
        );
        assert!(body.contains(r#"<w:gridSpan w:val="2"/>"#), "{body}");
        assert!(
            body.contains(r#"<w:pgSz w:w="6000" w:h="8000"/>"#),
            "{body}"
        );
        assert!(body.contains(r#"w:left="600""#), "{body}");
        let links = part(&mut archive, "word/_rels/document.xml.rels");
        assert!(
            links.contains(r#"Target="https://example.com" TargetMode="External""#),
            "{links}"
        );
    }

    #[test]
    fn text_keeps_the_look_and_place_it_has_on_the_page() {
        let source = "#set text(font: \"DejaVu Sans Mono\", size: 12pt, fill: rgb(\"#123456\"))\n#set par(justify: true)\n= Heading\n#text(fill: rgb(\"#AA0000\"))[Red] text. #lorem(40)\n\n#align(center)[Centred]";
        let mut archive = word(source);
        let body = body(&mut archive);
        assert!(
            body.contains(r#"<w:rFonts w:ascii="DejaVu Sans Mono""#),
            "{body}"
        );
        assert!(body.contains(r#"<w:color w:val="123456"/>"#), "{body}");
        assert!(body.contains(r#"<w:color w:val="AA0000"/>"#), "{body}");
        assert!(body.contains(r#"<w:sz w:val="24"/>"#), "{body}");
        assert!(body.contains(r#"<w:jc w:val="both"/>"#), "{body}");
        assert!(body.contains(r#"<w:jc w:val="center"/>"#), "{body}");
        assert!(body.contains(r#"w:lineRule="exact""#), "{body}");
        // The font travels inside the file, obfuscated as Word wants.
        let table = part(&mut archive, "word/fontTable.xml");
        assert!(
            table.contains(r#"<w:font w:name="DejaVu Sans Mono"><w:embedRegular"#),
            "{table}"
        );
        let mut font = Vec::new();
        archive
            .by_name("word/fonts/font1.odttf")
            .unwrap()
            .read_to_end(&mut font)
            .unwrap();
        assert!(!font.is_empty());
        assert!(part(&mut archive, "word/settings.xml").contains("<w:embedTrueTypeFonts/>"));
    }

    #[test]
    fn header_and_footer_become_the_word_header_with_page_numbers() {
        let source = "#set page(width: 300pt, height: 300pt, header: [Running title], numbering: \"1 of 1\")\n#lorem(150)";
        let mut archive = word(source);
        let header = part(&mut archive, "word/header2.xml");
        assert!(header.contains("Running title"), "{header}");
        assert!(
            header.contains(r#"<w:fldSimple w:instr=" PAGE ">"#),
            "{header}"
        );
        assert!(
            header.contains(r#"<w:fldSimple w:instr=" SECTIONPAGES ">"#),
            "{header}"
        );
        let body = body(&mut archive);
        assert!(!body.contains("Running title"), "{body}");
        assert_eq!(body.matches("<w:sectPr>").count(), 1, "{body}");
        assert!(
            body.contains(r#"<w:headerReference w:type="default" r:id="#),
            "{body}"
        );
    }

    #[test]
    fn a_designed_page_is_copied_and_the_rest_flows() {
        let source = "#page(margin: 0pt)[#block(width: 100%, height: 100%, fill: navy)[#text(fill: white, size: 30pt)[Cover title]]]\n= First chapter\nBody text.";
        let mut archive = word(source);
        let body = body(&mut archive);
        assert_eq!(body.matches("<w:sectPr>").count(), 2, "{body}");
        let end = body.find("</w:sectPr>").unwrap();
        let cover = &body[..end + body[end..].find("</w:p>").unwrap()];
        assert!(
            cover.contains(r#"behindDoc="1""#) && cover.contains("<wps:txbx>"),
            "{cover}"
        );
        assert!(
            cover.contains("Cover title") && !cover.contains("First chapter"),
            "{cover}"
        );
        assert_eq!(body.matches("Cover title").count(), 1, "{body}");
        assert!(body.contains(r#"<w:pStyle w:val="Heading1"/>"#), "{body}");
    }

    #[test]
    fn footnotes_formulas_pictures_and_outlines_are_word_ones() {
        let dot = png(&Frame::soft(Size::splat(Abs::pt(4.0))), 1.0).unwrap();
        std::fs::write(std::env::temp_dir().join("znote-docx-dot.png"), dot).unwrap();
        let source = "#outline()\n= Section\nText.#footnote[The note.] Inline $x^2$ here.\n$ a/b $\n#figure(image(\"znote-docx-dot.png\", width: 50%, alt: \"Dot\"), caption: [A dot])";
        let mut archive = word(source);
        let body = body(&mut archive);
        assert!(
            body.contains(r#"<w:footnoteReference w:id="1"/>"#),
            "{body}"
        );
        assert!(!body.contains("The note."), "{body}");
        assert!(part(&mut archive, "word/footnotes.xml").contains("The note."));
        assert!(body.contains("<w:r/><m:oMath><m:sSup>"), "{body}");
        assert!(body.contains("<m:oMathPara><m:oMath><m:f>"), "{body}");
        assert!(body.contains(r#"descr="Dot""#), "{body}");
        assert!(body.contains(r#"<w:pStyle w:val="Caption"/>"#), "{body}");
        assert!(
            body.contains(r#" PAGEREF _loc_1 \h "#) || body.contains(" PAGEREF _"),
            "{body}"
        );
        let mut picture = Vec::new();
        archive
            .by_name("word/media/image1.png")
            .unwrap()
            .read_to_end(&mut picture)
            .unwrap();
        assert!(picture.starts_with(b"\x89PNG"));
    }

    #[test]
    fn a_figure_html_cannot_show_is_taken_from_the_page_as_a_picture() {
        let source = "Before.\n#figure(layout(size => rect(width: 2cm, height: 1cm, fill: red)), caption: [Measured])\nAfter.";
        let mut archive = word(source);
        let body = body(&mut archive);
        let picture = body.find("<wp:inline").expect(&body);
        assert!(picture < body.find("Measured").unwrap(), "{body}");
        let mut png = Vec::new();
        archive
            .by_name("word/media/image1.png")
            .unwrap()
            .read_to_end(&mut png)
            .unwrap();
        assert!(png.starts_with(b"\x89PNG"));
        // About the size Typst drew it (2 cm wide, 2 pt of room on each side).
        let width = body[picture..]
            .split(r#"cx=""#)
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .and_then(|cx| cx.parse::<f64>().ok())
            .unwrap();
        assert!((width / 12700.0 - (56.69 + 4.0)).abs() < 1.0, "{width}");
    }

    #[test]
    fn a_heading_typst_moved_to_the_next_page_keeps_its_space_above() {
        // The second heading does not fit with the lines it keeps on its page, so Typst starts a
        // page with it, leaving room on the first; Word may keep it there.
        let source = "#set page(width: 300pt, height: 250pt)\n= First\n#lorem(30)\n\n#lorem(25)\n= Second\n#lorem(60)";
        let document = document(source);
        assert_eq!(
            document.pages().len(),
            2,
            "the case needs Typst to move the heading"
        );
        let mut archive = word(source);
        let body = body(&mut archive);
        let before = |heading: &str| {
            let at = body.find(&format!(">{heading}<")).unwrap();
            let paragraph = &body[body[..at].rfind("<w:p>").unwrap()..at];
            paragraph
                .split(r#"w:before=""#)
                .nth(1)
                .and_then(|rest| rest.split('"').next())
                .and_then(|value| value.parse::<i64>().ok())
                .unwrap()
        };
        let paragraph = |text: &str| {
            let at = body.find(text).unwrap();
            body[body[..at].rfind("<w:p>").unwrap()..at].to_string()
        };
        let first_body = paragraph("Lorem ipsum");
        let space = first_body
            .split(r#"w:before=""#)
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .and_then(|value| value.parse::<i64>().ok())
            .unwrap();
        assert!(before("Second") > space, "{body}");
        assert!(before("Second") > 100, "{body}");
    }

    #[test]
    fn layout_keeps_its_content_and_page_breaks_carry_over() {
        let source = "#align(center)[Centred]\n#grid(columns: 2, [Left cell], [Right cell])\n#pad(x: 1cm)[Padded]\n#pagebreak()\nNext page\n#polygon((0pt, 0pt), (1cm, 0pt), (0pt, 1cm))";
        let (html, _) = html(source);
        let bytes = docx(&document(source), &html, &Equations::new()).unwrap();
        let body = part(
            &mut ZipArchive::new(Cursor::new(bytes)).unwrap(),
            "word/document.xml",
        );
        for text in ["Centred", "Left cell", "Right cell", "Padded", "Next page"] {
            assert!(body.contains(text), "{text}: {body}");
        }
        assert_eq!(
            body.matches(r#"<w:br w:type="page"/>"#).count(),
            1,
            "{body}"
        );
        assert!(
            body.contains("<wp:inline"),
            "the polygon is a picture: {body}"
        );
    }
}