kakemono 0.18.0

Convert PDF, Word and EPUB documents to HTML, Markdown, EPUB, LaTeX and JSON in Rust
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
//! Rows of a column -> blocks: paragraphs, display equations, footnotes.
//!
//! Each leaf of the reading order (a column piece) is turned into blocks in
//! four steps: its rows are gathered (tiny orphan rows joined to their
//! neighbours), each row is classified as text, equation or float by a
//! sequence of rules, the footnote area at the bottom is found, and the text
//! rows are grouped into paragraphs.

use super::lines::{LinesConfig, merge_row};
use super::order::{ItemRef, Leaf};
use super::page::{DocStats, PageData};
use crate::backend::FontInfo;
use crate::common::geom::Rect;
use crate::model::Line;
use crate::model::Loc;
use regex::Regex;
use std::sync::LazyLock;

/// A footnote numbered on the baseline ("1. Since the publication ..."),
/// as in IEEE journals.
static NUMBERED_NOTE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\d{1,2}\.\s+\S").unwrap());
/// A note without a mark that conferences print at the foot of the first
/// page ("36th Conference on Neural Information Processing Systems
/// (NeurIPS 2022).").
static VENUE_NOTE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^\d{1,2}(?:st|nd|rd|th)\s+(?:[A-Z][\w-]*\s+){0,3}(?:Conference|Workshop|Symposium)\b").unwrap()
});
/// An equation number at the right margin: "(3)", "(A.2)", "(4.1b)".
static EQNO: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\((?:[A-Z]\.?)?\d+(?:\.\d+)*[a-z]?\)$").unwrap());
/// A bullet at the start of a line.
pub static BULLET: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[•◦▪■–∗⋆·‣▶►○●◆\-]\s").unwrap());
/// An enumeration label at the start of a line.
pub static NUM_LABEL: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:\(\d{1,2}\)|\([a-z]\)|\([ivx]{1,4}\)|\d{1,2}[.)]|[a-z]\))\s").unwrap());
/// A bibliography label at the start of a line ("[12] "): the next entry of
/// a reference list, also without a "References" heading (APS papers).
pub static BRACKET_LABEL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\[\d{1,3}\]\s").unwrap());
/// Any list item label at the start of a line: a bullet or an enumeration
/// label (the union of [`BULLET`] and [`NUM_LABEL`]).
pub static LIST_LABEL: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"^(?:[•◦▪■–∗⋆·‣▶►○●◆\-]\s|\(\d{1,2}\)\s|\([a-z]\)\s|\([ivx]{1,4}\)\s|\d{1,2}[.)]\s|[a-z]\)\s)").unwrap()
});

/// The equation rules for rows without an equation number, tried in order.
/// Pieces of big brackets, parentheses and braces (U+239B to U+23AD:
/// ⎛⎜⎝⎞⎟⎠⎡⎢⎣⎤⎥⎦⎧⎨⎩⎪⎫⎬⎭), which TeX stacks to make the tall delimiters of a display.
const BRACKET_PIECES: [char; 19] = [
    '\u{239B}', '\u{239C}', '\u{239D}', '\u{239E}', '\u{239F}', '\u{23A0}', '\u{23A1}', '\u{23A2}', '\u{23A3}',
    '\u{23A4}', '\u{23A5}', '\u{23A6}', '\u{23A7}', '\u{23A8}', '\u{23A9}', '\u{23AA}', '\u{23AB}', '\u{23AC}',
    '\u{23AD}',
];

const EQUATION_RULES: [EquationRule; 6] = [
    displayed_formula,
    symbol_row,
    centred_relation,
    stacked_formula,
    centred_stacked_relation,
    drawn_bracket,
];

/// The paragraph break rules, tried in order (centred groups never break).
const PARAGRAPH_RULES: [ParagraphRule; 4] = [
    starts_with_marker,
    new_enumeration_item,
    follows_short_line,
    indent_changes,
];

/// Tuning parameters of block building. Part of [`LayoutConfig`](crate::config::LayoutConfig).
///
/// Lengths are in PDF points (`_pt`), in multiples of a font size (`_em`:
/// the body size for leaf-level measures, else the row's or line's own
/// size) or in multiples of the document's leading (`_leading`); `_ratio`
/// fields are fractions between 0 and 1.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct BlocksConfig {
    // --- gathering rows ---
    /// A row with at most this many characters may be an orphan (a piece of
    /// inline math split off its line); the row it joins has more.
    pub orphan_max_chars: usize,
    /// An orphan row is narrower than this many body sizes.
    pub orphan_max_width_em: f32,
    /// With at least this many text rows, the right edge of the leaf is a
    /// high percentile of the row ends (robust against a few overlong
    /// rows); with fewer, it is the rightmost end.
    pub right_percentile_min_rows: usize,
    /// The percentile of row ends taken as the right edge of the leaf.
    pub right_edge_percentile_ratio: f32,
    /// A row ends at the right edge of the leaf if within this (points) ...
    pub justified_edge_tol_pt: f32,
    /// ... and the text of the leaf is justified when at least this share
    /// (0-1) of its rows do.
    pub justified_min_ratio: f32,

    // --- equation rows ---
    /// A row is isolated (white space around it, as around a displayed
    /// formula) when the ink gaps to the rows above and below exceed this
    /// many body sizes.
    pub isolation_gap_em: f32,
    /// An equation number ends within this many body sizes of the leaf's
    /// right edge.
    pub eqno_margin_em: f32,
    /// A row is centred when its centre is within this fraction of the
    /// leaf width of the leaf's centre ...
    pub centered_tol_ratio: f32,
    /// ... (but at least this) ...
    pub centered_min_tol_pt: f32,
    /// ... and it is indented by at least this many sizes on both sides.
    pub centered_min_margin_em: f32,
    /// A row spans several baselines (a fraction, a stacked formula) when
    /// its baselines differ by more than this many sizes.
    pub multi_baseline_em: f32,
    /// A row with an equation number is an equation when less than this
    /// fraction of its characters are prose.
    pub numbered_max_prose_ratio: f32,
    /// A displayed formula has at least this fraction of math characters...
    pub display_min_math_ratio: f32,
    /// ... at most this fraction of prose ...
    pub display_max_prose_ratio: f32,
    /// ... and is centred or indented by at least this many sizes.
    pub display_min_indent_em: f32,
    /// A row of almost nothing but symbols has at least this fraction of
    /// math characters ...
    pub symbolic_min_math_ratio: f32,
    /// ... at most this fraction of prose ...
    pub symbolic_max_prose_ratio: f32,
    /// ... at least this many characters ...
    pub symbolic_min_chars: usize,
    /// ... and is indented by at least this many sizes (or isolated).
    pub symbolic_min_indent_em: f32,
    /// A centred, isolated formula made mostly of operator names has at
    /// least this fraction of math characters ...
    pub operator_min_math_ratio: f32,
    /// ... and at most this fraction of prose (plus a relation sign).
    pub operator_max_prose_ratio: f32,
    /// A row spanning several baselines is a formula with at least this
    /// fraction of math characters ...
    pub stacked_min_math_ratio: f32,
    /// ... at most this fraction of prose ...
    pub stacked_max_prose_ratio: f32,
    /// ... and an indent of at least this many sizes on both sides.
    pub stacked_min_margin_em: f32,
    /// A weak equation candidate with a relation sign is indented by at
    /// least this many sizes on both sides ...
    pub weak_min_margin_em: f32,
    /// ... has at most this many characters ...
    pub weak_max_chars: usize,
    /// ... and at most this fraction of prose.
    pub weak_max_prose_ratio: f32,
    /// An indented row of at most this many characters and no prose (a
    /// numerator such as "1", a limit) is a weak candidate too.
    pub weak_tiny_max_chars: usize,
    /// A weak candidate indented by less than this many sizes, right below
    /// a prose row, is the wrapped end of that paragraph: it is not
    /// promoted.
    pub weak_flush_max_indent_em: f32,
    /// A row that is flush left (see `weak_flush_max_indent_em`) and ends
    /// less than this many sizes from the right edge fills the column, as
    /// lines of a paragraph do: with enough prose (see the next two fields),
    /// it is no weak candidate.
    pub weak_full_max_slack_em: f32,
    /// ... with at least this many prose characters,
    pub weak_full_min_prose_chars: f32,
    /// ... or with some prose, on one baseline and at least this many
    /// characters long (a short line with fractions above and below it,
    /// like `where μ = (a)/(b) x + (c)/(d) y`, spans the column too).
    pub weak_full_flat_min_chars: usize,
    /// Without a relation sign, a weak candidate has at least this fraction
    /// of math characters ...
    pub weak_min_math_ratio: f32,
    /// ... and at most this fraction of prose.
    pub weak_math_max_prose_ratio: f32,
    /// A weak candidate is promoted to an equation when its ink gap to an
    /// adjacent equation row is less than this many leadings.
    pub promote_max_gap_leading: f32,
    /// Adjacent equation rows closer than this many leadings are merged into
    /// one equation (unless both are numbered).
    pub merge_max_gap_leading: f32,
    /// An opening delimiter of an equation taller than this (em of its font
    /// size) encloses the rows beside it: the lines of a `cases` or of a
    /// matrix belong to the equation, even when one reads as text
    /// ("−x, otherwise").
    pub enclosing_min_height_em: f32,
    /// How far (points) an enclosed row may reach past the top or the bottom
    /// of the delimiter.
    pub enclosing_tolerance_pt: f32,
    /// A horizontal rule at most this thick (and at least
    /// `fraction_bar_min_width_pt` wide) next to an equation may be a
    /// fraction bar: a text row right above or below it, within its width,
    /// is the numerator or denominator of the equation.
    pub fraction_bar_max_thickness_pt: f32,
    /// Narrowest fraction bar.
    pub fraction_bar_min_width_pt: f32,
    /// Largest gap between a fraction bar and its numerator or
    /// denominator, in sizes of the row's font.
    pub fraction_part_max_gap_em: f32,
    /// A line of text holding the denominators of the fractions whose
    /// numerators were taken for an equation is a line of a paragraph (the
    /// fractions are inline) when it has at least this many characters;
    /// a shorter one is the rest of the displayed formula.
    pub inline_fraction_min_chars: usize,
    /// A row without an equation number that has at least this many of the
    /// little words of sentences ([`SENTENCE_WORDS`]) is prose, however much
    /// math it holds (`For every a ∈ T, one has Γa ∈ T.`).
    pub sentence_min_words: usize,
    /// A text row right below or above a big operator (`∑`) of an
    /// equation, overlapping it, with a font at most this fraction of the
    /// equation's, is a limit of the operator.
    pub limit_max_size_ratio: f32,

    // --- footnotes ---
    /// Footnote text is at least this much smaller than the body size.
    pub footnote_size_drop_pt: f32,
    /// A footnote rule is at least this long ...
    pub footnote_rule_min_width_pt: f32,
    /// ... and at most this fraction of the leaf width ...
    pub footnote_rule_max_width_ratio: f32,
    /// ... (with the leaf counted as at least this wide) ...
    pub footnote_rule_min_leaf_pt: f32,
    /// ... and starts within this of the leaf's left edge (or is centred in
    /// the leaf within this).
    pub footnote_rule_align_pt: f32,
    /// Text rows starting less than this above the rule count as below it.
    pub footnote_rule_tol_pt: f32,
    /// A footnote rule may lie this far (points) above the leaf: the layout
    /// can put footnotes that run across the page, below a rule in a
    /// column, into a leaf of their own.
    pub footnote_rule_above_leaf_pt: f32,
    /// Below a footnote rule, text may be as large as the body text (ACM
    /// and IEEE styles set footnotes in the body size) if the first row
    /// starts with a footnote mark; it may exceed the body size by at most
    /// this much.
    pub footnote_same_size_max_excess_pt: f32,
    /// Without a rule, the footnote area is a trailing run of lines at
    /// least this much smaller than the body size ...
    pub footnote_run_size_drop_pt: f32,
    /// ... introduced by a footnote mark, more than this many leadings
    /// (scaled to the line's size) below the row above.
    pub footnote_gap_leading: f32,
    /// ... and ending below this fraction of the page height, or with no
    /// text below it: notes end the text of the page, so small marked text
    /// above other text (affiliations and an abstract in small type under
    /// the title) is not a footnote area.
    pub footnote_run_min_bottom_ratio: f32,

    // --- paragraphs ---
    /// The lines of a centred group have their centres within this of the
    /// median centre ...
    pub centered_group_tol_pt: f32,
    /// ... and at least one starts more than this right of the group's left
    /// edge (otherwise it is justified text).
    pub centered_group_min_offset_pt: f32,
    /// Width of the space before a word, in sizes, when testing whether the
    /// next word would have fit on the previous line.
    pub para_word_space_em: f32,
    /// A line ends short (ending its paragraph) when the next word plus a
    /// space would have fit before the group's right edge minus this.
    pub para_short_line_slack_pt: f32,
    /// A group of at least this many lines with few of them reaching its
    /// right edge is set ragged right (a letter quoted in a novel): its
    /// short lines do not end paragraphs unless they end a sentence.
    pub ragged_min_lines_count: usize,
    /// In ragged text, a line ending at most this many font sizes before the
    /// right edge is a full line of prose.
    pub ragged_line_max_gap_em: f32,
    /// A group of lines is prose (ragged text, or text in a document whose
    /// paragraphs are separated by space) when at least this share of its
    /// words start in lowercase.
    pub ragged_prose_min_lower_ratio: f32,
    /// The right edge of a paragraph is at most this far (points) beyond the
    /// right edge of the column's text, so that one line with a wide inline
    /// formula does not make every full line before it look short.
    pub para_right_overshoot_pt: f32,
    /// A numbered line starts a new item when it starts within this many
    /// sizes of the paragraph's first line.
    pub para_label_align_em: f32,
    /// A line starting more than this many sizes left or right of the
    /// paragraph's other continuation lines starts a new paragraph.
    pub para_indent_change_em: f32,
    /// A paragraph whose first glyph is at least this many times as large
    /// as its line opens with a drop cap: the lines set beside the cap are
    /// indented by its width, which does not start a new paragraph.
    pub drop_cap_min_size_ratio: f32,
    /// Two text rows belong to different blocks when their baseline gap
    /// exceeds this many expected leadings ...
    pub block_gap_leading: f32,
    /// ... plus this slack ...
    pub block_gap_slack_pt: f32,
    /// ... and their ink is more than this many sizes apart.
    pub block_ink_gap_em: f32,
    /// Two text rows whose sizes differ by more than this belong to
    /// different blocks.
    pub block_size_change_pt: f32,
    /// A change between bold and regular separates blocks only when both
    /// rows have more than this many characters ...
    pub bold_flip_min_chars: usize,
    /// ... and either the upper row is bold or the gap exceeds this many
    /// expected leadings.
    pub bold_flip_gap_leading: f32,
    /// A bold row that ends with a period, has at least two and at most this
    /// many words and is followed by regular text without extra space is a
    /// run-in head that filled its line ("**Performance stratified by
    /// syntactic divergence.** As discussed ..."), not a heading of its own.
    pub bold_run_in_max_words_count: usize,
    /// A row is bold when at least this fraction of its glyphs are bold.
    pub bold_dominant_ratio: f32,

    // --- margin notes ---
    /// A line at least this wide (a fraction of the page width) is a line
    /// of the main text of its page ...
    pub main_text_min_width_ratio: f32,
    /// ... and a block of text beside all of them, at most this wide, ...
    pub margin_note_max_width_ratio: f32,
    /// ... and set at most this size (a fraction of the body size), is a
    /// note in the margin (a book's sidenotes): it is set apart like a
    /// footnote, and does not cut the paragraph it stands beside.
    pub margin_note_max_size_ratio: f32,
    /// A page has margin notes only beside at least this many lines of
    /// main text.
    pub main_text_min_lines_count: usize,

    // --- parts of one equation ---
    /// Two equation blocks side by side, in the same column or in columns
    /// of a zone that holds nothing but parts of equations, whose boxes
    /// share at least this fraction of the height of the lower one ...
    pub equation_join_min_overlap_ratio: f32,
    /// ... and are at most this far apart (multiple of the body size) are
    /// two parts of one display that the reading order cut apart (a matrix
    /// wide enough to look like columns).
    pub equation_join_max_gap_em: f32,
    /// Equation blocks of different zones of the page whose boxes overlap
    /// or are at most this far apart (multiple of the body size) are parts
    /// of one display: the reading order cut a tall matrix into zones. So is
    /// a text block that holds pieces of a big bracket (⎛, ⎟, ⎠: rows of a
    /// matrix read as text) at most this far from an equation.
    pub equation_touch_max_gap_em: f32,
    /// A text block with at least this fraction of its area inside the box
    /// of an equation is a part of it (rows of a matrix read as text).
    pub equation_absorb_min_overlap_ratio: f32,
}

/// The default thresholds of block building.
const DEFAULT_CONFIG: BlocksConfig = BlocksConfig {
    orphan_max_chars: 4,
    orphan_max_width_em: 3.5,
    right_percentile_min_rows: 8,
    right_edge_percentile_ratio: 0.92,
    justified_edge_tol_pt: 1.5,
    justified_min_ratio: 0.4,
    isolation_gap_em: 0.55,
    eqno_margin_em: 2.5,
    centered_tol_ratio: 0.03,
    centered_min_tol_pt: 4.0,
    centered_min_margin_em: 1.2,
    multi_baseline_em: 0.25,
    numbered_max_prose_ratio: 0.6,
    display_min_math_ratio: 0.25,
    display_max_prose_ratio: 0.5,
    display_min_indent_em: 3.0,
    symbolic_min_math_ratio: 0.45,
    symbolic_max_prose_ratio: 0.15,
    symbolic_min_chars: 6,
    symbolic_min_indent_em: 1.0,
    operator_min_math_ratio: 0.08,
    operator_max_prose_ratio: 0.8,
    stacked_min_math_ratio: 0.3,
    stacked_max_prose_ratio: 0.3,
    stacked_min_margin_em: 1.0,
    weak_min_margin_em: 1.2,
    weak_max_chars: 110,
    weak_max_prose_ratio: 0.85,
    weak_tiny_max_chars: 3,
    weak_flush_max_indent_em: 0.5,
    weak_full_max_slack_em: 0.5,
    weak_full_min_prose_chars: 6.0,
    weak_full_flat_min_chars: 30,
    weak_min_math_ratio: 0.2,
    weak_math_max_prose_ratio: 0.3,
    promote_max_gap_leading: 0.9,
    merge_max_gap_leading: 0.9,
    enclosing_min_height_em: 1.8,
    enclosing_tolerance_pt: 1.0,
    fraction_bar_max_thickness_pt: 1.2,
    fraction_bar_min_width_pt: 2.0,
    fraction_part_max_gap_em: 0.6,
    inline_fraction_min_chars: 30,
    sentence_min_words: 4,
    limit_max_size_ratio: 0.85,
    footnote_size_drop_pt: 0.4,
    footnote_rule_min_width_pt: 20.0,
    footnote_rule_max_width_ratio: 0.62,
    footnote_rule_min_leaf_pt: 120.0,
    footnote_rule_align_pt: 8.0,
    footnote_rule_tol_pt: 2.0,
    footnote_rule_above_leaf_pt: 20.0,
    footnote_same_size_max_excess_pt: 0.3,
    footnote_run_size_drop_pt: 0.9,
    footnote_gap_leading: 1.25,
    footnote_run_min_bottom_ratio: 0.6,
    centered_group_tol_pt: 2.5,
    centered_group_min_offset_pt: 3.0,
    para_word_space_em: 0.25,
    para_short_line_slack_pt: 1.0,
    ragged_min_lines_count: 4,
    ragged_line_max_gap_em: 2.5,
    ragged_prose_min_lower_ratio: 0.6,
    para_right_overshoot_pt: 3.0,
    para_label_align_em: 0.6,
    para_indent_change_em: 0.6,
    drop_cap_min_size_ratio: 2.0,
    block_gap_leading: 1.25,
    block_gap_slack_pt: 1.5,
    block_ink_gap_em: 0.45,
    block_size_change_pt: 0.6,
    bold_flip_min_chars: 2,
    bold_flip_gap_leading: 1.1,
    bold_run_in_max_words_count: 12,
    bold_dominant_ratio: 0.95,
    main_text_min_width_ratio: 0.45,
    margin_note_max_width_ratio: 0.22,
    margin_note_max_size_ratio: 0.92,
    main_text_min_lines_count: 5,
    equation_join_min_overlap_ratio: 0.5,
    equation_join_max_gap_em: 3.0,
    equation_touch_max_gap_em: 0.5,
    equation_absorb_min_overlap_ratio: 0.8,
};

impl Default for BlocksConfig {
    fn default() -> Self {
        DEFAULT_CONFIG
    }
}

/// A block of running text: a paragraph, a list item, a heading.
#[derive(Debug, Clone)]
pub struct TextBlock {
    /// Its lines, top to bottom.
    pub lines: Vec<Line>,
    /// Where it is on the page.
    pub loc: Loc,
    /// Left edge of the surrounding text group.
    pub left: f32,
    /// Right edge of the surrounding text group.
    pub right: f32,
    /// The surrounding group is centred text.
    pub centered: bool,
    /// Baseline distance to the previous row of the leaf.
    pub gap_before: f32,
    /// Union of the line boxes.
    pub bbox: Rect,
}

/// A displayed equation.
#[derive(Debug, Clone)]
pub struct EquationBlock {
    /// The pieces of the equation, as lines.
    pub lines: Vec<Line>,
    /// Ink extent of the equation without its number.
    pub bbox: Rect,
    /// The equation number, e.g. "(3)".
    pub number: Option<String>,
    /// The line holding the equation number, if any.
    pub number_line: Option<Line>,
    /// Where it is on the page.
    pub loc: Loc,
}

/// A block of a leaf, in reading order.
#[derive(Debug, Clone)]
pub enum RawBlock {
    /// Running text.
    Text(TextBlock),
    /// A displayed equation.
    Equation(EquationBlock),
    /// The float with index `idx` on the page sits here.
    Float {
        /// Index of the float in the page's floats.
        idx: usize,
        /// Where it is on the page.
        loc: Loc,
    },
    /// A footnote.
    Footnote(TextBlock),
}

/// Character counts of a row used to tell formulas from prose.
struct RowStats {
    /// All characters.
    n_chars: usize,
    /// Characters in a math font or that are math symbols.
    math_chars: usize,
    /// Characters in runs of at least four letters (words).
    prose_chars: usize,
}

/// A row of a leaf after classification.
enum Row {
    /// A line of text (the row's lines merged).
    Text(Line),
    /// A displayed equation.
    Equation {
        /// Its pieces.
        lines: Vec<Line>,
        /// Its ink extent without the number.
        bbox: Rect,
        /// Its number, if any.
        number: Option<String>,
        /// The line holding the number.
        number_line: Option<Line>,
    },
    /// A float (index into the page's floats).
    Float(usize),
}

/// A row of a leaf as gathered from the reading order, before
/// classification.
struct RowDraft {
    /// The lines of the row.
    lines: Vec<Line>,
    /// The float in the row, if any.
    float: Option<usize>,
    /// Union of the line boxes.
    bbox: Rect,
}

/// A text row that is not an equation on its own but looks like part of
/// one: its lines and ink extent. It is promoted when it sits next to an
/// equation row.
/// A weak equation candidate: its lines, its ink, and whether it is flush
/// with the left edge of the leaf.
type WeakEquation = (Vec<Line>, Rect, bool);

/// The horizontal extent of the text of a leaf.
struct LeafExtent {
    /// Leftmost start of a text row.
    left: f32,
    /// Right edge of the text (a high percentile of the row ends).
    right: f32,
    /// `right - left`, at least 1.
    width: f32,
    /// The text is justified: many rows end at `right`.
    justified: bool,
    /// Centre between `left` and `right`.
    center_x: f32,
}

/// The measures of one row that the equation rules test.
struct RowFeatures {
    /// The row ends with an equation number.
    numbered: bool,
    /// Number of characters (without the number).
    n_chars: usize,
    /// Fraction of math characters.
    math_frac: f32,
    /// Fraction of prose characters.
    prose_frac: f32,
    /// Font size of the row (the largest, at least 1).
    em: f32,
    /// Distance from the leaf's left edge.
    left_indent: f32,
    /// Distance to the leaf's right edge.
    right_slack: f32,
    /// The row is centred in the leaf.
    centered: bool,
    /// There is white space above and below the row.
    isolated: bool,
    /// The row spans several baselines.
    multi: bool,
    /// The row contains a relation sign ("=", "≤", ...).
    has_relation: bool,
    /// The row starts with an operator or is a single function term
    /// ("P(A)"): a line of a display set in text letters.
    continues_display: bool,
    /// The row holds a piece of a tall bracket or brace (`⎡`, `⎪`): only a
    /// displayed matrix or `cases` draws one.
    has_bracket_piece: bool,
}

/// A rule of the equation classification: whether a row is a display
/// equation for one reason.
type EquationRule = fn(&RowFeatures, &BlocksConfig) -> bool;

/// A candidate line for the end of a paragraph, as the paragraph rules see
/// it.
struct ParagraphBreak<'a> {
    /// The paragraph so far (lines and gaps before them).
    para: &'a [(Line, f32)],
    /// The candidate next line.
    line: &'a Line,
    /// The text of `line`.
    text: &'a str,
    /// Right edge of the text group.
    right: f32,
    /// The group is in the footnote area.
    footnote: bool,
    /// The group is set ragged right (see [`is_ragged`]).
    ragged: bool,
    /// The group is prose (see [`is_prose`]) in a document that separates
    /// its paragraphs by space ([`DocStats::spaced_paragraphs`]).
    spaced_prose: bool,
}

/// A rule of the paragraph splitting: whether a line starts a new
/// paragraph for one reason.
type ParagraphRule = fn(&ParagraphBreak, &BlocksConfig) -> bool;

/// Everything the steps of [`build_blocks`] read.
#[derive(Clone, Copy)]
struct BlockContext<'a> {
    /// The page.
    page: &'a PageData,
    /// Document-wide font statistics.
    stats: &'a DocStats,
    /// The document's fonts.
    fonts: &'a [FontInfo],
    /// The thresholds.
    cfg: &'a BlocksConfig,
    /// Thresholds of line building, for rows merged into one line.
    lines_cfg: &'a LinesConfig,
    /// Right edge of the text of the leaf being built if it is justified
    /// (infinite otherwise or before it is measured): a line that sticks out past it (a wide inline formula)
    /// does not move the right edge of its paragraph.
    leaf_right: f32,
}

/// Turns the rows of every leaf of a page into blocks, in reading order:
/// text blocks (paragraphs, list items), display equations, floats, and the
/// footnotes at the bottom of a leaf.
pub fn build_blocks(
    page: &PageData,
    leaves: &[Leaf],
    stats: &DocStats,
    fonts: &[FontInfo],
    cfg: &BlocksConfig,
    lines_cfg: &LinesConfig,
) -> Vec<RawBlock> {
    let ctx = BlockContext {
        page,
        stats,
        fonts,
        cfg,
        lines_cfg,
        leaf_right: f32::INFINITY,
    };
    let mut out = Vec::new();
    for (leaf_idx, leaf) in leaves.iter().enumerate() {
        let loc = Loc {
            page: page.index,
            zone: leaf.zone,
            zone_cols: leaf.zone_cols,
            col: leaf.col,
            leaf: leaf_idx,
        };
        let mut drafts = gather_rows(page, leaf);
        join_orphan_rows(&mut drafts, stats, cfg);
        let extent = LeafExtent::measure(&drafts, leaf, cfg);
        let ctx = BlockContext {
            leaf_right: if extent.justified { extent.right } else { f32::INFINITY },
            ..ctx
        };
        let (mut rows, mut weak) = classify_rows(ctx, drafts, &extent);
        promote_weak_equations(&mut rows, &mut weak, stats, cfg);
        attach_stray_numbers(&mut rows, &extent, stats, cfg);
        let rows = merge_equation_rows(rows, stats, cfg);
        let bars = fraction_bars(page, cfg);
        let rows = inline_numerators(rows, &bars, ctx);
        let rows = absorb_enclosed_rows(rows, &bars, cfg);
        let fn_start = footnote_start(ctx, leaf, &rows, &extent);
        emit_blocks(ctx, rows, fn_start, loc, &mut out);
    }
    out
}

/// Turns the text blocks of the margin notes of a page into footnote
/// blocks: narrow blocks of small text (see
/// [`BlocksConfig::margin_note_max_size_ratio`]) that lie wholly beside the
/// lines of the main text, to the left or to the right, within their
/// height, and that are not headings (all bold). Set apart as notes, they
/// no longer read as paragraphs of the text, nor cut the paragraph they
/// stand beside. A page with few long lines of main text (two columns of
/// text) has no margin notes.
pub fn mark_margin_notes(
    blocks: &mut [RawBlock],
    page_width: f32,
    stats: &DocStats,
    fonts: &[FontInfo],
    cfg: &BlocksConfig,
) {
    let max_size = cfg.margin_note_max_size_ratio * stats.body_size;
    let main_lines: Vec<&Line> = blocks
        .iter()
        .filter_map(|block| match block {
            RawBlock::Text(text) => Some(text.lines.iter()),
            _ => None,
        })
        .flatten()
        .filter(|line| line.size > max_size && line.bbox.width() >= cfg.main_text_min_width_ratio * page_width)
        .collect();
    if main_lines.len() < cfg.main_text_min_lines_count {
        return;
    }
    let main = main_lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
    let bold = |line: &Line| fonts.get(usize::from(line.font)).is_some_and(|font| font.bold);
    for block in blocks.iter_mut() {
        let RawBlock::Text(text) = block else {
            continue;
        };
        let small = text.lines.iter().all(|line| line.size <= max_size);
        let narrow = text.bbox.width() <= cfg.margin_note_max_width_ratio * page_width;
        let beside =
            (text.bbox.x1 <= main.x0 || text.bbox.x0 >= main.x1) && text.bbox.y0 >= main.y0 && text.bbox.y1 <= main.y1;
        let heading = text.lines.iter().all(bold);
        if small && narrow && beside && !heading {
            *block = RawBlock::Footnote(text.clone());
        }
    }
}

/// Joins the parts of one displayed equation that the reading order cut
/// apart: equation blocks side by side (see
/// [`BlocksConfig::equation_join_min_overlap_ratio`]), and text blocks that
/// lie inside the box of an equation. The joined equation takes the place
/// of its first part in the reading order.
pub fn join_equation_parts(blocks: &mut Vec<RawBlock>, stats: &DocStats, cfg: &BlocksConfig) {
    let mut i = 0;
    while i < blocks.len() {
        let RawBlock::Equation(equation) = &blocks[i] else {
            i += 1;
            continue;
        };
        let (target, loc) = (equation.bbox, equation.loc);
        let math_zone = is_math_zone(blocks, loc.zone);
        let part =
            (0..blocks.len()).find(|&j| j != i && is_equation_part(&target, loc, math_zone, &blocks[j], stats, cfg));
        let Some(j) = part else {
            i += 1;
            continue;
        };
        let other = blocks.remove(j);
        let i_now = if j < i { i - 1 } else { i };
        if let RawBlock::Equation(equation) = &mut blocks[i_now] {
            match other {
                RawBlock::Equation(part) => {
                    equation.bbox = equation.bbox.union(&part.bbox);
                    equation.lines.extend(part.lines);
                    if equation.number.is_none() {
                        equation.number = part.number;
                        equation.number_line = part.number_line;
                    }
                }
                RawBlock::Text(part) => {
                    equation.bbox = equation.bbox.union(&part.bbox);
                    equation.lines.extend(part.lines);
                }
                _ => {}
            }
            equation
                .lines
                .sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
        }
        // Look again from the joined equation: it may have grown.
        i = i_now;
    }
}

/// Whether every block of zone `zone` of the page is an equation or a text
/// block made of pieces of math (see [`has_bracket_pieces`]): the zone was
/// cut out of the page by a display, whose columns are not columns of text.
fn is_math_zone(blocks: &[RawBlock], zone: usize) -> bool {
    blocks.iter().all(|block| match block {
        RawBlock::Equation(_) => true,
        RawBlock::Text(text) | RawBlock::Footnote(text) => text.loc.zone != zone || has_bracket_pieces(text),
        RawBlock::Float { loc, .. } => loc.zone != zone,
    })
}

/// Whether a text block holds pieces of a big bracket (⎛, ⎜, ⎝, ⎞, ⎟,
/// ⎠ and the like), which only ever make up a display.
fn has_bracket_pieces(text: &TextBlock) -> bool {
    text.lines
        .iter()
        .any(|line| line.glyphs.iter().any(|glyph| glyph.text.contains(BRACKET_PIECES)))
}

/// Whether `block` is a part of the equation whose box is `target` (at
/// `loc`): an equation beside it, level with it, in the same column (or
/// in another column of a zone of math, `math_zone`); an equation of
/// another zone that touches it; a text block inside it, or a text block
/// of bracket pieces that touches it.
fn is_equation_part(
    target: &Rect,
    loc: Loc,
    math_zone: bool,
    block: &RawBlock,
    stats: &DocStats,
    cfg: &BlocksConfig,
) -> bool {
    let touches = |bbox: &Rect| {
        let gap_x = (bbox.x0 - target.x1).max(target.x0 - bbox.x1);
        let gap_y = (bbox.y0 - target.y1).max(target.y0 - bbox.y1);
        let max_gap = cfg.equation_touch_max_gap_em * stats.body_size;
        gap_x <= max_gap && gap_y <= max_gap
    };
    match block {
        RawBlock::Equation(other) if other.loc.zone != loc.zone => touches(&other.bbox),
        RawBlock::Equation(other) if other.loc.zone == loc.zone && (other.loc.col == loc.col || math_zone) => {
            let bbox = other.bbox;
            let overlap = (target.y1.min(bbox.y1) - target.y0.max(bbox.y0)).max(0.0);
            let lower = target.height().min(bbox.height()).max(1.0);
            let gap = (bbox.x0 - target.x1).max(target.x0 - bbox.x1);
            overlap >= cfg.equation_join_min_overlap_ratio * lower
                && gap >= 0.0
                && gap <= cfg.equation_join_max_gap_em * stats.body_size
        }
        RawBlock::Text(text) => {
            let bbox = text.bbox;
            let width = (target.x1.min(bbox.x1) - target.x0.max(bbox.x0)).max(0.0);
            let height = (target.y1.min(bbox.y1) - target.y0.max(bbox.y0)).max(0.0);
            let area = (bbox.width() * bbox.height()).max(1.0);
            width * height >= cfg.equation_absorb_min_overlap_ratio * area
                || (has_bracket_pieces(text) && touches(&bbox))
        }
        _ => false,
    }
}

impl LeafExtent {
    /// Measures the text rows (rows without a float) of a leaf. The right
    /// edge falls back to the leaf's box when the percentile has no data.
    fn measure(drafts: &[RowDraft], leaf: &Leaf, cfg: &BlocksConfig) -> Self {
        let text_x1: Vec<f32> = drafts
            .iter()
            .filter(|draft| draft.float.is_none())
            .map(|draft| draft.bbox.x1)
            .collect();
        let left = drafts
            .iter()
            .filter(|draft| draft.float.is_none())
            .map(|draft| draft.bbox.x0)
            .fold(f32::INFINITY, f32::min);
        let enough_rows = text_x1.len() >= cfg.right_percentile_min_rows;
        let right = if enough_rows {
            percentile(text_x1.clone(), cfg.right_edge_percentile_ratio, leaf.bbox.x1)
        } else {
            text_x1.iter().copied().fold(f32::NEG_INFINITY, f32::max)
        };
        let flush_rows = text_x1
            .iter()
            .filter(|x1| (**x1 - right).abs() <= cfg.justified_edge_tol_pt)
            .count();
        let justified = enough_rows && flush_rows as f32 >= cfg.justified_min_ratio * text_x1.len() as f32;
        Self {
            left,
            right,
            justified,
            width: (right - left).max(1.0),
            center_x: (left + right) * 0.5,
        }
    }
}

/// Whether `ch` is a math symbol (operators, relations, arrows, Greek and
/// mathematical alphanumerics).
fn is_math_char(ch: char) -> bool {
    matches!(
        ch,
        '=' | '+'
            | '−'
            | '×'
            | '÷'
            | '·'
            | '∑'
            | '∏'
            | '∫'
            | '√'
            | '∞'
            | '≤'
            | '≥'
            | '≠'
            | '≈'
            | '∈'
            | '∉'
            | '⊂'
            | '⊆'
            | '∪'
            | '∩'
            | '∧'
            | '∨'
            | '¬'
            | '→'
            | '←'
            | '↔'
            | '⇒'
            | '⇔'
            | '∀'
            | '∃'
            | '∂'
            | '∇'
            | '∝'
            | '∼'
            | '≡'
            | '⟨'
            | '⟩'
            | '‖'
            | '|'
            | '<'
            | '>'
            | '±'
            | '∓'
            | '⊕'
            | '⊗'
            | '∘'
            | '′'
            | '⊤'
            | '⊥'
            | '∥'
            | '≜'
            | '≪'
            | '≫'
            | '↦'
            | '∖'
    ) || ('\u{0391}'..='\u{03C9}').contains(&ch)
        || ('\u{1D400}'..='\u{1D7FF}').contains(&ch)
}

/// Whether a glyph's text is a relation sign, the mark of a formula.
fn is_relation(text: &str) -> bool {
    matches!(text, "=" | "≤" | "≥" | "≈" | "∈" | "→" | "∝" | "≡" | "<" | ">")
}

/// Counts the characters, math characters and prose characters (runs of at
/// least four letters without a space) of a row.
fn row_stats(lines: &[&Line], fonts: &[FontInfo]) -> RowStats {
    let mut stats = RowStats {
        n_chars: 0,
        math_chars: 0,
        prose_chars: 0,
    };
    for line in lines {
        let mut run = 0usize;
        for glyph in &line.glyphs {
            let font = &fonts[glyph.font as usize];
            let nchars = glyph.text.chars().count();
            stats.n_chars += nchars;
            let mathy = font.math || glyph.text.chars().any(is_math_char);
            if mathy {
                stats.math_chars += nchars;
            }
            let alpha = !mathy && glyph.script == 0 && glyph.text.chars().all(|ch| ch.is_alphabetic());
            if alpha && !glyph.space_before {
                run += nchars;
            } else {
                if run >= 4 {
                    stats.prose_chars += run;
                }
                run = if alpha { nchars } else { 0 };
            }
        }
        if run >= 4 {
            stats.prose_chars += run;
        }
    }
    stats
}

/// The value at quantile `quantile` (0-1, nearest rank) of `values`, or
/// `default` when there are none.
fn percentile(mut values: Vec<f32>, quantile: f32, default: f32) -> f32 {
    if values.is_empty() {
        return default;
    }
    values.sort_by(|a, b| a.total_cmp(b));
    let idx = ((values.len() - 1) as f32 * quantile).round() as usize;
    values[idx]
}

/// Whether the line ends with a hyphen (a word continues on the next line).
fn ends_with_hyphen(line: &Line) -> bool {
    line.glyphs.last().is_some_and(|glyph| glyph.text.ends_with('-'))
}

/// Whether (nearly) the whole line is set in bold.
fn bold_dominant(line: &Line, fonts: &[FontInfo], cfg: &BlocksConfig) -> bool {
    line.font_frac(fonts, |font| font.bold) >= cfg.bold_dominant_ratio
}

/// Whether the first visible glyph of the line is set in a bold font.
fn starts_bold(line: &Line, fonts: &[FontInfo]) -> bool {
    line.glyphs
        .iter()
        .find(|glyph| !glyph.text.trim().is_empty())
        .and_then(|glyph| fonts.get(glyph.font as usize))
        .is_some_and(|font| font.bold)
}

/// Whether the line starts with a footnote mark: a superscript or a
/// footnote symbol.
fn footnote_marked(line: &Line) -> bool {
    line.starts_with_superscript()
        || line
            .glyphs
            .first()
            .is_some_and(|glyph| matches!(glyph.text.as_str(), "∗" | "†" | "‡" | "§" | "" | "*"))
}

/// Total number of characters of the row's lines.
fn row_chars(draft: &RowDraft) -> usize {
    draft.lines.iter().map(|line| line.char_count()).sum::<usize>()
}

/// Collects the rows of a leaf from the reading order: the lines of each
/// row (cloned from the page) and the float it holds, if any.
fn gather_rows(page: &PageData, leaf: &Leaf) -> Vec<RowDraft> {
    let mut drafts: Vec<RowDraft> = Vec::new();
    for row in &leaf.rows {
        let mut lines = Vec::new();
        let mut float = None;
        for item in row {
            match *item {
                ItemRef::Line(i) => lines.push(page.lines[i].clone()),
                ItemRef::Float(i) => float = Some(i),
            }
        }
        let bbox = lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
        drafts.push(RowDraft { lines, float, bbox });
    }
    drafts
}

/// Tiny orphan rows (pieces of inline math) join the row they overlap: the
/// previous or next row, whichever is vertically closer.
fn join_orphan_rows(drafts: &mut Vec<RowDraft>, stats: &DocStats, cfg: &BlocksConfig) {
    let mut i = 0;
    while i < drafts.len() {
        let tiny = drafts[i].float.is_none()
            && row_chars(&drafts[i]) <= cfg.orphan_max_chars
            && drafts[i].bbox.width() < cfg.orphan_max_width_em * stats.body_size;
        if tiny && let Some(target) = orphan_target(drafts, i, stats, cfg) {
            let row = drafts.remove(i);
            let target = if target > i { target - 1 } else { target };
            drafts[target].lines.extend(row.lines);
            drafts[target].bbox = drafts[target].bbox.union(&row.bbox);
            continue;
        }
        i += 1;
    }
}

/// The index of the neighbour row that the orphan row `idx` joins: a text
/// row with more characters that overlaps it vertically and covers it
/// horizontally (within a body size). The closer one wins when both
/// neighbours qualify; `None` when neither does.
fn orphan_target(drafts: &[RowDraft], idx: usize, stats: &DocStats, cfg: &BlocksConfig) -> Option<usize> {
    let orphan = drafts[idx].bbox;
    let accepts = |other: &RowDraft| {
        other.float.is_none()
            && other.bbox.y_overlap(&orphan) > 0.0
            && orphan.x0 >= other.bbox.x0 - stats.body_size
            && orphan.x1 <= other.bbox.x1 + stats.body_size
            && row_chars(other) > cfg.orphan_max_chars
    };
    let prev_ok = idx > 0 && accepts(&drafts[idx - 1]);
    let next_ok = idx + 1 < drafts.len() && accepts(&drafts[idx + 1]);
    match (prev_ok, next_ok) {
        (true, true) => {
            let dist_prev = (drafts[idx - 1].bbox.cy() - orphan.cy()).abs();
            let dist_next = (drafts[idx + 1].bbox.cy() - orphan.cy()).abs();
            Some(if dist_prev <= dist_next { idx - 1 } else { idx + 1 })
        }
        (true, false) => Some(idx - 1),
        (false, true) => Some(idx + 1),
        _ => None,
    }
}

/// Classifies every row of a leaf as float, equation or text. Returns the
/// rows and, parallel to them, the weak equation candidates among the text
/// rows (`None` for every other row). A row holding a float and lines
/// yields a float row followed by a row for the lines; empty rows yield
/// nothing.
fn classify_rows(
    ctx: BlockContext,
    drafts: Vec<RowDraft>,
    extent: &LeafExtent,
) -> (Vec<Row>, Vec<Option<WeakEquation>>) {
    let mut rows: Vec<Row> = Vec::new();
    let mut weak: Vec<Option<WeakEquation>> = Vec::new();
    let ink_boxes: Vec<Rect> = drafts
        .iter()
        .map(|draft| draft.lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.ink)))
        .collect();
    for (draft_idx, draft) in drafts.into_iter().enumerate() {
        let isolated = is_isolated(&ink_boxes, draft_idx, ctx.stats, ctx.cfg);
        if let Some(float) = draft.float {
            rows.push(Row::Float(float));
            weak.push(None);
        }
        if draft.lines.is_empty() {
            continue;
        }
        let (row, weak_eq) = classify_text_row(ctx, draft.lines, extent, isolated);
        weak.push(weak_eq);
        rows.push(row);
    }
    (rows, weak)
}

/// Whether row `idx` has white space above and below it, as around a
/// displayed formula. The first and last rows, and neighbours without ink,
/// count as white space.
fn is_isolated(ink_boxes: &[Rect], idx: usize, stats: &DocStats, cfg: &BlocksConfig) -> bool {
    let ink = ink_boxes[idx];
    let above = idx == 0
        || ink_boxes[idx - 1].is_unset()
        || ink.y0 - ink_boxes[idx - 1].y1 > cfg.isolation_gap_em * stats.body_size;
    let below = idx + 1 >= ink_boxes.len()
        || ink_boxes[idx + 1].is_unset()
        || ink_boxes[idx + 1].y0 - ink.y1 > cfg.isolation_gap_em * stats.body_size;
    above && below
}

/// Classifies the lines of one row (not empty) as an equation or a text
/// row. A text row also returns its lines and ink as a weak equation
/// candidate when it looks formula-like.
fn classify_text_row(
    ctx: BlockContext,
    mut lines: Vec<Line>,
    extent: &LeafExtent,
    isolated: bool,
) -> (Row, Option<WeakEquation>) {
    lines.sort_by(|a, b| a.bbox.x0.total_cmp(&b.bbox.x0));
    let number = equation_number(&lines, extent, ctx.stats, ctx.cfg);
    let (is_eq, weak_eq, ink, flush) = {
        let content: Vec<&Line> = if number.is_some() {
            lines[..lines.len() - 1].iter().collect()
        } else {
            lines.iter().collect()
        };
        let features = RowFeatures::measure(ctx, &content, extent, isolated, number.is_some());
        let sentence = number.is_none() && sentence_words(&content) >= ctx.cfg.sentence_min_words;
        let is_eq = !sentence && is_equation(&features, ctx.cfg);
        // A formula-like line that did not qualify on its own; it is
        // promoted later if it sits right next to an equation row.
        let flush = features.left_indent < ctx.cfg.weak_flush_max_indent_em * features.em;
        // A line of prose that fills the column is a line of a paragraph,
        // however much math it holds.
        let prose_chars = features.prose_frac * features.n_chars as f32;
        let prose = prose_chars >= ctx.cfg.weak_full_min_prose_chars
            || (prose_chars > 0.0 && !features.multi && features.n_chars >= ctx.cfg.weak_full_flat_min_chars);
        let full = flush && prose && features.right_slack < ctx.cfg.weak_full_max_slack_em * features.em;
        let weak_eq = !is_eq && !full && !sentence && weak_equation(&features, ctx.cfg);
        let ink = content.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.ink));
        (is_eq, weak_eq, ink, flush)
    };
    if is_eq {
        let number_line = if number.is_some() { lines.pop() } else { None };
        let row = Row::Equation {
            lines,
            bbox: ink,
            number,
            number_line,
        };
        (row, None)
    } else {
        let weak = weak_eq.then_some((lines.clone(), ink, flush));
        (Row::Text(merge_row(ctx.page.index, lines, ctx.lines_cfg)), weak)
    }
}

/// Big operators, whose limits are set above and below them.
const BIG_OPERATORS: &[&str] = &["∑", "∏", "∐", "⋃", "⋂", "⨁", "⨂", "⨀", "⋁", "⋀", "⨄", "⨆"];

/// A single function term, as the denominator of a fraction in a display
/// set in text letters: "P(mammogram+)", "Var(X)".
static FUNCTION_TERM: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^[A-Za-z]{1,4} ?\([^()]{1,40}\)$").unwrap());

/// Little words of English sentences, rare in displayed formulas.
const SENTENCE_WORDS: &[&str] = &[
    "the", "we", "is", "are", "that", "this", "which", "for", "and", "with", "have", "has", "be", "can", "then",
    "when", "one", "of", "to", "in", "by", "as", "on", "from", "it", "its", "our", "every", "all", "now", "so",
];

/// How many words of `lines` are [`SENTENCE_WORDS`].
fn sentence_words(lines: &[&Line]) -> usize {
    lines
        .iter()
        .map(|line| {
            outside_parentheses(&line.text())
                .split(|ch: char| !ch.is_ascii_alphabetic())
                .filter(|word| SENTENCE_WORDS.iter().any(|known| known.eq_ignore_ascii_case(word)))
                .count()
        })
        .sum()
}

/// `text` without what is inside parentheses: the arguments of a function
/// written in words ("P(has BC and mammogram+)") are not a sentence.
fn outside_parentheses(text: &str) -> String {
    let mut depth = 0usize;
    let mut out = String::with_capacity(text.len());
    for ch in text.chars() {
        match ch {
            '(' => depth += 1,
            ')' => depth = depth.saturating_sub(1),
            _ if depth == 0 => out.push(ch),
            _ => {}
        }
    }
    out
}

/// The equation number of a row (lines sorted left to right): its last line
/// when the row has at least two lines and that line is a number like "(3)"
/// at the right margin. Returned without white space.
fn equation_number(lines: &[Line], extent: &LeafExtent, stats: &DocStats, cfg: &BlocksConfig) -> Option<String> {
    if lines.len() < 2 {
        return None;
    }
    let last = lines.last().unwrap();
    let text: String = last.text().chars().filter(|ch| !ch.is_whitespace()).collect();
    (EQNO.is_match(&text) && last.bbox.x1 >= extent.right - cfg.eqno_margin_em * stats.body_size).then_some(text)
}

impl RowFeatures {
    /// Measures the `content` lines of a row (without its equation number)
    /// against the leaf's `extent`.
    fn measure(ctx: BlockContext, content: &[&Line], extent: &LeafExtent, isolated: bool, numbered: bool) -> Self {
        let cfg = ctx.cfg;
        let stats = row_stats(content, ctx.fonts);
        let content_box = content.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
        let em = content.iter().map(|line| line.size).fold(0.0, f32::max).max(1.0);
        let left_indent = content_box.x0 - extent.left;
        let right_slack = extent.right - content_box.x1;
        let centered = (content_box.cx() - extent.center_x).abs()
            <= (cfg.centered_tol_ratio * extent.width).max(cfg.centered_min_tol_pt)
            && left_indent >= cfg.centered_min_margin_em * em
            && right_slack >= cfg.centered_min_margin_em * em;
        let multi = {
            let mut baselines: Vec<f32> = content.iter().map(|line| line.baseline).collect();
            baselines.sort_by(|a, b| a.total_cmp(b));
            baselines.last().unwrap() - baselines[0] > cfg.multi_baseline_em * em
        };
        let has_relation = content
            .iter()
            .any(|line| line.glyphs.iter().any(|glyph| is_relation(&glyph.text)));
        let text = content.iter().map(|line| line.text()).collect::<Vec<_>>().join(" ");
        let text = text.trim();
        // A line of a display set in text letters: it goes on from the line
        // above ("+ P(no BC)P(mammogram+ | no BC)"), or it is one function
        // term (the denominator "P(mammogram+)").
        let operator_start = text.starts_with([
            '+', '\u{2212}', '=', '\u{D7}', '\u{B7}', '\u{2248}', '\u{2264}', '\u{2265}',
        ]);
        let call_only = FUNCTION_TERM.is_match(text);
        let has_bracket_piece = text.chars().any(is_bracket_piece);
        Self {
            numbered,
            n_chars: stats.n_chars,
            math_frac: stats.math_chars as f32 / stats.n_chars.max(1) as f32,
            prose_frac: stats.prose_chars as f32 / stats.n_chars.max(1) as f32,
            em,
            left_indent,
            right_slack,
            centered,
            isolated,
            multi,
            has_relation,
            continues_display: operator_start || call_only,
            has_bracket_piece,
        }
    }
}

/// Whether a row is a display equation. A numbered row is one unless it is
/// mostly prose; other rows need one of the [`EQUATION_RULES`].
fn is_equation(features: &RowFeatures, cfg: &BlocksConfig) -> bool {
    if features.numbered {
        return features.prose_frac < cfg.numbered_max_prose_ratio;
    }
    EQUATION_RULES.iter().any(|rule| rule(features, cfg))
}

/// Rule: mostly math, little prose, centred or clearly indented.
fn displayed_formula(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.math_frac >= cfg.display_min_math_ratio
        && row.prose_frac <= cfg.display_max_prose_ratio
        && (row.centered || row.left_indent >= cfg.display_min_indent_em * row.em)
}

/// Rule: a row with a piece of a tall bracket or brace and little prose: a
/// line of a displayed matrix or `cases`, however it sits.
fn drawn_bracket(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.has_bracket_piece && row.prose_frac <= cfg.stacked_max_prose_ratio
}

/// Whether `ch` is a piece of a tall bracket, brace or parenthesis
/// (U+239B to U+23AD), which fonts use to draw delimiters taller than any
/// glyph.
fn is_bracket_piece(ch: char) -> bool {
    ('\u{239B}'..='\u{23AD}').contains(&ch)
}

/// Rule: almost nothing but symbols, indented or isolated.
fn symbol_row(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.math_frac >= cfg.symbolic_min_math_ratio
        && row.prose_frac <= cfg.symbolic_max_prose_ratio
        && row.n_chars >= cfg.symbolic_min_chars
        && (row.left_indent >= cfg.symbolic_min_indent_em * row.em || row.isolated)
}

/// Rule: a centred, isolated formula made mostly of operator names, with a
/// relation sign.
fn centred_relation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.centered
        && row.isolated
        && row.math_frac >= cfg.operator_min_math_ratio
        && row.prose_frac <= cfg.operator_max_prose_ratio
        && row.has_relation
}

/// Rule: a formula spanning several baselines (fractions, stacked limits),
/// indented on both sides.
fn stacked_formula(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.multi
        && row.math_frac >= cfg.stacked_min_math_ratio
        && row.prose_frac <= cfg.stacked_max_prose_ratio
        && row.left_indent >= cfg.stacked_min_margin_em * row.em
        && row.right_slack >= cfg.stacked_min_margin_em * row.em
}

/// Rule: a centred formula spanning several baselines with a relation sign
/// and no prose word at all (variables set in text italics, as in APS
/// papers, are not counted as math but are no words either).
fn centred_stacked_relation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    row.centered
        && row.multi
        && row.has_relation
        && row.prose_frac == 0.0
        && row.math_frac >= cfg.operator_min_math_ratio
}

/// Whether a row that is not an equation on its own looks like one line of
/// a multi-line display: an indented short row with a relation sign, or a
/// row with a fair amount of math and little prose, or a tiny indented row
/// without prose (the numerator of a fraction).
fn weak_equation(row: &RowFeatures, cfg: &BlocksConfig) -> bool {
    (row.has_relation
        && row.left_indent >= cfg.weak_min_margin_em * row.em
        && row.right_slack >= cfg.weak_min_margin_em * row.em
        && row.n_chars <= cfg.weak_max_chars
        && row.prose_frac <= cfg.weak_max_prose_ratio)
        || (row.math_frac >= cfg.weak_min_math_ratio && row.prose_frac <= cfg.weak_math_max_prose_ratio)
        || (row.continues_display
            && row.n_chars <= cfg.weak_max_chars
            && row.left_indent >= cfg.weak_min_margin_em * row.em
            && row.right_slack >= cfg.weak_min_margin_em * row.em)
        || (row.n_chars <= cfg.weak_tiny_max_chars
            && row.prose_frac == 0.0
            && row.left_indent >= cfg.weak_min_margin_em * row.em
            && row.right_slack >= cfg.weak_min_margin_em * row.em)
}

/// Promotes weak candidates adjacent to an equation (lines of a multi-line
/// display where only some lines look like math), repeatedly, until no
/// more rows change.
fn promote_weak_equations(rows: &mut [Row], weak: &mut [Option<WeakEquation>], stats: &DocStats, cfg: &BlocksConfig) {
    loop {
        let mut changed = false;
        for i in 0..rows.len() {
            let Some((_, ink, flush)) = &weak[i] else { continue };
            // A flush-left row right below prose is the wrapped end of that
            // paragraph ("… for all / T ≥ 1."), not a line of the display.
            if *flush && i > 0 && matches!(rows[i - 1], Row::Text(_)) && weak[i - 1].is_none() {
                continue;
            }
            let near = |j: usize| match &rows[j] {
                Row::Equation { bbox, .. } => {
                    let gap = if bbox.cy() < ink.cy() {
                        ink.y0 - bbox.y1
                    } else {
                        bbox.y0 - ink.y1
                    };
                    gap < cfg.promote_max_gap_leading * stats.leading
                }
                _ => false,
            };
            if (i > 0 && near(i - 1)) || (i + 1 < rows.len() && near(i + 1)) {
                let (lines, bbox, _) = weak[i].take().unwrap();
                rows[i] = Row::Equation {
                    lines,
                    bbox,
                    number: None,
                    number_line: None,
                };
                changed = true;
            }
        }
        if !changed {
            break;
        }
    }
}

/// Gives an equation number that stands in a row of its own ("(4)" between
/// the two lines of a split equation, "(20)" under the line it belongs to)
/// to the unnumbered equation row next to it (above first, else below), and
/// takes the row out. The number must be at the right margin and close to
/// the equation.
fn attach_stray_numbers(rows: &mut Vec<Row>, extent: &LeafExtent, stats: &DocStats, cfg: &BlocksConfig) {
    let mut i = 0;
    while i < rows.len() {
        let Row::Text(line) = &rows[i] else {
            i += 1;
            continue;
        };
        let text: String = line.text().chars().filter(|ch| !ch.is_whitespace()).collect();
        let at_margin = line.bbox.x1 >= extent.right - cfg.eqno_margin_em * stats.body_size;
        if !(EQNO.is_match(&text) && at_margin) {
            i += 1;
            continue;
        }
        let max_gap = cfg.merge_max_gap_leading * stats.leading;
        let ink = line.ink;
        let takes = |row: Option<&Row>| match row {
            Some(Row::Equation { number: None, bbox, .. }) => (ink.y0 - bbox.y1).max(bbox.y0 - ink.y1) < max_gap,
            _ => false,
        };
        let target = if i > 0 && takes(rows.get(i - 1)) {
            i - 1
        } else if takes(rows.get(i + 1)) {
            i + 1
        } else {
            i += 1;
            continue;
        };
        let Row::Text(number_line) = rows.remove(i) else {
            unreachable!()
        };
        let target = if target > i { target - 1 } else { target };
        if let Row::Equation {
            number,
            number_line: slot,
            ..
        } = &mut rows[target]
        {
            *number = Some(text);
            *slot = Some(number_line);
        }
    }
}

/// Merges vertically adjacent equation rows (multi-line equations,
/// numerators and denominators) unless both carry a number. The merged
/// equation keeps the first number; the line of a second number stays
/// among its lines so that its glyphs are drawn.
fn merge_equation_rows(rows: Vec<Row>, stats: &DocStats, cfg: &BlocksConfig) -> Vec<Row> {
    let mut merged: Vec<Row> = Vec::new();
    for row in rows {
        let Row::Equation {
            lines,
            bbox,
            number,
            number_line,
        } = row
        else {
            merged.push(row);
            continue;
        };
        if let Some(Row::Equation {
            lines: prev_lines,
            bbox: prev_bbox,
            number: prev_number,
            number_line: prev_number_line,
        }) = merged.last_mut()
        {
            let gap = bbox.y0 - prev_bbox.y1;
            let overlap = gap < 0.0;
            if overlap
                || (gap < cfg.merge_max_gap_leading * stats.leading && !(prev_number.is_some() && number.is_some()))
            {
                prev_lines.extend(lines);
                *prev_bbox = prev_bbox.union(&bbox);
                if prev_number.is_none() {
                    *prev_number = number;
                    *prev_number_line = number_line;
                } else if let Some(line) = number_line {
                    // Keep the glyphs of a second number drawable.
                    prev_lines.push(line);
                }
                continue;
            }
        }
        merged.push(Row::Equation {
            lines,
            bbox,
            number,
            number_line,
        });
    }
    merged
}

/// Moves into an equation the text rows that belong to it: those a tall
/// opening delimiter of it encloses (beside it, within its height, above or
/// below the line of the delimiter: the lines of `cases`, the rows of a
/// matrix), and the numerator or denominator of one of its fractions (a row
/// right above or below a fraction bar `bars` that reaches the equation,
/// within the bar's width), and the limits of its big operators, which do
/// not look like math on their own (`log(2)`).
fn absorb_enclosed_rows(rows: Vec<Row>, bars: &[Rect], cfg: &BlocksConfig) -> Vec<Row> {
    let tol = cfg.enclosing_tolerance_pt;
    let belongs = |line: &Line, lines: &[Line], bbox: &Rect| {
        let enclosed = enclosing_delimiters(lines, cfg)
            .iter()
            .any(|ink| line.ink.y0 >= ink.y0 - tol && line.ink.y1 <= ink.y1 + tol && line.ink.x0 >= ink.x1 - tol);
        let gap = cfg.fraction_part_max_gap_em * line.size;
        let fraction_part = bars.iter().any(|bar| {
            let within = line.ink.x0 >= bar.x0 - tol && line.ink.x1 <= bar.x1 + tol;
            let reaches = bar.x0 < bbox.x1 && bar.x1 > bbox.x0 && bar.y0 <= bbox.y1 + gap && bar.y1 >= bbox.y0 - gap;
            let below = line.ink.y0 >= bar.y1 && line.ink.y0 - bar.y1 <= gap;
            let above = line.ink.y1 <= bar.y0 && bar.y0 - line.ink.y1 <= gap;
            within && reaches && (below || above)
        });
        let size = lines.iter().map(|line| line.size).fold(0.0, f32::max);
        let limit = line.size <= cfg.limit_max_size_ratio * size
            && lines
                .iter()
                .flat_map(|eq_line| &eq_line.glyphs)
                .filter(|glyph| BIG_OPERATORS.contains(&glyph.text.as_str()))
                .any(|op| {
                    line.ink.x0 < op.ink.x1
                        && line.ink.x1 > op.ink.x0
                        && ((line.ink.y0 >= op.ink.y1 - tol && line.ink.y0 - op.ink.y1 <= gap)
                            || (line.ink.y1 <= op.ink.y0 + tol && op.ink.y0 - line.ink.y1 <= gap))
                });
        enclosed || fraction_part || limit
    };
    let mut out: Vec<Row> = Vec::new();
    for mut row in rows {
        if let Row::Text(line) = &row
            && let Some(Row::Equation { lines, bbox, .. }) = out.last_mut()
            && belongs(line, lines, bbox)
        {
            *bbox = bbox.union(&line.ink);
            if let Row::Text(line) = row {
                lines.push(line);
            }
            continue;
        }
        // Rows above the equation come before it.
        if let Row::Equation { lines, bbox, .. } = &mut row {
            while let Some(Row::Text(line)) = out.last()
                && belongs(line, lines, bbox)
            {
                *bbox = bbox.union(&line.ink);
                if let Some(Row::Text(line)) = out.pop() {
                    lines.insert(0, line);
                }
            }
        }
        out.push(row);
    }
    out
}

/// Joins an equation row made only of the numerators of fractions to the
/// line of text right below it, which holds their denominators (each line
/// of the row is just above a fraction bar over that line): a long line is
/// a sentence with inline fractions (`v/α ≥ w/β`), and the numerators join
/// it; a short one is the rest of the displayed formula, which joins the
/// equation.
fn inline_numerators(rows: Vec<Row>, bars: &[Rect], ctx: BlockContext) -> Vec<Row> {
    let cfg = ctx.cfg;
    let tol = cfg.enclosing_tolerance_pt;
    let mut out: Vec<Row> = Vec::new();
    for row in rows {
        if let Row::Text(text) = &row
            && let Some(Row::Equation {
                lines, number: None, ..
            }) = out.last()
        {
            let gap = cfg.fraction_part_max_gap_em * text.size;
            let numerator = |line: &Line| {
                bars.iter().any(|bar| {
                    line.ink.x0 >= bar.x0 - tol
                        && line.ink.x1 <= bar.x1 + tol
                        && line.ink.y1 <= bar.y0
                        && bar.y0 - line.ink.y1 <= gap
                        && text.ink.y0 <= bar.y1 + gap
                        && text.ink.y1 >= bar.y1
                        && bar.x0 >= text.ink.x0 - tol
                        && bar.x1 <= text.ink.x1 + tol
                })
            };
            let inline = text.text().chars().count() >= cfg.inline_fraction_min_chars;
            if lines.iter().all(numerator)
                && let Some(Row::Equation { mut lines, bbox, .. }) = out.pop()
                && let Row::Text(text) = row
            {
                if inline {
                    lines.push(text);
                    out.push(Row::Text(merge_row(ctx.page.index, lines, ctx.lines_cfg)));
                } else {
                    // The rest of a displayed formula that did not look like
                    // one without its fractions.
                    let bbox = bbox.union(&text.ink);
                    lines.push(text);
                    out.push(Row::Equation {
                        lines,
                        bbox,
                        number: None,
                        number_line: None,
                    });
                }
                continue;
            }
        }
        out.push(row);
    }
    out
}

/// The horizontal rules of `page` that may be fraction bars.
fn fraction_bars(page: &PageData, cfg: &BlocksConfig) -> Vec<Rect> {
    page.paths
        .iter()
        .filter(|path| !path.is_white())
        .map(|path| path.bbox)
        .filter(|bbox| {
            bbox.height() <= cfg.fraction_bar_max_thickness_pt && bbox.width() >= cfg.fraction_bar_min_width_pt
        })
        .collect()
}

/// The ink of the tall opening delimiters (`{`, `(`, `[`) of the lines of an
/// equation.
fn enclosing_delimiters(lines: &[Line], cfg: &BlocksConfig) -> Vec<Rect> {
    lines
        .iter()
        .flat_map(|line| &line.glyphs)
        .filter(|glyph| matches!(glyph.text.as_str(), "{" | "(" | "["))
        .filter(|glyph| glyph.ink.height() > cfg.enclosing_min_height_em * glyph.size)
        .map(|glyph| glyph.ink)
        .collect()
}

/// Index of the first row that belongs to the footnote area of the leaf
/// (`rows.len()` when there is none): below a footnote rule if there is
/// one, else a trailing run of small lines introduced by a footnote mark at
/// the foot of the page.
fn footnote_start(ctx: BlockContext, leaf: &Leaf, rows: &[Row], extent: &LeafExtent) -> usize {
    // Notes end the text of the page: they are low on it, or nothing is
    // below them (a short last page).
    let at_foot = rows
        .iter()
        .rev()
        .find_map(|row| match row {
            Row::Text(line) => Some(line.bbox.y1),
            _ => None,
        })
        .is_some_and(|bottom| {
            bottom >= ctx.cfg.footnote_run_min_bottom_ratio * ctx.page.height
                || !ctx.page.lines.iter().any(|line| line.bbox.y0 > bottom)
        });
    ruled_footnote_start(ctx, leaf, rows, extent)
        .or_else(|| marked_footnote_start(rows, ctx.stats, ctx.cfg).filter(|_| at_foot))
        .unwrap_or(rows.len())
}

/// The first row below a footnote rule: a short, left-aligned horizontal
/// rule inside the leaf with only small text rows below it. With several
/// such rules, the one that starts the area earliest wins. `None` without
/// a footnote rule.
fn ruled_footnote_start(ctx: BlockContext, leaf: &Leaf, rows: &[Row], extent: &LeafExtent) -> Option<usize> {
    let (stats, cfg) = (ctx.stats, ctx.cfg);
    let text_rows: Vec<(usize, &Line)> = rows
        .iter()
        .enumerate()
        .filter_map(|(i, row)| {
            if let Row::Text(line) = row {
                Some((i, line))
            } else {
                None
            }
        })
        .collect();
    let small = |line: &Line| line.size <= stats.body_size - cfg.footnote_size_drop_pt;
    let mut best: Option<usize> = None;
    for path in &ctx.page.paths {
        if !path.is_hrule() {
            continue;
        }
        let width = path.bbox.width();
        if width < cfg.footnote_rule_min_width_pt
            || width > cfg.footnote_rule_max_width_ratio * extent.width.max(cfg.footnote_rule_min_leaf_pt)
        {
            continue;
        }
        let left_aligned = (path.bbox.x0 - extent.left).abs() <= cfg.footnote_rule_align_pt;
        let centred = (path.bbox.cx() - extent.center_x).abs() <= cfg.footnote_rule_align_pt;
        if !(left_aligned || centred) {
            continue;
        }
        if path.bbox.y0 < leaf.bbox.y0 - cfg.footnote_rule_above_leaf_pt || path.bbox.y0 > leaf.bbox.y1 {
            continue;
        }
        let below: Vec<&(usize, &Line)> = text_rows
            .iter()
            .filter(|(_, line)| line.bbox.y0 > path.bbox.y0 - cfg.footnote_rule_tol_pt)
            .collect();
        if below.is_empty() {
            continue;
        }
        // Small text, or body-sized text introduced by a footnote mark.
        let marked_first = footnote_marked(below[0].1) || NUMBERED_NOTE.is_match(&below[0].1.text());
        let fits = |line: &Line| {
            small(line) || (marked_first && line.size <= stats.body_size + cfg.footnote_same_size_max_excess_pt)
        };
        if !below.iter().all(|(_, line)| fits(line)) {
            continue;
        }
        // Nothing but small text rows may follow.
        let first = below[0].0;
        if rows[first..].iter().any(|row| !matches!(row, Row::Text(_))) {
            continue;
        }
        if best.is_none_or(|start| first < start) {
            best = Some(first);
        }
    }
    best
}

/// Without a footnote rule: the first row of the trailing run of small text
/// rows that starts with a footnote mark and is set apart from the row
/// above. `None` when there is no such row (the leaf's first row never
/// starts a footnote area).
fn marked_footnote_start(rows: &[Row], stats: &DocStats, cfg: &BlocksConfig) -> Option<usize> {
    let mut k = rows.len();
    while k > 0 {
        match &rows[k - 1] {
            Row::Text(line) if line.size <= stats.body_size - cfg.footnote_run_size_drop_pt => k -= 1,
            _ => break,
        }
    }
    while k < rows.len() {
        let Row::Text(line) = &rows[k] else { break };
        // In the trailing run of small lines, a note may also be numbered
        // on the baseline.
        let text = line.text();
        let marked = footnote_marked(line) || NUMBERED_NOTE.is_match(&text) || VENUE_NOTE.is_match(&text);
        let gap_ok = k == 0
            || match &rows[k - 1] {
                Row::Text(prev) => {
                    line.baseline - prev.baseline
                        > cfg.footnote_gap_leading * stats.leading * line.size / stats.body_size
                }
                _ => true,
            };
        if marked && gap_ok && k > 0 {
            return Some(k);
        }
        k += 1;
    }
    None
}

/// Emits the blocks of a leaf's rows in order: floats and equations as they
/// are, consecutive text rows grouped (split at large gaps, size changes
/// and bold changes) and then cut into paragraphs. Rows from `fn_start` on
/// are footnotes.
fn emit_blocks(ctx: BlockContext, rows: Vec<Row>, fn_start: usize, loc: Loc, out: &mut Vec<RawBlock>) {
    let mut prev_baseline: Option<f32> = None;
    let mut group: Vec<(Line, f32)> = Vec::new(); // line, gap before
    let n_rows = rows.len();
    for (row_idx, row) in rows.into_iter().enumerate() {
        let footnote = row_idx >= fn_start;
        if row_idx == fn_start {
            flush_group(ctx, &mut group, loc, out, false);
            prev_baseline = None;
        }
        match row {
            Row::Float(idx) => {
                flush_group(ctx, &mut group, loc, out, footnote);
                out.push(RawBlock::Float { idx, loc });
                prev_baseline = None;
            }
            Row::Equation {
                lines,
                bbox,
                number,
                number_line,
            } => {
                flush_group(ctx, &mut group, loc, out, footnote);
                out.push(RawBlock::Equation(EquationBlock {
                    lines,
                    bbox,
                    number,
                    number_line,
                    loc,
                }));
                prev_baseline = None;
            }
            Row::Text(line) => {
                let gap = prev_baseline
                    .map(|baseline| line.baseline - baseline)
                    .unwrap_or(f32::INFINITY);
                if let Some((last, _)) = group.last()
                    && starts_new_group(ctx, last, &line, gap)
                {
                    flush_group(ctx, &mut group, loc, out, footnote);
                }
                prev_baseline = Some(line.baseline);
                group.push((line, gap));
            }
        }
        if row_idx + 1 == n_rows {
            flush_group(ctx, &mut group, loc, out, footnote);
        }
    }
    flush_group(ctx, &mut group, loc, out, false);
}

/// Whether text row `line` (at baseline distance `gap` from the previous
/// row) starts a new group after `last`: a large gap, a change of size, or
/// a change between bold and regular.
fn starts_new_group(ctx: BlockContext, last: &Line, line: &Line, gap: f32) -> bool {
    let (stats, cfg, fonts) = (ctx.stats, ctx.cfg, ctx.fonts);
    let expected = stats.leading * last.size.max(line.size) / stats.body_size;
    let ink_gap = line.ink.y0 - last.ink.y1;
    let big_gap =
        gap > cfg.block_gap_leading * expected + cfg.block_gap_slack_pt && ink_gap > cfg.block_ink_gap_em * line.size;
    let size_change = (last.size - line.size).abs() > cfg.block_size_change_pt;
    let bold_flip = bold_dominant(last, fonts, cfg) != bold_dominant(line, fonts, cfg)
        && last.char_count() > cfg.bold_flip_min_chars
        && line.char_count() > cfg.bold_flip_min_chars
        // A bold run-in heading that fills a whole line is rare; a flip
        // only separates blocks when the bold line stands alone.
        && (bold_dominant(last, fonts, cfg) || gap > cfg.bold_flip_gap_leading * expected)
        // ... and it does not go on into the next line: a long run-in
        // heading ("One-Stage Detection vs. Two-Stage Proposal + De- /
        // tection. The OverFeat ...") ends in bold on the line below.
        && !(bold_dominant(last, fonts, cfg) && starts_bold(line, fonts))
        // A bold sentence-like row that fills its line is the head of the
        // paragraph that goes on below.
        && !(bold_dominant(last, fonts, cfg) && is_run_in_head(last, gap, expected, cfg));
    big_gap || size_change || bold_flip
}

/// Whether the bold row `last`, followed by a row at baseline distance `gap`
/// (`expected` is the usual distance), is a run-in head that filled its line:
/// capitalised words ending in a period (not a numbered or lettered section
/// heading, not a single word) and no extra space below.
fn is_run_in_head(last: &Line, gap: f32, expected: f32, cfg: &BlocksConfig) -> bool {
    let text = last.text();
    let text = text.trim();
    let words = text.split_whitespace().count();
    // A section label ("A.1", "4.2", "B.") is not a word of a sentence.
    let labeled = text
        .split_whitespace()
        .next()
        .is_some_and(|word| word.chars().any(char::is_numeric) || word.trim_end_matches('.').chars().count() < 2);
    text.ends_with('.')
        && !labeled
        && text.chars().next().is_some_and(char::is_uppercase)
        && (2..=cfg.bold_run_in_max_words_count).contains(&words)
        && gap <= cfg.bold_flip_gap_leading * expected
}

/// Cuts the group of text rows into paragraphs and appends them to `out`
/// as text blocks (footnotes when `footnote`), leaving `group` empty. An
/// empty group adds nothing.
fn flush_group(ctx: BlockContext, group: &mut Vec<(Line, f32)>, loc: Loc, out: &mut Vec<RawBlock>, footnote: bool) {
    if group.is_empty() {
        return;
    }
    let cfg = ctx.cfg;
    let lines: Vec<(Line, f32)> = std::mem::take(group);
    let left = lines.iter().map(|line| line.0.bbox.x0).fold(f32::INFINITY, f32::min);
    let right = lines
        .iter()
        .map(|line| line.0.bbox.x1)
        .fold(f32::NEG_INFINITY, f32::max)
        .min(ctx.leaf_right + cfg.para_right_overshoot_pt);
    let centers: Vec<f32> = lines.iter().map(|line| line.0.bbox.cx()).collect();
    let median_center = crate::common::geom::median(&centers, 0.0);
    let centered = lines.len() >= 2
        && centers
            .iter()
            .all(|center| (center - median_center).abs() <= cfg.centered_group_tol_pt)
        && lines
            .iter()
            .any(|line| (line.0.bbox.x0 - left).abs() > cfg.centered_group_min_offset_pt)
        && !footnote;

    let layout = GroupLayout {
        right,
        centered,
        footnote,
        spaced: ctx.stats.spaced_paragraphs,
    };
    for para in split_paragraphs(lines, layout, ctx.fonts, cfg) {
        let gap_before = para[0].1;
        let lines: Vec<Line> = para.into_iter().map(|line| line.0).collect();
        let bbox = lines.iter().fold(Rect::EMPTY, |acc, line| acc.union(&line.bbox));
        let block = TextBlock {
            lines,
            loc,
            left,
            right,
            centered,
            gap_before,
            bbox,
        };
        out.push(if footnote {
            RawBlock::Footnote(block)
        } else {
            RawBlock::Text(block)
        });
    }
}

/// How a group of lines is set, for [`split_paragraphs`].
#[derive(Clone, Copy)]
struct GroupLayout {
    /// Right edge of the group's text.
    right: f32,
    /// The group is centred.
    centered: bool,
    /// The group is in the footnote area.
    footnote: bool,
    /// The document separates its paragraphs by space.
    spaced: bool,
}

/// Splits the lines of a group (with their gaps before) into paragraphs. A
/// centred group is one paragraph; otherwise a line starts a new paragraph
/// when one of the [`PARAGRAPH_RULES`] says so.
fn split_paragraphs(
    lines: Vec<(Line, f32)>,
    layout: GroupLayout,
    fonts: &[FontInfo],
    cfg: &BlocksConfig,
) -> Vec<Vec<(Line, f32)>> {
    let GroupLayout {
        right,
        centered,
        footnote,
        spaced,
    } = layout;
    let ragged = is_ragged(&lines, right, fonts, cfg);
    let spaced_prose = spaced && is_prose(&lines, fonts, true, cfg);
    let mut paras: Vec<Vec<(Line, f32)>> = Vec::new();
    for (line, gap) in lines {
        let Some(para) = paras.last_mut() else {
            paras.push(vec![(line, gap)]);
            continue;
        };
        let breaks = !centered && {
            let text = line.text();
            let candidate = ParagraphBreak {
                para,
                line: &line,
                text: &text,
                right,
                footnote,
                ragged,
                spaced_prose,
            };
            PARAGRAPH_RULES.iter().any(|rule| rule(&candidate, cfg))
        };
        if breaks {
            paras.push(vec![(line, gap)]);
        } else {
            para.push((line, gap));
        }
    }
    paras
}

/// Rule: the line starts with a bullet, or (in footnotes) with a footnote
/// mark.
fn starts_with_marker(candidate: &ParagraphBreak, _cfg: &BlocksConfig) -> bool {
    (candidate.footnote && footnote_marked(candidate.line))
        || (BULLET.is_match(candidate.text) && !dash_goes_on(candidate))
}

/// Whether a line starting with a dash goes on with the sentence of the
/// line before ("... the model\n– and then beat it"): a dash and a
/// lower-case word after a line that ended without punctuation.
fn dash_goes_on(candidate: &ParagraphBreak) -> bool {
    let prev = candidate.para.last().map(|(line, _)| line.text()).unwrap_or_default();
    let mut words = candidate.text.split_whitespace();
    let dash = words.next().is_some_and(|word| matches!(word, "–" | "—" | "-"));
    let lower = words
        .next()
        .and_then(|word| word.chars().next())
        .is_some_and(char::is_lowercase);
    dash && lower && !prev.trim_end().ends_with(['.', ':', ';', '!', '?'])
}

/// Rule: the line starts with an enumeration label, aligned with a
/// paragraph that also starts with one: the next item of a list.
fn new_enumeration_item(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
    let first = &candidate.para[0].0;
    let labelled = |text: &str| NUM_LABEL.is_match(text) || BRACKET_LABEL.is_match(text);
    labelled(candidate.text)
        && labelled(&first.text())
        && (candidate.line.bbox.x0 - first.bbox.x0).abs() <= cfg.para_label_align_em * candidate.line.size
}

/// Rule: the previous line ended early although the line's first word
/// would have fit (and it did not end with a hyphen). Text set ragged right
/// breaks its lines early anyway: there, a line that nearly reaches the
/// right edge (within [`BlocksConfig::ragged_line_max_gap_em`]) ends its
/// paragraph only when it ends a sentence; a much shorter one (an item of a
/// list of names, a line of code) still does. In a document whose
/// paragraphs are separated by space, the space already ends them: prose
/// set close together is one paragraph, whatever its short lines.
fn follows_short_line(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
    if candidate.spaced_prose {
        return false;
    }
    let prev = &candidate.para.last().unwrap().0;
    let em = candidate.line.size;
    let sentence_end = || {
        prev.text()
            .trim_end()
            .trim_end_matches(['\u{2019}', '\u{201D}', '"', '\'', ')'])
            .ends_with(['.', '!', '?', ':', ';'])
    };
    let nearly_full = candidate.right - prev.bbox.x1 <= cfg.ragged_line_max_gap_em * em;
    !ends_with_hyphen(prev)
        && (!candidate.ragged || !nearly_full || sentence_end())
        && prev.bbox.x1 + cfg.para_word_space_em * em + candidate.line.first_word_width()
            < candidate.right - cfg.para_short_line_slack_pt
}

/// Whether a group of `lines` is prose set ragged right: it has at least
/// [`BlocksConfig::ragged_min_lines_count`] lines, fewer than
/// [`BlocksConfig::justified_min_ratio`] of those before the last end at the
/// group's `right` edge (justified text ends nearly all of them there), and
/// each line reads as a sentence ([`is_prose`]): a listing of code whose
/// lines are prose taken together ("# assign base score" over
/// `if gender.lower() == "male":`) still keeps its lines apart.
fn is_ragged(lines: &[(Line, f32)], right: f32, fonts: &[FontInfo], cfg: &BlocksConfig) -> bool {
    if lines.len() < cfg.ragged_min_lines_count
        || !lines
            .iter()
            .all(|line| is_prose(std::slice::from_ref(line), fonts, false, cfg))
    {
        return false;
    }
    let body = &lines[..lines.len() - 1];
    let flush = body
        .iter()
        .filter(|(line, _)| (line.bbox.x1 - right).abs() <= cfg.justified_edge_tol_pt)
        .count();
    (flush as f32) < cfg.justified_min_ratio * body.len() as f32
}

/// Whether a group of `lines` reads as sentences: not code (monospaced),
/// and mostly lowercase words (a list of names and roles is not prose).
/// The words are counted over the whole group: one line of names ("Mr. and
/// Mrs. Dursley, of number four, Privet Drive") does not make a novel's
/// paragraph a list. With `shouting`, words in capitals count as words of
/// a sentence too ("YOU WON'T BELIEVE / WHAT IT'S DOING!"): a list of
/// names is in title case.
fn is_prose(lines: &[(Line, f32)], fonts: &[FontInfo], shouting: bool, cfg: &BlocksConfig) -> bool {
    let (mut lower, mut words) = (0, 0);
    for (line, _) in lines {
        let text = line.text();
        for word in text.split_whitespace() {
            let letters: Vec<char> = word.chars().filter(|ch| ch.is_alphabetic()).collect();
            let capitals = letters.len() >= 2 && letters.iter().all(|ch| ch.is_uppercase());
            words += 1;
            lower += usize::from(word.starts_with(|ch: char| ch.is_lowercase()) || (shouting && capitals));
        }
    }
    lines
        .iter()
        .all(|(line, _)| line.font_frac(fonts, |font| font.mono) < cfg.bold_dominant_ratio)
        && lower as f32 >= cfg.ragged_prose_min_lower_ratio * words as f32
}

/// Rule: in a paragraph of two lines or more, the line starts left or right
/// of the paragraph's continuation lines.
/// The lines set beside a drop cap at the start of the paragraph (indented
/// by its width) do not count, and do not start a new paragraph either.
fn indent_changes(candidate: &ParagraphBreak, cfg: &BlocksConfig) -> bool {
    if candidate.para.len() == 1 {
        return false;
    }
    let cap_bottom = drop_cap_bottom(&candidate.para[0].0, cfg);
    let beside = |line: &Line| cap_bottom.is_some_and(|bottom| line.bbox.y0 < bottom);
    if beside(candidate.line) {
        return false;
    }
    let em = candidate.line.size;
    let rest_x0 = candidate.para[1..]
        .iter()
        .filter(|line| !beside(&line.0))
        .map(|line| line.0.bbox.x0)
        .fold(f32::INFINITY, f32::min);
    if rest_x0.is_infinite() {
        return false;
    }
    candidate.line.bbox.x0 > rest_x0 + cfg.para_indent_change_em * em
        || candidate.line.bbox.x0 < rest_x0 - cfg.para_indent_change_em * em
}

/// The bottom of the drop cap that opens `first`, the first line of a
/// paragraph: its first glyph, when it is at least
/// [`BlocksConfig::drop_cap_min_size_ratio`] times as large as the line.
fn drop_cap_bottom(first: &Line, cfg: &BlocksConfig) -> Option<f32> {
    // An opening quote before the letter is as large as it.
    first
        .glyphs
        .iter()
        .take(2)
        .filter(|glyph| glyph.size >= cfg.drop_cap_min_size_ratio * first.size)
        .map(|glyph| glyph.ink.y1)
        .reduce(f32::max)
}

#[cfg(test)]
mod tests {
    use super::{BlocksConfig, EquationBlock, GroupLayout, RawBlock, TextBlock, join_equation_parts, split_paragraphs};
    use crate::analysis::lines::{LinesConfig, build_lines};
    use crate::analysis::page::DocStats;
    use crate::backend::{Dir, FontInfo, Glyph, RawPage};
    use crate::common::geom::Rect;
    use crate::model::Line;
    use crate::model::Loc;

    /// The lines of a page holding `rows` of 10 pt text, one every 12 pt,
    /// each glyph half an em wide.
    fn lines_of(rows: &[&str]) -> Vec<(Line, f32)> {
        let mut glyphs = Vec::new();
        for (row, text) in rows.iter().enumerate() {
            let y = 100.0 + 12.0 * row as f32;
            for (i, ch) in text.chars().enumerate() {
                let x = 40.0 + 5.0 * i as f32;
                glyphs.push(Glyph {
                    text: ch.to_string(),
                    x,
                    y,
                    adv: 5.0,
                    size: 10.0,
                    font: 0,
                    dir: Dir::Horizontal,
                    angle: 0.0,
                    invisible: false,
                    color: [0; 3],
                    ink: Rect::new(x, y - 7.0, x + 5.0, y),
                });
            }
        }
        let raw = RawPage {
            width: 600.0,
            height: 800.0,
            glyphs,
            ..Default::default()
        };
        let (lines, _) = build_lines(&raw, &LinesConfig::default());
        lines.into_iter().map(|line| (line, 0.0)).collect()
    }

    /// The paragraphs of `rows`, as lists of line texts.
    fn paragraphs(rows: &[&str]) -> Vec<Vec<String>> {
        paragraphs_in(rows, false)
    }

    /// The paragraphs of `rows` in a document whose paragraphs are
    /// separated by space (`spaced`) or not.
    fn paragraphs_in(rows: &[&str], spaced: bool) -> Vec<Vec<String>> {
        let lines = lines_of(rows);
        let right = lines
            .iter()
            .map(|(line, _)| line.bbox.x1)
            .fold(f32::NEG_INFINITY, f32::max);
        let fonts = [FontInfo::default()];
        let layout = GroupLayout {
            right,
            centered: false,
            footnote: false,
            spaced,
        };
        split_paragraphs(lines, layout, &fonts, &BlocksConfig::default())
            .into_iter()
            .map(|para| para.iter().map(|(line, _)| line.text()).collect())
            .collect()
    }

    #[test]
    fn ragged_prose_breaks_only_at_the_end_of_a_sentence() {
        // A letter quoted in a novel, set ragged right: "you" ends its line
        // early although "will" would have fit.
        let letter = [
            "do not like it, for it will make the surprise the greater, when",
            "I write to them and sign my name as his wife, and then you",
            "will laugh at me and say that it is a good joke indeed. What",
            "a good joke it will be! I can hardly write for laughing and",
            "then I hope you will drink to our good journey.",
        ];
        assert_eq!(paragraphs(&letter).len(), 1);
    }

    #[test]
    fn spaced_novel_paragraph_is_not_cut_at_short_lines() {
        // A novel made in Word: paragraphs separated by a blank line, set
        // ragged right, so a line may end well before the longest one
        // ("Mrs." with room for "Potter"), even after a full stop.
        let paragraph = [
            "The Dursleys had everything they wanted, but they also had a secret, and",
            "their greatest fear was that somebody would discover it. They didn't",
            "think they could bear it if anyone found out. Mrs.",
            "Potter was Mrs. Dursley's sister, but they hadn't met for several years;",
        ];
        assert_eq!(paragraphs_in(&paragraph, true).len(), 1);
        // Without the spacing, the short lines that end a sentence still
        // end paragraphs.
        assert!(paragraphs_in(&paragraph, false).len() > 1);
    }

    #[test]
    fn spaced_novel_keeps_a_shouted_sentence_whole() {
        let shout = [
            "\"DUDLEY! MR. DURSLEY! COME AND LOOK AT THIS SNAKE! YOU WON'T BELIEVE",
            "WHAT IT'S DOING!\"",
        ];
        assert_eq!(paragraphs_in(&shout, true).len(), 1);
    }

    #[test]
    fn spaced_document_keeps_a_list_of_names_apart() {
        let names = [
            "Greg Brockman Infrastructure lead",
            "Trevor Cai Throughput lead",
            "David Farhi Optimization Team",
            "Chris Hesse Usability Lead",
            "Amin Tootoonchian Model Distribution, Systems & Networking Lead",
        ];
        assert_eq!(paragraphs_in(&names, true).len(), names.len());
    }

    #[test]
    fn ragged_list_of_names_keeps_its_lines_apart() {
        // Each name and role on a line of its own, the column as wide as
        // its longest entry.
        let names = [
            "Greg Brockman Infrastructure lead",
            "Trevor Cai Throughput lead",
            "David Farhi Optimization Team",
            "Chris Hesse Usability Lead",
            "Amin Tootoonchian Model Distribution, Systems & Networking Lead",
        ];
        assert_eq!(paragraphs(&names).len(), names.len());
    }

    /// A block of `rows` (see [`lines_of`]) moved right by `dx` and down by
    /// `dy`, in column `col` of zone `zone`: an equation, or text.
    fn part(rows: &[&str], dx: f32, dy: f32, zone: usize, col: usize, equation: bool) -> RawBlock {
        let lines: Vec<Line> = lines_of(rows)
            .into_iter()
            .map(|(mut line, _)| {
                line.bbox = Rect::new(
                    line.bbox.x0 + dx,
                    line.bbox.y0 + dy,
                    line.bbox.x1 + dx,
                    line.bbox.y1 + dy,
                );
                line.baseline += dy;
                line
            })
            .collect();
        let bbox = lines.iter().map(|line| line.bbox).reduce(|a, b| a.union(&b)).unwrap();
        let loc = Loc {
            page: 0,
            zone,
            zone_cols: 2,
            col,
            leaf: col,
        };
        if equation {
            RawBlock::Equation(EquationBlock {
                lines,
                bbox,
                number: None,
                number_line: None,
                loc,
            })
        } else {
            RawBlock::Text(TextBlock {
                lines,
                loc,
                left: bbox.x0,
                right: bbox.x1,
                centered: false,
                gap_before: 0.0,
                bbox,
            })
        }
    }

    const STATS: DocStats = DocStats {
        body_size: 10.0,
        body_font: 0,
        leading: 12.0,
        spaced_paragraphs: false,
    };

    /// A matrix that the reading order cut into two columns of a zone (its
    /// first rows read as text, set off by the pieces of its brackets) is
    /// joined into one equation.
    #[test]
    fn matrix_cut_into_columns_is_one_equation() {
        let mut blocks = vec![
            part(&["⎛ cosh φ"], 60.0, 0.0, 1, 0, false),
            part(&["", "Λ = ⎜⎜ 0", "⎝ 0"], 60.0, 0.0, 1, 0, true),
            part(&["− sinh φ 0 0 ⎞"], 120.0, 0.0, 1, 1, false),
            part(&["", "1 0 ⎟ .", "0 1 ⎠"], 130.0, 0.0, 1, 1, true),
        ];
        join_equation_parts(&mut blocks, &STATS, &BlocksConfig::default());
        assert_eq!(blocks.len(), 1);
        let RawBlock::Equation(equation) = &blocks[0] else {
            panic!("the parts make an equation");
        };
        assert_eq!(equation.lines.len(), 6);
    }

    /// Two equations level with each other in the two columns of a zone of
    /// running text (a two-column page) stay apart.
    #[test]
    fn equations_of_two_text_columns_stay_apart() {
        let mut blocks = vec![
            part(&["Some running text of the left column."], 0.0, -24.0, 1, 0, false),
            part(&["x = y + z"], 60.0, 0.0, 1, 0, true),
            part(&["Some running text of the right column."], 220.0, -24.0, 1, 1, false),
            part(&["a = b"], 240.0, 0.0, 1, 1, true),
        ];
        join_equation_parts(&mut blocks, &STATS, &BlocksConfig::default());
        assert_eq!(blocks.len(), 4);
    }
}