f-office-docx 0.2.2

DOCX model and Word's layout rules.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
//! Office Math (`m:oMath`) as runs of text: a first step that gives equations their text, in
//! the math font with mathematical italic letters, and about their width in the line, before a
//! layout of their structure. The runs of scripts and of the parts of fractions keep the parts
//! that they are in, for the sizes and shifts of the math font, stacked fractions, the two
//! scripts of a sub-superscript and the two limits of an n-ary operator mark their start,
//! middle and end for the layout of their parts, matrices mark their cells and rows,
//! delimiters and n-ary operators show their
//! characters, and the rows of an equation array become lines.

use f_office_xml::enumeration::{Values, another, own};
use f_office_xml::{Document, NodeId};

use f_office_units::Length;

use crate::body::{
    AccentMark, BarMark, BarSide, BorderBoxFlags, CellJustification, Content, DEFAULT_ACCENT,
    DEFAULT_GROUP_CHR, GapMinimum, GroupChrMark, GroupChrPlacement, GrownMark, LimitMark,
    LimitSide, MathBoxMark, MatrixBase, MatrixMark, MatrixSettings, ROOT_SIGN, RadicalMark,
    RowSpacing, Run, RunRecord, RunWrapper, ScriptMark, ScriptSide, SlashKind, SlashMark,
    StackMark, read_wrapped,
};
use crate::ns::{M, W};
use crate::on_off;
use crate::props::{Alignment, FontRef, Limit, MathScript, MathStep, MathStyle, RunProps};
use crate::reader::PartReader;
use crate::text::OPERATOR_BREAK_SPACE;
use crate::warnings::Feature;

mod classes;

pub(crate) use classes::ordinary;
use classes::{OperatorClass, operator_class};

/// The font that Word draws equations in.
pub(crate) const MATH_FONT: &str = "Cambria Math";

/// The space that Word puts on each side of a binary operator outside script style, 4/18 em.
/// A no-break space stands for it without a place to break the line, and the shaping gives it
/// that width, but for the space after the operator at the top level of an equation in a line,
/// which an operator break space stands for.
pub(crate) const OPERATOR_SPACE: char = '\u{00A0}';

/// A hair space, which the shaping gives the width that a relation's space adds to an
/// operator's. F-Office breaks lines only at spaces (U+0020), so it does not break an equation.
pub(crate) const HAIR_SPACE: char = '\u{200A}';

/// The space that Word puts on each side of a relation outside script style, 5/18 em: a
/// no-break space and a hair space.
const RELATION_SPACE: [char; 2] = [OPERATOR_SPACE, HAIR_SPACE];

/// The space between a function's name and its argument, around an n-ary operator after an
/// operand and before its element, and after a comma, a semicolon or a colon: a thin space, a
/// sixth of an em in the math font, which does not break the line.
const THIN_SPACE: char = '\u{2009}';

/// The prime, which Word draws for an apostrophe of a math run that is not normal text, with
/// the glyph of its script level.
const PRIME: char = '\u{2032}';

/// Reads an equation (`m:oMath`) or a display of equations (`m:oMathPara`) into runs, starting
/// at `script`: the outermost level of a display when its paragraph is one, and inline after a
/// list label. An equation that goes on from the one right before it (`goes_on`) reads the
/// operand at that one's end as before its start.
pub(crate) fn read(
    reader: &mut PartReader,
    node: NodeId,
    (script, goes_on): (MathScript, bool),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let script = script.with_small_frac(reader.small_frac());
    if doc.is(node, M, "oMath") && goes_on {
        walk(reader, node, script, runs);
    } else if doc.is(node, M, "oMath") {
        equation(reader, node, script, runs);
    } else {
        walk(reader, node, script, runs);
    }
}

/// Reads one equation (`m:oMath`) on its own, so that an operator at its start counts as
/// unary whatever the paragraph has before it.
fn equation(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let mut own = Vec::new();
    walk(reader, node, script, &mut own);
    runs.extend(own);
}

/// Whether the equation's runs so far end with an operand, such as a letter, a digit or a
/// closing delimiter, so that an operator after them stands between two operands.
fn ends_with_operand(runs: &[Run]) -> bool {
    ends_with_operand_past(runs, |c| {
        matches!(c, OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE | BAR)
    })
}

/// Whether the equation's runs so far end with an operand when the literal spaces at their end
/// are left out too, which a grown delimiter's thin space reads past.
fn ends_with_operand_past_spaces(runs: &[Run]) -> bool {
    ends_with_operand_past(runs, |c| {
        matches!(
            c,
            OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE | BAR | ' '
        )
    })
}

/// Whether the equation's runs so far end with an operand, with the characters that `skipped`
/// accepts left out.
fn ends_with_operand_past(runs: &[Run], skipped: fn(char) -> bool) -> bool {
    runs.iter()
        .rev()
        .flat_map(|run| run.content.iter().rev())
        .find_map(|content| match content {
            Content::Text(text) => text.chars().rev().find(|c| !skipped(*c)).map(ends_operand),
            // A stack, such as a fraction, is an operand, and each of its parts starts an
            // equation of its own.
            Content::Stack(mark) => Some(*mark == StackMark::End),
            // So is a matrix, and each of its cells starts an equation of its own.
            Content::Matrix(mark) => Some(*mark == MatrixMark::End),
            // A linear or skewed fraction is an operand, and its parts start equations of their own.
            Content::MathSlash(mark) => Some(*mark == SlashMark::End),
            // A limit structure is an operand unless its base is an operator, and its parts start
            // equations of their own.
            Content::MathLimit(mark) => Some(matches!(mark, LimitMark::End { operand: true })),
            // A grouping character structure is an operand unless it draws an operator on the
            // baseline (`pos == vertJc`).
            Content::GroupChr(mark) => Some(matches!(mark, GroupChrMark::End { operand: true })),
            // A border box is an operand, and its inside starts an equation of its own.
            Content::MathBox(mark) => Some(*mark == MathBoxMark::BorderEnd),
            Content::LineBreak => Some(false),
            _ => None,
        })
        .unwrap_or(false)
}

/// A vertical bar, which closes an operand after an operand and opens one elsewhere, so that
/// what stands before it decides whether an operator after it stands between two operands.
const BAR: char = '|';

/// Whether the character `ch` ends an operand, such as a letter, a digit or a closing delimiter,
/// so that an operator right after it stands between two operands. After an operator or an
/// opening delimiter, an operator is unary. A [`BAR`] is decided by what stands before it.
fn ends_operand(ch: char) -> bool {
    !operator(ch) && !matches!(ch, '(' | '[' | '{' | '\u{27E8}')
}

/// Whether the equation's runs so far end with a thin space, such as the one before the element
/// of an n-ary operator or after a comma.
fn ends_with_thin_space(runs: &[Run]) -> bool {
    runs.iter()
        .rev()
        .flat_map(|run| run.content.iter().rev())
        .find_map(|content| match content {
            Content::Text(text) => text.chars().next_back(),
            _ => None,
        })
        == Some(THIN_SPACE)
}

/// Puts a thin space after a punctuation mark of [`SPACED_MARKS`] or an ellipsis that ends the
/// equation's runs so far, outside script style, when the element `child`, named `name`, goes
/// on with an operand: a structure other than an n-ary operator or an equation array, or a run
/// whose first character is no space and no operator. A decimal mark takes none.
fn space_after_punctuation(
    doc: &Document,
    (child, name): (NodeId, &str),
    script: MathScript,
    runs: &mut [Run],
) {
    let next = match name {
        "r" => doc
            .child_elements(child)
            .filter(|t| doc.is(*t, M, "t"))
            .find_map(|t| doc.text_content(t).chars().next()),
        "nary" | "eqArr" => None,
        _ if STRUCTURES.contains(&name) => Some('x'),
        _ => None,
    };
    let Some(next) = next.filter(|&c| c != ' ' && !operator(c)) else {
        return;
    };
    if script.style() >= MathStyle::Script {
        return;
    }
    let Some(Content::Text(text)) = runs.last_mut().and_then(|run| run.content.last_mut()) else {
        return;
    };
    let mut ends = text.chars().rev();
    let (Some(mark), before) = (ends.next(), ends.next()) else {
        return;
    };
    let spaced = SPACED_MARKS.contains(&mark) || ELLIPSES.contains(&mark);
    if spaced && !decimal(before, mark, next) {
        text.push(THIN_SPACE);
    }
}

/// The punctuation marks after which Word puts a thin space before an operand, outside script
/// style: Unicode's math class punctuation, with `!` and `‼`.
const SPACED_MARKS: [char; 9] = [
    ',', ';', ':', '.', '?', '!', '\u{203C}', '\u{00A1}', '\u{00BF}',
];

/// Whether `mark`, between `before` and `next`, is a decimal mark: a comma or a period between
/// two digits.
fn decimal(before: Option<char>, mark: char, next: char) -> bool {
    matches!(mark, ',' | '.') && before.is_some_and(|c| c.is_ascii_digit()) && next.is_ascii_digit()
}

/// Whether a paragraph holds a display of equations (`m:oMathPara`), which Word centers
/// unless its justification says otherwise.
pub fn is_display(doc: &Document, paragraph: NodeId) -> bool {
    doc.child(paragraph, M, "oMathPara").is_some()
}

/// The alignment of a paragraph that holds a display of equations, whatever the paragraph's
/// own alignment: the justification of its `m:oMathPara` (`m:oMathParaPr/m:jc`) puts the
/// display at the left indent for `left` and at the right indent for `right`, and `center`,
/// `centerGroup` or no justification center it.
pub(crate) fn display_alignment(reader: &mut PartReader, paragraph: NodeId) -> Alignment {
    let doc = reader.doc;
    doc.child(paragraph, M, "oMathPara")
        .and_then(|display| doc.child(display, M, "oMathParaPr"))
        .and_then(|props| doc.child(props, M, "jc"))
        .and_then(|jc| reader.enumeration_in(jc, (Some(M), "val"), DISPLAY_JUSTIFICATION))
        .unwrap_or(Alignment::Center)
}

/// `ST_Jc` of OMML, the justification of a display (`m:oMathParaPr/m:jc`): left and right at
/// the indents, center centered, and centerGroup, which centers the display's equations as one
/// group, drawn centered. A missing value, and text outside the type, are centered.
const DISPLAY_JUSTIFICATION: &Values<Alignment> = &Values::new(&[
    own("left", Alignment::Start),
    own("right", Alignment::End),
    own("center", Alignment::Center),
    another("centerGroup", Alignment::Center),
]);

/// Whether a paragraph's content is one or more equations (`m:oMath`) and nothing else but
/// runs without content and bookmarks. Word makes such a paragraph a display, centered
/// whatever the paragraph's alignment, with all its equations on one line, unless a list
/// label stands before them; a space, a tab or text beside an equation keeps it inline.
pub fn holds_only_equations(doc: &Document, paragraph: NodeId) -> bool {
    let mut equations = 0;
    for child in doc.child_elements(paragraph) {
        if doc.is(child, M, "oMath") {
            equations += 1;
        } else if !no_content(doc, child) {
            return false;
        }
    }
    equations > 0
}

/// Whether a child of a paragraph adds nothing to its content: the paragraph's properties, a
/// bookmark's start or end, or a run with no child but its properties.
fn no_content(doc: &Document, child: NodeId) -> bool {
    doc.is(child, W, "pPr")
        || doc.is(child, W, "bookmarkStart")
        || doc.is(child, W, "bookmarkEnd")
        || (doc.is(child, W, "r") && doc.child_elements(child).all(|c| doc.is(c, W, "rPr")))
}

/// The structures of an equation (ECMA-376 Part 1, 22.1.2), each with its properties element
/// `m:<name>Pr`, whose control properties (`m:ctrlPr`) give the size that the fences of the
/// delimiters inside the outermost one take.
const STRUCTURES: [&str; 19] = [
    "acc",
    "bar",
    "borderBox",
    "box",
    "d",
    "eqArr",
    "f",
    "func",
    "groupChr",
    "limLow",
    "limUpp",
    "m",
    "nary",
    "phant",
    "rad",
    "sPre",
    "sSub",
    "sSubSup",
    "sSup",
];

/// The equation-level control size carried from the first drawing child of `m:oMath`.
#[derive(Clone, Copy)]
enum EquationSize {
    /// Outside `m:oMath`, or `m:oMath` has no drawing child.
    None,
    /// The first drawing child's explicit `w:sz` (`None` means paragraph default).
    Inherited(Option<i64>),
}

/// The part of the element `child`, named `name`, of a part `outer`: inside it, when it is a
/// structure, with the equation's outermost size (`eq_size`, from the first drawing child of
/// `m:oMath`) when at the top level, or the structure's own control size otherwise.
fn entered(
    reader: &mut PartReader,
    (child, name, eq_size): (NodeId, &str, EquationSize),
    outer: MathScript,
) -> MathScript {
    let doc = reader.doc;
    if !STRUCTURES.contains(&name) {
        return outer;
    }
    let size = if outer.in_no_structure()
        && let EquationSize::Inherited(size) = eq_size
    {
        size
    } else {
        let settings = doc.child(child, M, &format!("{name}Pr"));
        control_size(reader, settings)
    };
    outer.in_structure(size)
}

/// The equation-level control size of `node` (`m:oMath`): the explicit size (`w:sz`) of the first
/// drawing child of `node`—from `w:rPr` when it is a math run (`m:r`), or from
/// `m:<name>Pr/m:ctrlPr/w:rPr` when it is a structure. Returns [`EquationSize::None`] outside
/// `m:oMath` or when `node` has no drawing child; [`EquationSize::Inherited`] carries that first
/// child's size (including `None` for paragraph default) to every top-level structure in the
/// equation.
fn equation_size(reader: &mut PartReader, node: NodeId, children: &[NodeId]) -> EquationSize {
    let doc = reader.doc;
    if !doc.is(node, M, "oMath") {
        return EquationSize::None;
    }
    let Some(first) = children.iter().copied().find(|&child| {
        let name = doc.element(child).map_or("", |e| e.name.local);
        if !doc.is(child, M, name) {
            return false;
        }
        if name == "r" {
            doc.child_elements(child)
                .any(|t| doc.is(t, M, "t") && !doc.text_content(t).is_empty())
        } else {
            STRUCTURES.contains(&name)
        }
    }) else {
        return EquationSize::None;
    };
    let name = doc.element(first).map_or("", |e| e.name.local);
    let size = if name == "r" {
        doc.child(first, W, "rPr")
            .and_then(|rpr| RunProps::read(reader, rpr).size)
    } else {
        let settings = doc.child(first, M, &format!("{name}Pr"));
        control_size(reader, settings)
    };
    EquationSize::Inherited(size)
}

fn walk(reader: &mut PartReader, node: NodeId, outer: MathScript, runs: &mut Vec<Run>) {
    walk_in(reader, (node, None), outer, runs);
}

/// Reads the math elements of `node`, an element of a grown delimiter whose opening and closing
/// characters are `enclosing`, or of another part of an equation when that is none.
fn walk_in(
    reader: &mut PartReader,
    (node, enclosing): (NodeId, Option<Fences>),
    outer: MathScript,
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let local = |n: NodeId| doc.element(n).map_or("", |e| e.name.local);
    let mut equations = 0;
    let children: Vec<NodeId> = doc.child_elements(node).collect();
    let eq_size = if outer.in_no_structure() {
        equation_size(reader, node, &children)
    } else {
        EquationSize::None
    };
    for (index, &child) in children.iter().enumerate() {
        if !doc.is(child, M, local(child)) {
            outside_math(reader, child, outer, runs);
            continue;
        }
        let name = local(child);
        space_after_punctuation(doc, (child, name), outer, runs);
        let script = entered(reader, (child, name, eq_size), outer);
        match name {
            "r" => {
                let rest = children.get(index..).unwrap_or(&[]);
                grown_space_after(reader, rest, script, runs);
                let operand = ends_with_operand(runs);
                let followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
                runs.extend(math_run(reader, child, script, (operand, followed)));
            }
            "sSup" | "sSub" | "sPre" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                script_structure(reader, child, (script, rest), runs);
            }
            "f" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                fraction(reader, child, (script, rest), runs);
            }
            "m" => matrix(reader, child, script, runs),
            "sSubSup" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                sub_superscript(reader, child, (script, rest), runs);
            }
            "d" => {
                let nested =
                    enclosing.is_some_and(|outer| beside_same(doc, (&children, index), outer));
                delimiter_in(reader, (child, nested), script, runs);
            }
            "nary" => nary(reader, child, script, runs),
            "func" => function(reader, child, script, runs),
            "phant" => phantom(reader, child, script, runs),
            "rad" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                radical(reader, child, (script, rest), runs);
            }
            "acc" => accent(reader, child, script, runs),
            "bar" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                bar(reader, child, (script, rest), runs);
            }
            "borderBox" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                border_box(reader, child, (script, rest), runs);
            }
            "groupChr" => {
                let rest = children.get(index + 1..).unwrap_or(&[]);
                group_chr(reader, child, (script, rest), runs);
            }
            "limLow" => {
                let is_followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
                limit_structure(reader, child, LimitSide::Lower, (script, is_followed), runs);
            }
            "limUpp" => {
                let is_followed = followed(doc, children.get(index + 1..).unwrap_or(&[]));
                limit_structure(reader, child, LimitSide::Upper, (script, is_followed), runs);
            }
            "eqArr" => equation_array(reader, child, script, runs),
            "box" if !laid_out_otherwise(doc, child, name) => {
                let mut inner = Vec::new();
                walk(reader, child, script, &mut inner);
                runs.extend(inner);
            }
            // The equations of a display go on lines of their own.
            "oMath" => {
                if equations > 0 {
                    runs.push(text_run(Content::LineBreak, script));
                }
                equations += 1;
                equation(reader, child, script, runs);
            }
            name if name.ends_with("Pr") => {}
            // A structure that no arm above lays out shows its content in a row.
            _ => {
                warn_of_a_row(reader, child, name);
                walk(reader, child, script, runs);
            }
        }
    }
}

/// Reads an element of an equation outside Office Math as the body reads it around runs: a
/// tracked change (`w:ins`, `w:del`, `w:moveFrom`, `w:moveTo`) with its runs marked as its
/// author's change, removed or added, and a hyperlink, a smart tag, custom XML or a content
/// control with what it holds. The marks that draw nothing are left out, and any other element
/// that holds something is left out with [`Feature::MathElement`]. A target that prints without
/// markup has accepted the tracked changes before.
fn outside_math(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let local = doc.element(node).map_or("", |e| e.name.local);
    let in_w = doc.is(node, W, local);
    match RunWrapper::of(local) {
        Some(wrapper) if in_w => {
            read_wrapped(doc, node, wrapper, runs, |runs| {
                walk(reader, node, script, runs);
            });
        }
        _ if (in_w && draws_nothing(local)) || doc.children(node).is_empty() => {}
        _ => reader.feature_not_supported(Feature::MathElement),
    }
}

/// Whether the element `local` of WordprocessingML draws nothing in an equation: the
/// properties of the containers (`w:sdtPr`, `w:sdtEndPr`, `w:customXmlPr`, `w:smartTagPr`), the
/// marks of proofing (`w:proofErr`) and of permissions (`w:permStart`, `w:permEnd`), and the
/// starts and ends of bookmarks, comment ranges, moves and custom XML ranges.
fn draws_nothing(local: &str) -> bool {
    matches!(
        local,
        "sdtPr" | "sdtEndPr" | "customXmlPr" | "smartTagPr" | "proofErr" | "permStart" | "permEnd"
    ) || ["Start", "End"].iter().any(|end| {
        local
            .strip_suffix(end)
            .is_some_and(|start| start == "bookmark" || start.ends_with("Range"))
    })
}

/// Warns of [`Feature::MathStructure`] when the element `node`, named `name`, is a structure
/// that no arm of the walk lays out and that Word lays out in another way than its content in a
/// row.
fn warn_of_a_row(reader: &mut PartReader, node: NodeId, name: &str) {
    if STRUCTURES.contains(&name) && laid_out_otherwise(reader.doc, node, name) {
        reader.feature_not_supported(Feature::MathStructure);
    }
}

/// Whether Word lays out the structure `node`, named `name`, which the walk shows as its
/// content in a row, in another way than that row: every such structure but a box (`m:box`)
/// that only groups its content, without acting as an operator (`m:opEmu`) or holding a break
/// (`m:brk`).
fn laid_out_otherwise(doc: &Document, node: NodeId, name: &str) -> bool {
    match name {
        "box" => {
            let props = doc.child(node, M, "boxPr");
            flag(doc, props, "opEmu").unwrap_or(false)
                || props.and_then(|props| doc.child(props, M, "brk")).is_some()
        }
        _ => true,
    }
}

/// A border box (`m:borderBox`): draws its visible sides (all four unless hidden by `m:hideTop`,
/// `m:hideBot`, `m:hideLeft`, `m:hideRight`) and strikes (`m:strikeH`, `m:strikeV`,
/// `m:strikeBLTR`, `m:strikeTLBR`) around its content (`m:e`). When all sides are hidden and no
/// strike is active, lays out the content in a fresh operand context without box marks.
fn border_box(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "borderBoxPr");
    let flags = border_box_flags(doc, settings);
    let content = doc.child(node, M, "e");
    if flags.is_empty() {
        if let Some(content) = content {
            let mut inner = Vec::new();
            walk(reader, content, script, &mut inner);
            runs.extend(inner);
        }
        return;
    }
    fraction_space_before_base(reader, (node, settings), script, runs);
    let mark = structure_mark(reader, settings, script);
    runs.push(mark(Content::MathBox(MathBoxMark::BorderStart(flags))));
    if let Some(content) = content {
        walk(reader, content, script, runs);
    }
    runs.push(mark(Content::MathBox(MathBoxMark::BorderEnd)));
    fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}

/// The visible sides and active strikes of a border box (`m:borderBoxPr`).
fn border_box_flags(doc: &Document, settings: Option<NodeId>) -> BorderBoxFlags {
    let on = |name: &str| flag(doc, settings, name).unwrap_or(false);
    let mut flags = BorderBoxFlags::EMPTY;
    for (name, bit) in [
        ("hideTop", BorderBoxFlags::TOP),
        ("hideBot", BorderBoxFlags::BOTTOM),
        ("hideLeft", BorderBoxFlags::LEFT),
        ("hideRight", BorderBoxFlags::RIGHT),
    ] {
        if !on(name) {
            flags = flags.with(bit);
        }
    }
    for (name, bit) in [
        ("strikeH", BorderBoxFlags::STRIKE_H),
        ("strikeV", BorderBoxFlags::STRIKE_V),
        ("strikeBLTR", BorderBoxFlags::STRIKE_BLTR),
        ("strikeTLBR", BorderBoxFlags::STRIKE_TLBR),
    ] {
        if on(name) {
            flags = flags.with(bit);
        }
    }
    flags
}

/// A function application (`m:func`): the function's name (`m:fName`), a thin space at the
/// function's control size, and its argument (`m:e`). An argument that starts with a delimiter
/// (`m:d`) or an opening fence character (`(`, `[`, `{`, `⟨`) follows the name without the space.
fn function(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    if let Some(name) = doc.child(node, M, "fName") {
        walk(reader, name, script, runs);
    }
    let Some(argument) = doc.child(node, M, "e") else {
        return;
    };
    let delimited = doc
        .child_elements(argument)
        .find(|n| {
            !doc.element(*n)
                .is_some_and(|e| e.name.local.ends_with("Pr"))
        })
        .is_some_and(|first| {
            doc.is(first, M, "d")
                || (doc.is(first, M, "r")
                    && doc
                        .child_elements(first)
                        .filter(|t| doc.is(*t, M, "t"))
                        .find_map(|t| doc.text_content(t).chars().next())
                        .is_some_and(|ch| matches!(ch, '(' | '[' | '{' | '\u{27E8}')))
        });
    if !delimited {
        let settings = doc.child(node, M, "funcPr");
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
    let mut arg = Vec::new();
    walk(reader, argument, script, &mut arg);
    runs.extend(arg);
}

/// The value of the on/off setting `name` among the properties `props`, or `None` when it is
/// absent. The setting is on unless its `m:val` turns it off.
fn flag(doc: &Document, props: Option<NodeId>, name: &str) -> Option<bool> {
    let setting = props.and_then(|p| doc.child(p, M, name))?;
    Some(on_off::element(doc, setting, M))
}

/// A phantom (`m:phant`): its content (`m:e`), shown as usual unless its properties turn
/// showing off (`m:show`). Then the content takes its room in the line and draws nothing, or
/// takes no room either when its width is zero (`m:zeroWid`).
fn phantom(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let start = runs.len();
    if let Some(content) = doc.child(node, M, "e") {
        walk(reader, content, script, runs);
    }
    let props = doc.child(node, M, "phantPr");
    if flag(doc, props, "show").unwrap_or(true) {
        return;
    }
    let no_width = flag(doc, props, "zeroWid").unwrap_or(false);
    for run in runs.iter_mut().skip(start) {
        if no_width {
            run.props.hidden = Some(true);
        } else {
            run.props.phantom = Some(true);
        }
    }
}

/// A radical (`m:rad`): its degree (`m:deg`) when it has content and its properties do not
/// hide it (`m:degHide`), the root sign U+221A, and its element (`m:e`), between marks of
/// [`RadicalMark`] that let the layout choose and place the sign's glyph, its bar and the
/// degree once the element is measured. The sign and the marks take the properties of the
/// radical's settings (`m:ctrlPr` in `m:radPr`), the degree is in script-script style, and the
/// element is cramped (ECMA-376 Part 1, 22.1.2: `m:rad`, `m:radPr`, `m:deg`, `m:degHide` and
/// `m:e`; OpenType `MATH` table, `MathConstants`).
fn radical(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "radPr");
    let degree = doc
        .child(node, M, "deg")
        .filter(|_| !flag(doc, settings, "degHide").unwrap_or(false))
        .filter(|deg| doc.child_elements(*deg).any(|n| !doc.is(n, M, "ctrlPr")));
    let mark = structure_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    runs.push(mark(Content::Radical(RadicalMark::Start {
        degree: degree.is_some(),
    })));
    if let Some(degree) = degree {
        walk(reader, degree, step(MathStep::Degree), runs);
    }
    let mut sign = control_symbol(reader, settings, &ROOT_SIGN.to_string(), script);
    sign.content.insert(0, Content::Radical(RadicalMark::Sign));
    runs.push(sign);
    runs.push(mark(Content::Radical(RadicalMark::Element)));
    if let Some(element) = doc.child(node, M, "e") {
        walk(reader, element, script.cramped(), runs);
    }
    runs.push(mark(Content::Radical(RadicalMark::End)));
    fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}

/// An accent (`m:acc`): its base (`m:e`) and the accent's character, from its properties
/// (`m:chr` in `m:accPr`) or else [`DEFAULT_ACCENT`], between marks of [`AccentMark`] that let
/// the layout choose the character's glyph and place it over the base once the base is
/// measured. The character and the marks take the properties of the accent's settings
/// (`m:ctrlPr` in `m:accPr`), and the base is cramped. An accent whose character is empty shows
/// its base alone
/// (ECMA-376 Part 1, 22.1.2: `m:acc`, `m:accPr` and `m:chr`).
fn accent(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "accPr");
    let character = settings
        .and_then(|props| doc.child(props, M, "chr"))
        .map_or_else(
            || DEFAULT_ACCENT.to_string(),
            |chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
        );
    let base = doc.child(node, M, "e");
    if character.is_empty() {
        if let Some(base) = base {
            walk(reader, base, script, runs);
        }
        return;
    }
    let mark = structure_mark(reader, settings, script);
    runs.push(mark(Content::Accent(AccentMark::Start)));
    if let Some(base) = base {
        walk(reader, base, script.cramped(), runs);
    }
    let mut glyph = control_symbol(reader, settings, &character, script);
    glyph
        .content
        .insert(0, Content::Accent(AccentMark::Character));
    runs.push(glyph);
    runs.push(mark(Content::Accent(AccentMark::End)));
}

/// A delimiter (`m:d`): its opening character, its elements with the separator between them,
/// and its closing character. The structure draws the three characters itself, with the
/// properties of its settings (`m:ctrlPr` in `m:dPr`) but at the size that the control
/// properties of the outermost structure of the equation give, its own when it is that
/// structure, or else at the size of a run without one; and each with the middle of its glyph's
/// ink on the math axis, when it does not grow (`m:grow` off) or its elements are
/// [`line_high`] and it [`nests`] no delimiter. Around other content, marks of [`GrownMark`]
/// around the delimiter and before
/// each character let the layout choose each character's glyph once the content is measured,
/// as the target draws it; after an operand outside script style a thin space comes before the
/// delimiter, which keeps its width only when the content counts as a subformula, as one after
/// the delimiter before an operand does ([`grown_space_after`]).
fn delimiter(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let props = doc.child(node, M, "dPr");
    let character = |name: &str, default: &str| -> String {
        props
            .and_then(|p| doc.child(p, M, name))
            .and_then(|c| doc.attribute(c, Some(M), "val"))
            .unwrap_or(default)
            .to_owned()
    };
    let (open, separator, close) = (
        character("begChr", "("),
        character("sepChr", "|"),
        character("endChr", ")"),
    );
    let elements: Vec<NodeId> = doc
        .child_elements(node)
        .filter(|n| doc.is(*n, M, "e"))
        .collect();
    let elem_script = if elements.len() > 1 {
        script.in_text_style()
    } else {
        script
    };
    let base = !flag(doc, props, "grow").unwrap_or(true)
        || (elements.iter().all(|&e| line_high(doc, e)) && !nests(doc, node));
    let enclosing = (!base).then(|| fences(doc, node));
    let glyph = |reader: &mut PartReader, text: &str| {
        let mut run = control_symbol(reader, props, text, script);
        // The fences take the size of the outermost structure's control properties, as a run
        // whose properties give that size or none.
        run.props.size = script.outermost_size();
        if let Some(ch) = text.chars().next() {
            if base {
                if !SPACED_MARKS.contains(&ch) {
                    run.props.math_script = Some(script.without_outermost().on_axis(ch));
                }
            } else {
                run.content
                    .insert(0, Content::Grown(GrownMark::Character(ch)));
            }
        }
        run
    };
    if !base {
        if script.style() < MathStyle::Script
            && ends_with_operand_past_spaces(runs)
            && !ends_with_thin_space(runs)
        {
            let mut space = control_symbol(reader, props, &THIN_SPACE.to_string(), script);
            space.props.size = script.outermost_size();
            space.content.push(Content::Grown(GrownMark::SpaceBefore));
            runs.push(space);
        }
        runs.push(text_run(Content::Grown(GrownMark::Start), script));
    }
    runs.push(glyph(reader, &open));
    let mut prev = None;
    for e in elements {
        if let Some(previous) = prev {
            push_delimiter_separator(
                reader,
                (props, previous, &separator),
                (elem_script, script),
                &glyph,
                runs,
            );
        }
        if prev.is_some() && separator.is_empty() {
            let mut part = Vec::new();
            walk_in(reader, (e, enclosing), elem_script, &mut part);
            runs.extend(part);
        } else {
            walk_in(reader, (e, enclosing), elem_script, runs);
        }
        prev = Some(e);
    }
    runs.push(glyph(reader, &close));
    if !base {
        let mut end = text_run(Content::Grown(GrownMark::End), script);
        end.props.size = script.outermost_size();
        runs.push(end);
    }
}

/// Emits an optional trailing thin space before a non-empty delimiter separator `separator` and
/// then pushes the separator glyph run itself.
fn push_delimiter_separator(
    reader: &mut PartReader,
    (props, previous, separator): (Option<NodeId>, NodeId, &str),
    (elem_script, script): (MathScript, MathScript),
    glyph: &impl Fn(&mut PartReader, &str) -> Run,
    runs: &mut Vec<Run>,
) {
    let Some(sep_ch) = separator.chars().next() else {
        return;
    };
    if elem_script.style() < MathStyle::Script
        && !is_close_fence(sep_ch)
        && !ends_with_thin_space(runs)
        && element_takes_space_before_sep(reader.doc, previous, runs)
    {
        let mut space = control_symbol(reader, props, &THIN_SPACE.to_string(), elem_script);
        space.props.size = script.outermost_size();
        runs.push(space);
    }
    runs.push(glyph(reader, separator));
}

/// Whether the last drawing child of delimiter element `element` takes a trailing thin space
/// before a non-closing separator: a fraction (`m:f`), an n-ary operator (`m:nary`), a grown
/// delimiter (`m:d`), or a script structure whose base ends in a fraction.
fn element_takes_space_before_sep(doc: &Document, element: NodeId, runs: &[Run]) -> bool {
    let last = doc
        .child_elements(element)
        .filter(|&child| {
            let name = doc.element(child).map_or("", |e| e.name.local);
            doc.is(child, M, name)
                && !name.ends_with("Pr")
                && (name != "r" || first_non_space_char(doc, child).is_some())
        })
        .last();
    let Some(last) = last else {
        return false;
    };
    match doc.element(last).map_or("", |e| e.name.local) {
        "f" | "nary" => true,
        "sSup" | "sSub" | "sSubSup" | "sPre" | "bar" | "borderBox" | "groupChr" | "rad" => {
            base_ends_with_fraction(doc, last)
        }
        "d" => runs
            .iter()
            .rev()
            .flat_map(|run| run.content.iter().rev())
            .find_map(|content| match content {
                Content::Grown(GrownMark::End) => Some(true),
                Content::Text(text) if text.is_empty() => None,
                _ => Some(false),
            })
            .unwrap_or(false),
        _ => false,
    }
}

/// A delimiter (`m:d`, [`delimiter`]); when it is `nested` in a grown delimiter
/// ([`beside_same`]), a [`GrownMark::NestedStart`] before its first run's content and a
/// [`GrownMark::NestedEnd`] after its last run's content let the layout measure it as a
/// delimiter nested in the other.
fn delimiter_in(
    reader: &mut PartReader,
    (node, nested): (NodeId, bool),
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let first = runs.len();
    delimiter(reader, node, script, runs);
    if !nested {
        return;
    }
    if let Some(run) = runs.get_mut(first) {
        run.content
            .insert(0, Content::Grown(GrownMark::NestedStart));
    }
    if let Some(run) = runs.last_mut() {
        run.content.push(Content::Grown(GrownMark::NestedEnd));
    }
}

/// The opening and the closing character of a delimiter.
type Fences<'a> = (&'a str, &'a str);

/// The opening and the closing character of the delimiter `node` (`m:begChr` and `m:endChr` in
/// `m:dPr`), `(` and `)` when its properties name none.
fn fences(doc: &Document, node: NodeId) -> Fences<'_> {
    let character = |name: &str, default: &'static str| {
        doc.child(node, M, "dPr")
            .and_then(|props| doc.child(props, M, name))
            .and_then(|c| doc.attribute(c, Some(M), "val"))
            .unwrap_or(default)
    };
    (character("begChr", "("), character("endChr", ")"))
}

/// Whether an element of the delimiter `node` holds a delimiter beside its own character
/// ([`beside_same`]), which makes `node` grow around content as high as a line too.
fn nests(doc: &Document, node: NodeId) -> bool {
    let outer = fences(doc, node);
    doc.child_elements(node)
        .filter(|n| doc.is(*n, M, "e"))
        .any(|e| {
            let children: Vec<NodeId> = doc.child_elements(e).collect();
            children.iter().enumerate().any(|(index, &child)| {
                doc.is(child, M, "d") && beside_same(doc, (&children, index), outer)
            })
        })
}

/// Whether the delimiter at `index` of the elements `children` of an element of a delimiter
/// whose characters are `outer` stands beside the same character: it is the first element, with
/// only properties before it, and opens with `outer`'s opening character, or the last one, with
/// only properties after it, and closes with `outer`'s closing character.
fn beside_same(doc: &Document, (children, index): (&[NodeId], usize), outer: Fences) -> bool {
    let Some(&node) = children.get(index) else {
        return false;
    };
    let inner = fences(doc, node);
    let properties = |nodes: &[NodeId]| {
        nodes
            .iter()
            .all(|&n| doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")))
    };
    (!outer.0.is_empty() && inner.0 == outer.0 && properties(children.get(..index).unwrap_or(&[])))
        || (!outer.1.is_empty()
            && inner.1 == outer.1
            && properties(children.get(index + 1..).unwrap_or(&[])))
}

/// Before the math runs `rest`, right after a delimiter that grows, outside script style, when
/// their first character past literal spaces is an operand: a thin space at the size of the
/// delimiter's fences, which keeps its width only when the delimiter's content counts as a
/// subformula. `rest` is the math run being read and the elements after it.
fn grown_space_after(
    reader: &mut PartReader,
    rest: &[NodeId],
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let Some(end) = runs
        .last()
        .filter(|run| run.content.contains(&Content::Grown(GrownMark::End)))
    else {
        return;
    };
    let size = end.props.size;
    let first = rest
        .iter()
        .take_while(|node| doc.is(**node, M, "r"))
        .flat_map(|node| doc.child_elements(*node))
        .filter(|t| doc.is(*t, M, "t"))
        .find_map(|t| doc.text_content(t).chars().find(|c| *c != ' '));
    let operand = first.is_some_and(|ch| {
        ends_operand(ch) && !matches!(ch, ')' | ']' | '}' | '\u{27E9}' | BAR) && !ch.is_whitespace()
    });
    if operand && script.style() < MathStyle::Script {
        let mut space = symbol(&THIN_SPACE.to_string(), script);
        space.props.size = size;
        space.content.push(Content::Grown(GrownMark::SpaceAfter));
        runs.push(space);
    }
}

/// Whether the content of a math element holds only runs, functions and delimiters around such
/// content, which stay as high as a line of text: the content around which Word draws a
/// delimiter's base glyph. A script, a fraction, a matrix, an equation array, an n-ary operator,
/// a radical, an accent, a box, a bar, a group character, a limit or a phantom is not, whatever
/// it holds, and neither is a delimiter that [`nests`] another.
fn line_high(doc: &Document, node: NodeId) -> bool {
    doc.child_elements(node).all(|child| {
        let name = doc.element(child).map_or("", |e| e.name.local);
        if !doc.is(child, M, name) || name == "r" || name.ends_with("Pr") {
            return true;
        }
        matches!(name, "d" | "func" | "e" | "fName")
            && line_high(doc, child)
            && !(name == "d" && nests(doc, child))
    })
}

/// An n-ary operator (`m:nary`): its character, after a thin space when it follows an operand
/// outside script style, its limits as scripts, and its element after a thin space. When both
/// limits show, they are stacked as the scripts of a sub-superscript are: both start at the end
/// of the operator, and they take the room of the wider one.
fn nary(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let props = doc.child(node, M, "naryPr");
    let operator = props
        .and_then(|p| doc.child(p, M, "chr"))
        .and_then(|c| doc.attribute(c, Some(M), "val"))
        .unwrap_or("\u{222B}");
    // After an operand Word puts 3/18 em before the operator; after an operator, an opening
    // delimiter or at the start none, and after a thin space already there no second one.
    if script.style() < MathStyle::Script && ends_with_operand(runs) && !ends_with_thin_space(runs)
    {
        runs.push(control_symbol(
            reader,
            props,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
    let limit = |hide: &str, name: &str| {
        doc.child(node, M, name)
            .filter(|_| !flag(doc, props, hide).unwrap_or(false))
    };
    let limits = (limit("subHide", "sub"), limit("supHide", "sup"));
    // A display draws its own n-ary operators with the larger variants of their glyphs, and
    // stacks their limits over and under them or beside them.
    let outermost = script.style() == MathStyle::Display;
    let bare = limits.0.is_none() && limits.1.is_none();
    if outermost && bare {
        runs.push(large_operator(reader, props, operator, script));
    } else if outermost && over_and_under(reader, props, operator) {
        limits_over_and_under(reader, props, operator, limits, script, runs);
    } else if outermost {
        limits_beside(reader, props, operator, limits, script, runs);
    } else {
        // The operator and the thin spaces around it take the size of the structure's
        // control properties, as a display's operator does. Inside a line, the operator stands
        // with the middle of its ink on the math axis.
        let mut symbol = control_symbol(reader, props, operator, script);
        if let Some(ch) = operator.chars().next() {
            symbol.props.math_script = Some(script.without_outermost().on_axis(ch));
        }
        runs.push(symbol);
        let drops = integral(operator);
        scripts(
            reader,
            props,
            limits,
            (script, Marks::Operator { drops }, false),
            runs,
        );
    }
    let Some(element) = doc.child(node, M, "e") else {
        return;
    };
    // Unlike a function's argument, an element that starts with a delimiter gets the space too.
    let content = doc
        .child_elements(element)
        .any(|n| !doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")));
    if content {
        runs.push(control_symbol(
            reader,
            props,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
    walk(reader, element, script, runs);
}

/// Whether an n-ary operator's limits go over and under it (`m:limLoc` `undOvr`) rather than
/// beside it (`subSup`). Without `m:limLoc`, those of an integral go beside it and those of
/// other operators, such as a sum, over and under it.
fn over_and_under(reader: &mut PartReader, props: Option<NodeId>, operator: &str) -> bool {
    let doc = reader.doc;
    let location = props
        .and_then(|p| doc.child(p, M, "limLoc"))
        .and_then(|l| reader.enumeration_or(l, (Some(M), "val"), LIMIT_LOCATION, "subSup"));
    match location {
        Some(over) => over,
        None => !integral(operator),
    }
}

/// Whether the n-ary operator `operator` is an integral, of the characters from U+222B to
/// U+2233 and from U+2A0B to U+2A1C.
fn integral(operator: &str) -> bool {
    operator
        .chars()
        .next()
        .is_some_and(|c| matches!(c, '\u{222B}'..='\u{2233}' | '\u{2A0B}'..='\u{2A1C}'))
}

/// `ST_LimLoc`, where the limits of an n-ary operator go (`m:limLoc`): over and under it
/// (`undOvr`, `true`) or beside it (`subSup`); each name is drawn. Text outside the type reads
/// as `subSup`, while a missing value follows the operator.
const LIMIT_LOCATION: &Values<bool> = &Values::new(&[own("undOvr", true), own("subSup", false)]);

/// An n-ary operator of a display with its limits over and under it: the operator in the
/// larger variant of its glyph, its upper limit centered over it and its lower limit centered
/// under it, as two centered stacks, the upper limit over the operator and both over the lower
/// limit, so that the structure takes the room of the widest of the three.
fn limits_over_and_under(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    operator: &str,
    (sub, sup): (Option<NodeId>, Option<NodeId>),
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let limit = Limit {
        operator: operator.chars().next().unwrap_or('\u{2211}'),
        beside: false,
    };
    let mark = stack_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    let start = StackMark::Start {
        bar: None,
        centered: true,
    };
    runs.push(mark(start));
    runs.push(mark(start));
    if let Some(sup) = sup {
        walk(reader, sup, step(MathStep::UpperLimit(limit)), runs);
    }
    runs.push(mark(StackMark::Middle));
    runs.push(large_operator(reader, settings, operator, script));
    runs.push(mark(StackMark::End));
    runs.push(mark(StackMark::Middle));
    if let Some(sub) = sub {
        walk(reader, sub, step(MathStep::LowerLimit(limit)), runs);
    }
    runs.push(mark(StackMark::End));
}

/// An n-ary operator of a display with its limits beside it: the operator in the larger
/// variant of its glyph, then its lower and upper limits as one stack that starts at the end
/// of the operator, the lower limit moved left by the italic correction of that glyph, so
/// that the structure ends where the limit that ends later ends.
fn limits_beside(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    operator: &str,
    (sub, sup): (Option<NodeId>, Option<NodeId>),
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let limit = Limit {
        operator: operator.chars().next().unwrap_or('\u{222B}'),
        beside: true,
    };
    let mark = stack_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    runs.push(large_operator(reader, settings, operator, script));
    runs.push(mark(StackMark::StartBeside(limit.operator)));
    if let Some(sub) = sub {
        walk(reader, sub, step(MathStep::LowerLimit(limit)), runs);
    }
    runs.push(mark(StackMark::Middle));
    if let Some(sup) = sup {
        walk(reader, sup, step(MathStep::UpperLimit(limit)), runs);
    }
    runs.push(mark(StackMark::End));
}

/// The kind of a fraction (`m:fPr/m:type`) as F-Office draws it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FractionKind {
    /// Stacked, with a fraction bar (`bar`).
    Bar,
    /// Stacked, without a fraction bar (`noBar`).
    NoBar,
    /// Numerator, fraction slash and denominator on one baseline (`lin`).
    Linear,
    /// Numerator raised and denominator lowered across a fraction slash (`skw`).
    Skewed,
}

/// `ST_FType`, the kind of a fraction (`m:fPr/m:type`): bar and noBar stacked, lin on one
/// baseline with a slash, and skw with its parts raised and lowered across a slash. A missing
/// value is bar; text outside the type is read as `lin`.
const FRACTION_KIND: &Values<FractionKind> = &Values::new(&[
    own("bar", FractionKind::Bar),
    own("skw", FractionKind::Skewed),
    own("lin", FractionKind::Linear),
    own("noBar", FractionKind::NoBar),
]);

/// The fraction slash (`U+2044`) drawn between the numerator and the denominator of a linear or
/// skewed fraction.
const FRACTION_SLASH: &str = "\u{2044}";

/// A fraction (`m:f`): a stacked fraction (`m:type` `bar`, the default, or `noBar`) marks its
/// start, the end of its numerator and its end around its parts, in runs with the fraction's
/// properties (`m:ctrlPr`). A linear (`lin`) or skewed (`skw`) fraction keeps its parts at the
/// enclosing script size and marks its start, its fraction slash (`U+2044`), its denominator and
/// its end. Outside script style, every fraction takes a thin space on each side next to adjacent
/// terms that do not already supply their own spacing.
fn fraction(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "fPr");
    let kind = settings
        .and_then(|p| doc.child(p, M, "type"))
        .and_then(|t| reader.enumeration_or(t, (Some(M), "val"), FRACTION_KIND, "lin"))
        .unwrap_or(FractionKind::Bar);
    if script.style() < MathStyle::Script && needs_fraction_space_before(runs) {
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
    match kind {
        FractionKind::Bar => stacked_fraction(reader, (node, settings), true, script, runs),
        FractionKind::NoBar => stacked_fraction(reader, (node, settings), false, script, runs),
        FractionKind::Linear => {
            slashed_fraction(reader, (node, settings), SlashKind::Linear, script, runs);
        }
        FractionKind::Skewed => {
            slashed_fraction(reader, (node, settings), SlashKind::Skewed, script, runs);
        }
    }
    if script.style() < MathStyle::Script && needs_fraction_space_after(reader, rest) {
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
}

/// A stacked fraction (`m:f` whose `m:type` is `bar` or `noBar`): numerator over denominator
/// between [`StackMark`] markers, with a fraction bar when `drawn_bar` is set.
fn stacked_fraction(
    reader: &mut PartReader,
    (node, settings): (NodeId, Option<NodeId>),
    drawn_bar: bool,
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let minimum = if script.style() == MathStyle::Display {
        GapMinimum::Display
    } else {
        GapMinimum::Line
    };
    let bar = drawn_bar.then_some(minimum);
    let mark = stack_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    runs.push(mark(StackMark::Start {
        bar,
        centered: true,
    }));
    if let Some(numerator) = doc.child(node, M, "num") {
        walk(reader, numerator, step(MathStep::Numerator), runs);
    }
    runs.push(mark(StackMark::Middle));
    if let Some(denominator) = doc.child(node, M, "den") {
        walk(reader, denominator, step(MathStep::Denominator), runs);
    }
    runs.push(mark(StackMark::End));
}

/// Opening fence characters after which a fraction takes no leading thin space.
fn is_open_fence(ch: char) -> bool {
    matches!(
        ch,
        '(' | '['
            | '{'
            | '\u{27E8}'
            | '\u{2308}'
            | '\u{230A}'
            | '\u{27E6}'
            | '\u{27EA}'
            | '\u{2016}'
    )
}

/// Closing fence characters before which a fraction takes no trailing thin space.
fn is_close_fence(ch: char) -> bool {
    matches!(
        ch,
        ')' | ']'
            | '}'
            | '\u{27E9}'
            | '\u{2309}'
            | '\u{230B}'
            | '\u{27E7}'
            | '\u{27EB}'
            | '\u{2016}'
    )
}

/// Whether a fraction after `runs` takes a leading thin space: when `runs` holds preceding
/// content in the same part that neither already ends with math spacing (operator, relation or
/// thin space) nor opens the part (opening fence, start of a delimiter or structure part).
/// Unlike binary/relation operators, a unary sign carries no trailing operator space and keeps
/// the thin space before the fraction.
fn needs_fraction_space_before(runs: &[Run]) -> bool {
    runs.iter()
        .rev()
        .flat_map(|run| run.content.iter().rev())
        .find_map(fraction_space_after_content)
        .unwrap_or(false)
}

/// Whether a single piece of preceding content asks for a thin space before a following fraction
/// (`Some(true)`), suppresses it (`Some(false)`), or is transparent (`None`, such as script marks).
fn fraction_space_after_content(content: &Content) -> Option<bool> {
    match content {
        Content::Text(text) => text
            .chars()
            .rev()
            .find(|&c| c != ' ')
            .map(fraction_space_after_char),
        Content::Stack(mark) => Some(*mark == StackMark::End),
        Content::Matrix(mark) => Some(*mark == MatrixMark::End),
        Content::MathSlash(mark) => Some(*mark == SlashMark::End),
        Content::MathLimit(mark) => Some(matches!(mark, LimitMark::End { operand: true })),
        Content::GroupChr(mark) => Some(matches!(mark, GroupChrMark::End { operand: true })),
        Content::MathBox(mark) => Some(*mark == MathBoxMark::BorderEnd),
        Content::Radical(mark) => Some(*mark == RadicalMark::End),
        Content::Accent(mark) => Some(*mark == AccentMark::End),
        Content::MathBar(mark) => Some(*mark == BarMark::End),
        Content::Grown(GrownMark::End) => Some(true),
        Content::Grown(GrownMark::Start) | Content::LineBreak => Some(false),
        _ => None,
    }
}

/// Whether a non-space preceding character asks for a thin space before a following fraction.
fn fraction_space_after_char(ch: char) -> bool {
    !matches!(
        ch,
        THIN_SPACE | OPERATOR_SPACE | OPERATOR_BREAK_SPACE | HAIR_SPACE
    ) && !is_open_fence(ch)
        && !leads(ch)
}

/// Whether a fraction (or a script structure whose base ends in a fraction) takes a trailing
/// thin space before `rest`, the remaining sibling elements of its part: when `rest` begins
/// with a term that does not already supply its own leading space (not a binary/relation
/// operator, ellipsis, closing fence, trailing end-of-part punctuation, or operator-spaced
/// structure).
fn needs_fraction_space_after(reader: &mut PartReader, rest: &[NodeId]) -> bool {
    let doc = reader.doc;
    for (pos, &node) in rest.iter().enumerate() {
        let name = doc.element(node).map_or("", |e| e.name.local);
        if !doc.is(node, M, name) || name.ends_with("Pr") {
            continue;
        }
        if name == "r" {
            if let Some((ch, more_in_run)) = first_non_space_char(doc, node) {
                let tail = rest.get(pos + 1..).unwrap_or(&[]);
                return fraction_space_before_run_char(doc, (node, tail), (ch, more_in_run));
            }
            continue;
        }
        return fraction_space_before_structure(reader, node, name);
    }
    false
}

/// The first character other than an ASCII space in the text elements of the math run `run`,
/// together with whether another non-space character follows it in the same run.
fn first_non_space_char(doc: &Document, run: NodeId) -> Option<(char, bool)> {
    let mut first = None;
    for t in doc.child_elements(run).filter(|&t| doc.is(t, M, "t")) {
        for ch in doc.text_content(t).chars().filter(|&c| c != ' ') {
            if let Some(prev) = first {
                return Some((prev, true));
            }
            first = Some(ch);
        }
    }
    first.map(|ch| (ch, false))
}

/// Whether a following math run starting with `ch` asks for a thin space after a fraction.
/// End-of-part punctuation (with nothing non-space after it in its run or `tail`) takes none.
fn fraction_space_before_run_char(
    doc: &Document,
    (run, tail): (NodeId, &[NodeId]),
    (ch, more_in_run): (char, bool),
) -> bool {
    if is_close_fence(ch) || ch.is_whitespace() {
        return false;
    }
    if SPACED_MARKS.contains(&ch) && !more_in_run && !has_non_space_content(doc, tail) {
        return false;
    }
    let normal = doc
        .child(run, M, "rPr")
        .and_then(|p| doc.child(p, M, "nor"))
        .is_some();
    if normal {
        return true;
    }
    let shown = shown(ch);
    !operator(shown) && !ELLIPSES.contains(&shown)
}

/// Whether any math element in `rest` holds a structure or a run with a non-space character.
fn has_non_space_content(doc: &Document, rest: &[NodeId]) -> bool {
    rest.iter().any(|&node| {
        let name = doc.element(node).map_or("", |e| e.name.local);
        if !doc.is(node, M, name) || name.ends_with("Pr") {
            return false;
        }
        name != "r" || first_non_space_char(doc, node).is_some()
    })
}

/// Whether a following math structure `node`, named `name`, asks for a thin space after a
/// fraction. Fractions, n-ary operators, and operator-base limits/group characters emit their own
/// leading space.
fn fraction_space_before_structure(reader: &mut PartReader, node: NodeId, name: &str) -> bool {
    let doc = reader.doc;
    match name {
        "f" | "nary" | "eqArr" => false,
        "limLow" | "limUpp" => doc
            .child(node, M, "e")
            .and_then(|base| single_operator_base(reader, base))
            .is_none(),
        "groupChr" => {
            let settings = doc.child(node, M, "groupChrPr");
            group_chr_operator(reader, settings).is_none()
        }
        _ => STRUCTURES.contains(&name),
    }
}

/// Whether the first or last drawing child of `node`'s base (`m:e`) is a fraction (`m:f`).
fn base_edge_is_fraction(doc: &Document, node: NodeId, last: bool) -> bool {
    let Some(base) = doc.child(node, M, "e") else {
        return false;
    };
    let mut drawing = doc.child_elements(base).filter(|&child| {
        let name = doc.element(child).map_or("", |e| e.name.local);
        doc.is(child, M, name)
            && !name.ends_with("Pr")
            && (name != "r" || first_non_space_char(doc, child).is_some())
    });
    let edge = if last { drawing.last() } else { drawing.next() };
    edge.is_some_and(|child| doc.is(child, M, "f"))
}

/// Whether the base (`m:e`) of a structure starts with a fraction (`m:f`), so that an enclosing
/// bar, border box, or grouping character carries the fraction's leading thin space outside
/// script style.
fn base_starts_with_fraction(doc: &Document, node: NodeId) -> bool {
    base_edge_is_fraction(doc, node, false)
}

/// Whether the base (`m:e`) of a structure ends with a fraction (`m:f`), so that an enclosing
/// script, bar, border box, grouping character, or radical carries the fraction's trailing thin
/// space outside script style.
fn base_ends_with_fraction(doc: &Document, node: NodeId) -> bool {
    base_edge_is_fraction(doc, node, true)
}

/// Prepends the leading thin space of a wrapper structure whose base starts with a fraction,
/// outside script style and after preceding content that asks for it.
fn fraction_space_before_base(
    reader: &mut PartReader,
    (node, settings): (NodeId, Option<NodeId>),
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    if script.style() < MathStyle::Script
        && base_starts_with_fraction(reader.doc, node)
        && needs_fraction_space_before(runs)
    {
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
}

/// Appends the trailing thin space of a structure whose base ends in a fraction, outside script
/// style and before a sibling term that asks for it.
fn fraction_space_after_base(
    reader: &mut PartReader,
    (node, settings): (NodeId, Option<NodeId>),
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    if script.style() < MathStyle::Script
        && base_ends_with_fraction(reader.doc, node)
        && needs_fraction_space_after(reader, rest)
    {
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    }
}

/// A linear or skewed fraction (`m:f` whose `m:type` is `lin` or `skw`): numerator and
/// denominator at `script` (no script-size reduction) with the fraction slash (`U+2044`) drawn
/// in the fraction's control properties between them.
fn slashed_fraction(
    reader: &mut PartReader,
    (node, settings): (NodeId, Option<NodeId>),
    kind: SlashKind,
    script: MathScript,
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let mark = structure_mark(reader, settings, script);
    runs.push(mark(Content::MathSlash(SlashMark::Start(kind))));
    if let Some(numerator) = doc.child(node, M, "num") {
        walk(reader, numerator, script, runs);
    }
    runs.push(mark(Content::MathSlash(SlashMark::Slash)));
    runs.push(control_symbol(reader, settings, FRACTION_SLASH, script));
    runs.push(mark(Content::MathSlash(SlashMark::Denominator)));
    if let Some(denominator) = doc.child(node, M, "den") {
        let den_script = match kind {
            SlashKind::Skewed => script.cramped(),
            SlashKind::Linear => script,
        };
        walk(reader, denominator, den_script, runs);
    }
    runs.push(mark(Content::MathSlash(SlashMark::End)));
}

/// The side of its base on which a bar structure draws its bar (`m:pos`).
const BAR_SIDE: &Values<BarSide> =
    &Values::new(&[own("top", BarSide::Top), own("bot", BarSide::Bottom)]);

/// A bar structure (`m:bar`): its base (`m:e`) between a start, with the side of its bar
/// (`m:pos` in `m:barPr`, under the base when it names none), and an end, in runs with the
/// structure's properties. The base of an overbar is cramped, as an accent's is.
fn bar(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "barPr");
    let side = settings
        .and_then(|props| doc.child(props, M, "pos"))
        .and_then(|pos| reader.enumeration_in(pos, (Some(M), "val"), BAR_SIDE))
        .unwrap_or_default();
    fraction_space_before_base(reader, (node, settings), script, runs);
    let mark = structure_mark(reader, settings, script);
    runs.push(mark(Content::MathBar(BarMark::Start(side))));
    if let Some(base) = doc.child(node, M, "e") {
        let base_script = match side {
            BarSide::Top => script.cramped(),
            BarSide::Bottom => script,
        };
        walk(reader, base, base_script, runs);
    }
    runs.push(mark(Content::MathBar(BarMark::End)));
    fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}

/// Reads the `m:pos` (default bottom) and `m:vertJc` (default top) of a `m:groupChrPr`.
fn group_chr_placement(reader: &mut PartReader, settings: Option<NodeId>) -> GroupChrPlacement {
    let doc = reader.doc;
    let position = settings
        .and_then(|props| doc.child(props, M, "pos"))
        .and_then(|pos| reader.enumeration_in(pos, (Some(M), "val"), BAR_SIDE))
        .unwrap_or(BarSide::Bottom);
    let vertical_align = settings
        .and_then(|props| doc.child(props, M, "vertJc"))
        .and_then(|jc| reader.enumeration_in(jc, (Some(M), "val"), BAR_SIDE))
        .unwrap_or(BarSide::Top);
    GroupChrPlacement {
        position,
        vertical_align,
    }
}

/// Emits the leading or trailing outer space of a `m:groupChr` structure: operator thin space
/// when `spaced && has_neighbor`, or wrapper fraction thin space when `!chr_on_baseline`.
fn group_chr_outer_space(
    reader: &mut PartReader,
    (node, settings): (NodeId, Option<NodeId>),
    (script, rest): (MathScript, Option<&[NodeId]>),
    (spaced, chr_on_baseline): (bool, bool),
    runs: &mut Vec<Run>,
) {
    let operator_neighbor = match rest {
        None => ends_with_operand(runs),
        Some(tail) => followed(reader.doc, tail),
    };
    if spaced && operator_neighbor {
        runs.push(control_symbol(
            reader,
            settings,
            &THIN_SPACE.to_string(),
            script,
        ));
    } else if !chr_on_baseline {
        match rest {
            None => fraction_space_before_base(reader, (node, settings), script, runs),
            Some(tail) => fraction_space_after_base(reader, (node, settings), (script, tail), runs),
        }
    }
}

/// A grouping character (`m:groupChr`): its base (`m:e`) and stretched character (`m:chr` in
/// `m:groupChrPr`, defaulting to [`DEFAULT_GROUP_CHR`]), with `m:pos` (default bottom) and
/// `m:vertJc` (default top). When `pos == vertJc`, the character stays on the baseline and `m:e`
/// steps down one script level above or below it; when `pos == vertJc` and the character is a
/// math operator (such as an arrow), thin spaces surround the structure outside script style.
fn group_chr(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "groupChrPr");
    let character = settings
        .and_then(|props| doc.child(props, M, "chr"))
        .map_or_else(
            || DEFAULT_GROUP_CHR.to_string(),
            |chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
        );
    let base = doc.child(node, M, "e");
    if character.is_empty() {
        if let Some(base) = base {
            walk(reader, base, script, runs);
        }
        return;
    }
    let placement = group_chr_placement(reader, settings);
    let chr_on_baseline = placement.position == placement.vertical_align;
    let single_op = group_chr_operator(reader, settings).is_some();
    let spaced = single_op && script.style() < MathStyle::Script;
    group_chr_outer_space(
        reader,
        (node, settings),
        (script, None),
        (spaced, chr_on_baseline),
        runs,
    );
    let mark = structure_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    runs.push(mark(Content::GroupChr(GroupChrMark::Start(placement))));
    if let Some(base) = base {
        let base_script = if chr_on_baseline {
            step(MathStep::Limit {
                lower: placement.position == BarSide::Top,
            })
        } else {
            script
        };
        walk(reader, base, base_script, runs);
    }
    let mut glyph = control_symbol(reader, settings, &character, script);
    glyph
        .content
        .insert(0, Content::GroupChr(GroupChrMark::Character));
    runs.push(glyph);
    runs.push(mark(Content::GroupChr(GroupChrMark::End {
        operand: !single_op,
    })));
    group_chr_outer_space(
        reader,
        (node, settings),
        (script, Some(rest)),
        (spaced, chr_on_baseline),
        runs,
    );
}

/// If `base` (`m:e`) holds a single math run whose shown text is one binary or relation operator,
/// or a single `m:groupChr` whose baseline character (`pos == vertJc`) is one binary or relation
/// operator, returns the surrounding space kind (`Operator` for a bare run, `Thin` for a
/// baseline `m:groupChr` operator) so `m:limLow`/`m:limUpp` keeps those spaces outside the stack.
#[derive(Clone, Copy)]
enum LimitBaseSpace {
    Operator(char),
    Thin,
}

impl LimitBaseSpace {
    fn text(self, script: MathScript, after: bool) -> String {
        match self {
            Self::Operator(op) if after => space_after_operator(script, op).iter().collect(),
            Self::Operator(op) => operator_space(script, op).iter().collect(),
            Self::Thin if script.style() < MathStyle::Script => THIN_SPACE.to_string(),
            Self::Thin => String::new(),
        }
    }
}

fn single_operator_base(reader: &mut PartReader, base: NodeId) -> Option<LimitBaseSpace> {
    let doc = reader.doc;
    let mut children = doc
        .child_elements(base)
        .filter(|&n| !doc.element(n).is_some_and(|e| e.name.local.ends_with("Pr")));
    let node = children.next()?;
    if children.next().is_some() {
        return None;
    }
    if doc.is(node, M, "r") {
        let text: String = doc
            .child_elements(node)
            .filter(|&n| doc.is(n, M, "t"))
            .map(|t| doc.text_content(t))
            .collect();
        let mut chars = text.chars().map(shown);
        let ch = chars.next()?;
        if chars.next().is_some() {
            return None;
        }
        return matches!(
            operator_class(ch),
            Some(OperatorClass::Relation | OperatorClass::Binary)
        )
        .then_some(LimitBaseSpace::Operator(ch));
    }
    if doc.is(node, M, "groupChr") {
        let settings = doc.child(node, M, "groupChrPr");
        let ch = group_chr_operator(reader, settings)?;
        let _ = ch;
        return Some(LimitBaseSpace::Thin);
    }
    None
}

/// If a `m:groupChr` with properties `settings` draws a single binary or relation operator on
/// the baseline (`pos == vertJc`), returns that operator character.
fn group_chr_operator(reader: &mut PartReader, settings: Option<NodeId>) -> Option<char> {
    let placement = group_chr_placement(reader, settings);
    if placement.position != placement.vertical_align {
        return None;
    }
    let doc = reader.doc;
    let character = settings
        .and_then(|props| doc.child(props, M, "chr"))
        .map_or_else(
            || DEFAULT_GROUP_CHR.to_string(),
            |chr| doc.attribute(chr, Some(M), "val").unwrap_or("").to_owned(),
        );
    let mut chars = character.chars();
    let ch = shown(chars.next()?);
    if chars.next().is_some() {
        return None;
    }
    operator_class(ch).map(|_| ch)
}

/// A lower- or upper-limit structure (`m:limLow` or `m:limUpp`): marks its start with `side`,
/// walks its base (`m:e`) at `script`, marks the start of its limit, walks its limit (`m:lim`)
/// one script level down (cramped when lower), and marks its end. When the base is a single
/// relation or binary operator (or a baseline `m:groupChr` operator), emits the operator's spaces
/// outside the stacked structure.
fn limit_structure(
    reader: &mut PartReader,
    node: NodeId,
    side: LimitSide,
    (script, followed): (MathScript, bool),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let props_name = match side {
        LimitSide::Lower => "limLowPr",
        LimitSide::Upper => "limUppPr",
    };
    let settings = doc.child(node, M, props_name);
    let base = doc.child(node, M, "e");
    let base_op = base.and_then(|b| single_operator_base(reader, b));
    if let Some(kind) = base_op
        && ends_with_operand(runs)
    {
        let before = kind.text(script, false);
        if !before.is_empty() {
            runs.push(control_symbol(reader, settings, &before, script));
        }
    }
    let mark = structure_mark(reader, settings, script);
    let step = steps_in(reader, settings, script);
    runs.push(mark(Content::MathLimit(LimitMark::Start(side))));
    if let Some(base) = base {
        walk(reader, base, script, runs);
    }
    runs.push(mark(Content::MathLimit(LimitMark::Limit)));
    if let Some(lim) = doc.child(node, M, "lim") {
        let lower = side == LimitSide::Lower;
        walk(reader, lim, step(MathStep::Limit { lower }), runs);
    }
    runs.push(mark(Content::MathLimit(LimitMark::End {
        operand: base_op.is_none(),
    })));
    if let Some(kind) = base_op
        && followed
    {
        let after = kind.text(script, true);
        if !after.is_empty() {
            runs.push(control_symbol(reader, settings, &after, script));
        }
    }
}

/// The rows of a matrix (`m:baseJc`): which row stands on the line's baseline.
const MATRIX_BASE: &Values<MatrixBase> = &Values::new(&[
    own("top", MatrixBase::Top),
    own("center", MatrixBase::Center),
    own("bot", MatrixBase::Bottom),
]);

/// The justification of a column of a matrix (`m:mcJc`). F-Office places a cell of a column
/// justified to the inside or the outside of the page in the column's middle.
const CELL_JUSTIFICATION: &Values<CellJustification> = &Values::new(&[
    own("left", CellJustification::Left),
    own("center", CellJustification::Center),
    own("right", CellJustification::Right),
    another("inside", CellJustification::Center),
    another("outside", CellJustification::Center),
]);

/// A matrix (`m:m`): its cells, the elements (`m:e`) of each row (`m:mr`), each after a mark
/// with its column's justification, each row after the first after a mark of its own, between
/// a start with the matrix's settings and an end, in runs with the matrix's properties
/// (`m:ctrlPr`). Each cell is a part of its own at the matrix's style.
fn matrix(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let settings = doc.child(node, M, "mPr");
    let columns = column_justifications(reader, settings);
    let rows = doc
        .child_elements(node)
        .filter(|n| doc.is(*n, M, "mr"))
        .map(|row| {
            doc.child_elements(row)
                .filter(|n| doc.is(*n, M, "e"))
                .enumerate()
                .map(|(column, cell)| (columns.get(column).copied().unwrap_or_default(), cell))
                .collect()
        })
        .collect();
    grid(reader, settings, (rows, script), runs);
}

/// An equation array (`m:eqArr`): its rows (`m:e`) stacked as the rows of a matrix of one
/// column with centered cells, with the base row and the row spacing of its settings
/// (`m:eqArrPr`), which name them as a matrix's do.
fn equation_array(reader: &mut PartReader, node: NodeId, script: MathScript, runs: &mut Vec<Run>) {
    let doc = reader.doc;
    let rows = doc
        .child_elements(node)
        .filter(|n| doc.is(*n, M, "e"))
        .map(|row| vec![(CellJustification::Center, row)])
        .collect();
    grid(reader, doc.child(node, M, "eqArrPr"), (rows, script), runs);
}

/// The marks and cells of a grid of `rows`, each a row of cells with their justifications,
/// between a start with the settings `settings` and an end.
fn grid(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    (rows, script): (Vec<Vec<(CellJustification, NodeId)>>, MathScript),
    runs: &mut Vec<Run>,
) {
    let start = matrix_settings(reader, settings);
    let mark = structure_mark(reader, settings, script);
    runs.push(mark(Content::Matrix(MatrixMark::Start(start))));
    for (index, row) in rows.into_iter().enumerate() {
        if index > 0 {
            runs.push(mark(Content::Matrix(MatrixMark::Row)));
        }
        for (justification, cell) in row {
            runs.push(mark(Content::Matrix(MatrixMark::Cell(justification))));
            walk(reader, cell, script, runs);
        }
    }
    runs.push(mark(Content::Matrix(MatrixMark::End)));
}

/// The rules of the distance between the rows of a matrix (`m:rSpRule`), each at its value:
/// one line, one and a half lines, two lines, exactly `m:rSp` twips and `m:rSp` half lines.
#[derive(Clone, Copy)]
enum RowRule {
    Single,
    OneAndAHalf,
    Double,
    Exactly,
    HalfLines,
}

/// The rules of `m:rSpRule`, at the index of their value.
const ROW_RULES: [RowRule; 5] = [
    RowRule::Single,
    RowRule::OneAndAHalf,
    RowRule::Double,
    RowRule::Exactly,
    RowRule::HalfLines,
];

/// The settings of a matrix (`m:mPr` in `settings`): the row on the line's baseline
/// (`m:baseJc`), the distance between rows (`m:rSpRule`, with `m:rSp` in twips for the exact
/// rule and in half lines for the multiple rule) and the least width of a column (`m:cSp`, in
/// twips). The column gap rules (`m:cGapRule` and `m:cGap`) do not change Word for Windows'
/// matrix, which keeps its gap.
fn matrix_settings(reader: &mut PartReader, settings: Option<NodeId>) -> MatrixSettings {
    let doc = reader.doc;
    let setting = |name: &str| settings.and_then(|p| doc.child(p, M, name));
    let base = setting("baseJc")
        .and_then(|n| reader.enumeration_in(n, (Some(M), "val"), MATRIX_BASE))
        .unwrap_or_default();
    let number = |reader: &mut PartReader, name: &str| {
        setting(name)
            .and_then(|n| reader.or_missing_in(n, (Some(M), "val"), crate::numbers::decimal))
    };
    let distance = number(reader, "rSp").unwrap_or(0).max(0);
    let rule = number(reader, "rSpRule")
        .and_then(|value| usize::try_from(value).ok())
        .and_then(|value| ROW_RULES.get(value));
    let rows = match rule {
        Some(RowRule::OneAndAHalf) => RowSpacing::OneAndAHalf,
        Some(RowRule::Double) => RowSpacing::Double,
        Some(RowRule::Exactly) => {
            Length::from_twips(distance).map_or(RowSpacing::Single, RowSpacing::Exactly)
        }
        Some(RowRule::HalfLines) => RowSpacing::HalfLines(distance),
        Some(RowRule::Single) | None => RowSpacing::Single,
    };
    let column_width = number(reader, "cSp")
        .and_then(|twips| Length::from_twips(twips.max(0)))
        .unwrap_or(Length::ZERO);
    MatrixSettings {
        base,
        rows,
        column_width,
    }
}

/// The justification of each column of a matrix, from the column settings (`m:mc` in `m:mcs`
/// of the settings `settings`), each of which covers `m:count` columns, one when it gives none.
fn column_justifications(
    reader: &mut PartReader,
    settings: Option<NodeId>,
) -> Vec<CellJustification> {
    let doc = reader.doc;
    let Some(columns) = settings.and_then(|p| doc.child(p, M, "mcs")) else {
        return Vec::new();
    };
    let mut out = Vec::new();
    for column in doc.child_elements(columns).filter(|n| doc.is(*n, M, "mc")) {
        let props = doc.child(column, M, "mcPr");
        let setting = |name: &str| props.and_then(|p| doc.child(p, M, name));
        let count = setting("count")
            .and_then(|n| reader.or_missing_in(n, (Some(M), "val"), crate::numbers::decimal))
            .unwrap_or(1)
            .clamp(1, crate::params::MATH_MATRIX_COLUMNS);
        let justification = setting("mcJc")
            .and_then(|n| reader.enumeration_in(n, (Some(M), "val"), CELL_JUSTIFICATION))
            .unwrap_or_default();
        let count = usize::try_from(count).unwrap_or(1);
        out.extend(std::iter::repeat_n(justification, count));
    }
    out
}

/// A sub-superscript (`m:sSubSup`): its base, then its subscript and its superscript stacked,
/// so that both start at the end of the base and the structure takes the room of the wider
/// script, each script placed by the base's corners.
fn sub_superscript(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let followed = followed(doc, rest);
    let settings = doc.child(node, M, "sSubSupPr");
    let start = box_start(doc, node);
    let boxed = start.is_some();
    if let Some(start) = start {
        let mark = structure_mark(reader, settings, script);
        runs.push(mark(Content::Scripts(start)));
    }
    if let Some(base) = doc.child(node, M, "e") {
        walk(reader, base, script, runs);
    }
    let parts = (doc.child(node, M, "sub"), doc.child(node, M, "sup"));
    scripts(
        reader,
        settings,
        parts,
        (script, Marks::Base { boxed }, followed),
        runs,
    );
    fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}

/// The mark that starts the base (`m:e`) of the script structure `node` when it may be a box
/// ([`ScriptMark::BoxStart`]): a base that holds a radical, a fraction or an overbar is one,
/// and a base that ends in delimiters is one when they grow. A script, an accent or an underbar
/// is none, whatever it holds: an underbar leaves its base's glyphs to the scripts.
fn box_start(doc: &Document, node: NodeId) -> Option<ScriptMark> {
    let base = doc.child(node, M, "e")?;
    let structures: Vec<(&str, NodeId)> = doc
        .child_elements(base)
        .filter_map(|child| {
            let name = doc.element(child).map_or("", |e| e.name.local);
            (doc.is(child, M, name) && !name.ends_with("Pr")).then_some((name, child))
        })
        .collect();
    let boxes = |&(name, child): &(&str, NodeId)| match name {
        "rad" | "f" => true,
        "bar" => overbar(doc, child),
        _ => false,
    };
    if structures.iter().any(boxes) {
        Some(ScriptMark::BoxStart { delimited: false })
    } else {
        (structures.last().map(|&(name, _)| name) == Some("d"))
            .then_some(ScriptMark::BoxStart { delimited: true })
    }
}

/// Whether the bar structure `node` draws its bar over its base (`m:pos` `top`).
fn overbar(doc: &Document, node: NodeId) -> bool {
    doc.child(node, M, "barPr")
        .and_then(|props| doc.child(props, M, "pos"))
        .and_then(|pos| doc.attribute(pos, Some(M), "val"))
        == Some("top")
}

/// The marks of [`ScriptMark`] that the scripts of [`scripts`] lie between: those of the
/// scripts of a base, which keep the drops from it when it is a box (`boxed`), or those of the
/// limits of an n-ary operator inside a line, which take the drops from the operator's ink when
/// `drops` is set.
#[derive(Clone, Copy)]
enum Marks {
    Base { boxed: bool },
    Operator { drops: bool },
}

/// A subscript and a superscript after their base: stacked when both are there, so that both
/// start at one place and they take the room of the wider one, with the properties of the
/// structure's settings (`settings`), between marks of [`ScriptMark`] (`marks`). The scripts
/// of a base, as a sub-superscript's are, start each by the base's corners and leave a space
/// after them, and they are `followed` when more of their argument comes after their
/// structure; the limits of an n-ary operator inside a line move by the operator's ink or
/// apart.
fn scripts(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    (sub, sup): (Option<NodeId>, Option<NodeId>),
    (script, marks, followed): (MathScript, Marks, bool),
    runs: &mut Vec<Run>,
) {
    let stacked = sub.is_some() && sup.is_some();
    let mark = stack_mark(reader, settings, script);
    let script_mark = structure_mark(reader, settings, script);
    let script_mark = |mark: ScriptMark| script_mark(Content::Scripts(mark));
    let step = steps_in(reader, settings, script);
    runs.push(script_mark(match marks {
        Marks::Operator { drops } => ScriptMark::Operator { stacked, drops },
        Marks::Base { boxed } => ScriptMark::Base {
            stacked,
            followed,
            boxed,
        },
    }));
    if stacked {
        runs.push(mark(StackMark::Start {
            bar: None,
            centered: false,
        }));
    }
    if let Some(sub) = sub {
        runs.push(script_mark(ScriptMark::Start(ScriptSide::Sub)));
        walk(reader, sub, step(MathStep::Subscript), runs);
        runs.push(script_mark(ScriptMark::End));
    }
    if stacked {
        runs.push(mark(StackMark::Middle));
    }
    let upper = if stacked {
        MathStep::SuperscriptBesideSubscript
    } else {
        MathStep::Superscript
    };
    if let Some(sup) = sup {
        runs.push(script_mark(ScriptMark::Start(ScriptSide::Sup)));
        walk(reader, sup, step(upper), runs);
        runs.push(script_mark(ScriptMark::End));
    }
    if stacked {
        runs.push(mark(StackMark::End));
    }
    runs.push(script_mark(ScriptMark::After));
}

/// A superscript (`m:sSup`), a subscript (`m:sSub`) or a pre-sub-superscript (`m:sPre`): its
/// base (`m:e`) as it is, and its scripts one step in, in the order of the document. The script
/// of a superscript or a subscript lies between marks of [`ScriptMark`] that start it by the
/// base's corners and leave a space after it; those of a pre-sub-superscript have none. The
/// script is `followed` when more of its argument comes after the structure.
fn script_structure(
    reader: &mut PartReader,
    node: NodeId,
    (script, rest): (MathScript, &[NodeId]),
    runs: &mut Vec<Run>,
) {
    let doc = reader.doc;
    let followed = followed(doc, rest);
    let local = doc.element(node).map_or("", |e| e.name.local);
    let attached = matches!(local, "sSub" | "sSup");
    let settings = doc.child(node, M, &format!("{local}Pr"));
    let upper = if doc.child(node, M, "sub").is_some() {
        MathStep::SuperscriptBesideSubscript
    } else {
        MathStep::Superscript
    };
    let size = control_size(reader, settings);
    let start = box_start(doc, node).filter(|_| attached);
    let boxed = start.is_some();
    let mark = structure_mark(reader, settings, script);
    let marks = |marks: [ScriptMark; 2], runs: &mut Vec<Run>| {
        if attached {
            runs.extend(marks.map(|m| mark(Content::Scripts(m))));
        }
    };
    for child in doc.child_elements(node) {
        let (script_side, step) = if doc.is(child, M, "sup") {
            (ScriptSide::Sup, upper)
        } else if doc.is(child, M, "sub") {
            (ScriptSide::Sub, MathStep::Subscript)
        } else {
            if doc.is(child, M, "e") {
                if let Some(start) = start {
                    runs.push(mark(Content::Scripts(start)));
                }
                walk(reader, child, script, runs);
            }
            continue;
        };
        marks(
            [
                ScriptMark::Base {
                    stacked: false,
                    followed,
                    boxed,
                },
                ScriptMark::Start(script_side),
            ],
            runs,
        );
        walk(reader, child, script.inside(step, size), runs);
        marks([ScriptMark::End, ScriptMark::After], runs);
    }
    fraction_space_after_base(reader, (node, settings), (script, rest), runs);
}

/// Whether `rest`, the elements after a structure in its argument, draw something: a math run
/// with text or a structure of the math namespace, not a properties element.
fn followed(doc: &Document, rest: &[NodeId]) -> bool {
    rest.iter().any(|&node| {
        let name = doc.element(node).map_or("", |e| e.name.local);
        if !doc.is(node, M, name) || name.ends_with("Pr") {
            return false;
        }
        name != "r"
            || doc
                .child_elements(node)
                .any(|t| doc.is(t, M, "t") && !doc.text_content(t).is_empty())
    })
}

/// The size in half-points that the control properties (`m:ctrlPr`) among a structure's
/// settings `settings` give, if any. A part one step in from a structure takes it
/// (`MathScript::inside`), so that the structure shifts its parts at that size.
fn control_size(reader: &mut PartReader, settings: Option<NodeId>) -> Option<i64> {
    let doc = reader.doc;
    settings
        .and_then(|p| doc.child(p, M, "ctrlPr"))
        .and_then(|c| doc.child(c, W, "rPr"))
        .and_then(|rpr| RunProps::read(reader, rpr).size)
}

/// The script of a part one step in from a structure, for each step: `script` inside at the
/// size that the control properties among the structure's settings `settings` give
/// ([`control_size`]).
fn steps_in(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    script: MathScript,
) -> impl Fn(MathStep) -> MathScript + use<> {
    let size = control_size(reader, settings);
    move |step| script.inside(step, size)
}

/// The runs of the marks of a stack, with the properties of the structure's settings
/// (`m:ctrlPr` in `settings`) at the size of `script`.
fn stack_mark(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    script: MathScript,
) -> impl Fn(StackMark) -> Run + use<> {
    let mark = structure_mark(reader, settings, script);
    move |stack| mark(Content::Stack(stack))
}

/// The runs of the marks of a structure, each a run of one mark, with the properties of the
/// structure's settings (`m:ctrlPr` in `settings`) at the size of `script`.
fn structure_mark(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    script: MathScript,
) -> impl Fn(Content) -> Run + use<> {
    let props = control_props(reader, settings, script);
    move |mark| Run {
        style: None,
        props: props.clone(),
        content: vec![mark],
        revisions: Default::default(),
        starts_buffer: false,
        buffer_only: crate::body::BufferOnly::default(),
        record: RunRecord::default(),
        code_format: None,
        links: Vec::new(),
    }
}

/// The properties of a structure's settings (`m:ctrlPr` in `settings`), in the math font at
/// the size of `script`. A structure inside an outermost structure whose settings give a size
/// takes that size, whatever its own settings give.
fn control_props(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    script: MathScript,
) -> RunProps {
    let doc = reader.doc;
    let mut props = settings
        .and_then(|p| doc.child(p, M, "ctrlPr"))
        .and_then(|c| doc.child(c, W, "rPr"))
        .map_or_default(|rpr| RunProps::read(reader, rpr));
    props.size = script.outermost_size().or(props.size);
    props.apply(&math_props(script));
    props
}

/// The run of a display's n-ary operator, drawn with the larger variant of its glyph, with
/// the properties of its structure's settings (`m:ctrlPr` in `settings`), the properties of
/// the structure's control character (ECMA-376 Part 1, 22.1).
fn large_operator(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    operator: &str,
    script: MathScript,
) -> Run {
    let mut run = control_symbol(reader, settings, operator, script);
    run.props.math_script = Some(script.without_outermost().large());
    run
}

/// A run of `text` that a structure draws itself, such as an n-ary operator or the thin space
/// before it or its element, with the properties of the structure's settings (`m:ctrlPr` in
/// `settings`), so at their size.
fn control_symbol(
    reader: &mut PartReader,
    settings: Option<NodeId>,
    text: &str,
    script: MathScript,
) -> Run {
    Run {
        style: None,
        props: control_props(reader, settings, script),
        content: vec![Content::Text(text.to_owned())],
        revisions: Default::default(),
        starts_buffer: false,
        buffer_only: crate::body::BufferOnly::default(),
        record: RunRecord::default(),
        code_format: None,
        links: Vec::new(),
    }
}

/// Marks a math run (without `m:nor`) with [`RunProps::math`]. When the run names neither
/// Latin font slot (`w:ascii`, `w:hAnsi`), fills both with [`MATH_FONT`] so paragraph and
/// document defaults do not cascade into it; when the run names at least one Latin slot, any
/// omitted sibling slot stays `None` so it inherits from paragraph or document defaults. Also
/// carries the bold and italic of `m:sty` onto runs that can draw in a non-math font.
fn apply_math_run_font(props: &mut RunProps, style: LetterStyle) {
    let default = || FontRef::Name(MATH_FONT.to_owned());
    let own_other = |slot: &Option<FontRef>| {
        slot.as_ref().is_some_and(
            |font| !matches!(font, FontRef::Name(name) if name.eq_ignore_ascii_case(MATH_FONT)),
        )
    };
    let has_slot = props.font_ascii.is_some() || props.font_hansi.is_some();
    if !has_slot {
        props.font_ascii = Some(default());
        props.font_hansi = Some(default());
    }
    let may_use_other = own_other(&props.font_ascii)
        || own_other(&props.font_hansi)
        || (has_slot && (props.font_ascii.is_none() || props.font_hansi.is_none()));
    props.math = Some(true);
    if may_use_other {
        if matches!(style, LetterStyle::Bold | LetterStyle::BoldItalic) {
            props.bold = Some(true);
        }
        if matches!(style, LetterStyle::Italic | LetterStyle::BoldItalic) {
            props.italic = Some(true);
        }
    }
}

/// The properties that every math run but normal text takes: the math font, and the mark of
/// text of an equation ([`RunProps::math`]), which keeps its italic from the face.
fn math_props(script: MathScript) -> RunProps {
    let font = FontRef::Name(MATH_FONT.to_owned());
    RunProps {
        font_ascii: Some(font.clone()),
        font_hansi: Some(font),
        math_script: in_script(script),
        math: Some(true),
        ..RunProps::default()
    }
}

/// The scripts of a run for its properties: `None` outside every script.
fn in_script(script: MathScript) -> Option<MathScript> {
    (script.depth() > 0).then_some(script.without_outermost())
}

fn text_run(content: Content, script: MathScript) -> Run {
    Run {
        style: None,
        props: math_props(script),
        content: vec![content],
        revisions: Default::default(),
        starts_buffer: false,
        buffer_only: crate::body::BufferOnly::default(),
        record: RunRecord::default(),
        code_format: None,
        links: Vec::new(),
    }
}

fn symbol(text: &str, script: MathScript) -> Run {
    text_run(Content::Text(text.to_owned()), script)
}

/// A math run (`m:r`): its text in the math font, with mathematical italic letters unless it
/// is plain (`m:sty` `p`) or normal text (`m:nor`), and operators spaced, after an operand when
/// `ends.0` and before more of its part when `ends.1`.
fn math_run(
    reader: &mut PartReader,
    node: NodeId,
    script: MathScript,
    ends: (bool, bool),
) -> Option<Run> {
    let doc = reader.doc;
    let text: String = doc
        .child_elements(node)
        .filter(|t| doc.is(*t, M, "t"))
        .map(|t| doc.text_content(t))
        .collect();
    if text.is_empty() {
        return None;
    }
    let math = doc.child(node, M, "rPr");
    let normal = math.and_then(|p| doc.child(p, M, "nor")).is_some();
    let style = math
        .and_then(|p| doc.child(p, M, "sty"))
        .and_then(|s| reader.enumeration_or(s, (Some(M), "val"), LETTER_STYLE, "p"))
        .unwrap_or(LetterStyle::Italic);
    let mut props = doc
        .child(node, W, "rPr")
        .map_or_default(|rpr| RunProps::read(reader, rpr));
    if normal {
        props.math = Some(false);
    } else {
        apply_math_run_font(&mut props, style);
    }
    if script.depth() > 0 {
        props.math_script = Some(script.without_outermost());
    }
    let shown = if normal {
        text
    } else {
        styled(&text, style, ends, script)
    };
    Some(Run {
        style: None,
        props,
        content: vec![Content::Text(shown)],
        revisions: Default::default(),
        starts_buffer: false,
        buffer_only: crate::body::BufferOnly::default(),
        record: RunRecord::default(),
        code_format: None,
        links: Vec::new(),
    })
}

/// The space on each side of the operator `ch` between two operands in the part `script`: none
/// in script and script-script style, which scripts, limits and the parts of a fraction in a
/// line take, and else the space of a relation or of a binary operator.
fn operator_space(script: MathScript, ch: char) -> &'static [char] {
    if script.style() >= MathStyle::Script {
        &[]
    } else if relation(ch) {
        &RELATION_SPACE
    } else {
        &[OPERATOR_SPACE]
    }
}

/// The space after the operator `ch` between two operands in the part `script`: the space of
/// [`operator_space`], which ends with an operator break space, where the line may break, at
/// the top level of an equation in a line.
fn space_after_operator(script: MathScript, ch: char) -> &'static [char] {
    let space = operator_space(script, ch);
    if space.is_empty() || script.is_display() || !script.in_no_structure() {
        space
    } else if relation(ch) {
        &[HAIR_SPACE, OPERATOR_BREAK_SPACE]
    } else {
        &[OPERATOR_BREAK_SPACE]
    }
}

/// The text of a math run in its math style, in the part `script`, with the space of
/// [`operator_space`] before and of [`space_after_operator`] after operators that stand
/// between two operands: after an operand of the run, or at the run's start when the equation
/// has an operand before the run (`operand`). A sign after another operator or after an opening
/// delimiter of the run is unary; a binary operator or a relation there keeps its space after it
/// when more of the run, or of its part after the run (`followed`), comes after it.
fn styled(
    text: &str,
    style: LetterStyle,
    (operand, followed): (bool, bool),
    script: MathScript,
) -> String {
    let chars: Vec<char> = text.chars().map(shown).collect();
    let mut out = String::new();
    let mut after_operand = operand;
    for (index, &ch) in chars.iter().enumerate() {
        let next = chars.get(index + 1).copied();
        match operator_class(ch) {
            Some(class) if after_operand => between(&mut out, script, (ch, class), next),
            Some(OperatorClass::Binary | OperatorClass::Relation) => {
                leading(&mut out, script, ch, next.is_some() || followed);
            }
            _ => operand_char(&mut out, (style, script), &chars, index, after_operand),
        }
        if ch != BAR {
            after_operand = ends_operand(ch);
        }
    }
    out
}

/// The character that Word shows for `ch` in an equation: the asterisk operator for an
/// asterisk, the minus sign for a hyphen and the prime for an apostrophe.
fn shown(ch: char) -> char {
    match ch {
        '*' => '\u{2217}',
        '-' => '\u{2212}',
        '\'' => PRIME,
        other => other,
    }
}

/// The multiplication sign, after which a line does not break where it has no operand before
/// it.
const HELD_LEADING: char = '\u{00D7}';

/// Writes the binary operator or relation `ch` that has no operand before it, with its space
/// after it when something comes after it in its part (`more`): the space of
/// [`space_after_operator`], where the line may break, and a no-break space after
/// [`HELD_LEADING`].
fn leading(out: &mut String, script: MathScript, ch: char, more: bool) {
    out.push(ch);
    if !more {
        return;
    }
    if ch == HELD_LEADING {
        out.extend(operator_space(script, ch));
    } else {
        out.extend(space_after_operator(script, ch));
    }
}

/// Writes the operator `ch` of `class` that stands between two operands, before the character
/// `next` of its run, with its spaces: before another binary operator or relation, none after
/// it, and a sign before a relation none at all.
fn between(
    out: &mut String,
    script: MathScript,
    (ch, class): (char, OperatorClass),
    next: Option<char>,
) {
    let pair = next.is_some_and(leads);
    if !(class == OperatorClass::Sign && next.is_some_and(relation)) {
        out.extend(operator_space(script, ch));
    }
    out.push(ch);
    if !pair {
        out.extend(space_after_operator(script, ch));
    }
}

/// Whether `ch` is a binary operator or a relation, which keeps its space after it where no
/// operand stands before it.
fn leads(ch: char) -> bool {
    matches!(
        operator_class(ch),
        Some(OperatorClass::Binary | OperatorClass::Relation)
    )
}

/// The midline and the horizontal ellipsis, which take a thin space on each side between two
/// operands.
const ELLIPSES: [char; 2] = ['\u{22EF}', '\u{2026}'];

/// Writes the character at `index` of a run's `chars`, which is no operator between two
/// operands, in `style`, with a thin space after a punctuation mark, and outside script style
/// around an ellipsis: before it after an operand that is no punctuation mark, and after it
/// before a character that is no operator.
fn operand_char(
    out: &mut String,
    (style, script): (LetterStyle, MathScript),
    chars: &[char],
    index: usize,
    after_operand: bool,
) {
    let Some(&ch) = chars.get(index) else {
        return;
    };
    let ellipsis = ELLIPSES.contains(&ch) && script.style() < MathStyle::Script;
    let punctuation_before = index
        .checked_sub(1)
        .and_then(|before| chars.get(before))
        .is_some_and(|c| SPACED_MARKS.contains(c));
    if ellipsis && after_operand && !punctuation_before {
        out.push(THIN_SPACE);
    }
    out.push(letter(ch, style));
    let operand_after = chars
        .get(index + 1)
        .is_some_and(|&next| next != ' ' && !operator(next));
    if (ellipsis && operand_after) || punctuation_space(script, chars, index) {
        out.push(THIN_SPACE);
    }
}

/// Whether the character at `index` of a run's `chars` is a punctuation mark of
/// [`SPACED_MARKS`] that takes a thin space after it, 341 units of Cambria Math where 3/18 em
/// is 341.33: outside script style, before another character of the run that is not a space,
/// and not a decimal mark.
fn punctuation_space(script: MathScript, chars: &[char], index: usize) -> bool {
    let (Some(&ch), Some(&next)) = (chars.get(index), chars.get(index + 1)) else {
        return false;
    };
    if script.style() >= MathStyle::Script || !SPACED_MARKS.contains(&ch) || next == ' ' {
        return false;
    }
    let before = index.checked_sub(1).and_then(|before| chars.get(before));
    !decimal(before.copied(), ch, next)
}

/// Whether `ch` is an operator, which Word spaces between two operands.
fn operator(ch: char) -> bool {
    operator_class(ch).is_some()
}

/// Whether an operator is a relation, such as an equals sign, an inequality or an arrow.
fn relation(ch: char) -> bool {
    operator_class(ch) == Some(OperatorClass::Relation)
}

/// A letter in a math run's style (`m:sty`): italic, bold, bold italic or plain, from the
/// Mathematical Alphanumeric Symbols block, Greek letters by [`greek`]. Other characters stay as
/// they are.
fn letter(ch: char, style: LetterStyle) -> char {
    if let Some(greek) = greek(ch, style) {
        return greek;
    }
    let offset = |base: char, first: char| {
        char::from_u32(u32::from(base) + (u32::from(ch) - u32::from(first))).unwrap_or(ch)
    };
    match (style, ch) {
        (LetterStyle::Bold, 'a'..='z') => offset('\u{1D41A}', 'a'),
        (LetterStyle::Bold, 'A'..='Z') => offset('\u{1D400}', 'A'),
        (LetterStyle::Bold | LetterStyle::BoldItalic, '0'..='9') => offset('\u{1D7CE}', '0'),
        (LetterStyle::BoldItalic, 'a'..='z') => offset('\u{1D482}', 'a'),
        (LetterStyle::BoldItalic, 'A'..='Z') => offset('\u{1D468}', 'A'),
        // The italic h is the Planck constant, which has its own place.
        (LetterStyle::Italic, 'h') => '\u{210E}',
        (LetterStyle::Italic, 'a'..='z') => offset('\u{1D44E}', 'a'),
        (LetterStyle::Italic, 'A'..='Z') => offset('\u{1D434}', 'A'),
        _ => ch,
    }
}

/// The variant Greek letters in the order of their mathematical forms: epsilon, theta, kappa,
/// phi, rho and pi.
const GREEK_VARIANTS: [char; 6] = [
    '\u{03F5}', '\u{03D1}', '\u{03F0}', '\u{03D5}', '\u{03F1}', '\u{03D6}',
];

/// The first character of each run of Greek forms of one style in the Mathematical
/// Alphanumeric Symbols block: the capitals from alpha, the nabla, the small letters from alpha
/// with the final sigma, the partial differential, and the variants in the order of
/// [`GREEK_VARIANTS`].
struct GreekForms {
    capitals: char,
    nabla: char,
    small: char,
    partial: char,
    variants: char,
}

/// The bold Greek forms.
const BOLD_GREEK: GreekForms = GreekForms {
    capitals: '\u{1D6A8}',
    nabla: '\u{1D6C1}',
    small: '\u{1D6C2}',
    partial: '\u{1D6DB}',
    variants: '\u{1D6DC}',
};

/// The italic Greek forms.
const ITALIC_GREEK: GreekForms = GreekForms {
    capitals: '\u{1D6E2}',
    nabla: '\u{1D6FB}',
    small: '\u{1D6FC}',
    partial: '\u{1D715}',
    variants: '\u{1D716}',
};

/// The bold italic Greek forms.
const BOLD_ITALIC_GREEK: GreekForms = GreekForms {
    capitals: '\u{1D71C}',
    nabla: '\u{1D735}',
    small: '\u{1D736}',
    partial: '\u{1D74F}',
    variants: '\u{1D750}',
};

/// A Greek letter, the nabla or the partial differential in a math run's style, if `ch` is one
/// and the style is not plain.
fn greek(ch: char, style: LetterStyle) -> Option<char> {
    let forms = match style {
        LetterStyle::Plain => return None,
        LetterStyle::Bold => &BOLD_GREEK,
        LetterStyle::Italic => &ITALIC_GREEK,
        LetterStyle::BoldItalic => &BOLD_ITALIC_GREEK,
    };
    let after = |first: char, steps: u32| char::from_u32(u32::from(first) + steps);
    let from = |first: char, start: char| after(first, u32::from(ch) - u32::from(start));
    match ch {
        '\u{0391}'..='\u{03A1}' | '\u{03A3}'..='\u{03A9}' => from(forms.capitals, '\u{0391}'),
        '\u{2207}' => Some(forms.nabla),
        '\u{03B1}'..='\u{03C9}' => from(forms.small, '\u{03B1}'),
        '\u{2202}' => Some(forms.partial),
        _ => {
            let place = GREEK_VARIANTS.iter().position(|&v| v == ch)?;
            after(forms.variants, u32::try_from(place).ok()?)
        }
    }
}

/// The style of the letters of a math run (`m:sty`).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum LetterStyle {
    /// Plain (`p`).
    Plain,
    /// Bold (`b`).
    Bold,
    /// Italic (`i`), the style of a run without `m:sty`.
    Italic,
    /// Bold italic (`bi`).
    BoldItalic,
}

/// `ST_Style`, the style of a math run's letters (`m:sty`): each name is drawn. Text outside
/// the type reads as `p`, plain, while a missing style is italic.
const LETTER_STYLE: &Values<LetterStyle> = &Values::new(&[
    own("p", LetterStyle::Plain),
    own("b", LetterStyle::Bold),
    own("i", LetterStyle::Italic),
    own("bi", LetterStyle::BoldItalic),
]);

#[cfg(test)]
mod tests;