kakemono 0.24.0

Convert PDF, Word, Excel, PowerPoint and EPUB documents and web pages 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
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
//! Detection of figures, tables and other graphics, and their captions.
//!
//! Vector drawings and images are clustered into components, captions are
//! found by their label ("Figure 3:"), and each caption claims the nearest
//! component. Everything inside a claimed region is rendered as an image
//! later, so the text inside it is removed from the text flow.

use super::lines::LinesConfig;
use super::page::{DocStats, PageData};
use crate::backend::{FontInfo, PathBox};
use crate::common::geom::Rect;
use crate::model::FloatKind;
use crate::model::{Line, LineGlyph};
use regex::Regex;
use std::collections::BTreeMap;
use std::sync::LazyLock;

/// Extra cells added to each dimension of the clustering grid, so that the
/// dilated box of an element touching the page edge still has a cell to fall
/// into instead of being clamped onto the content.
const GRID_PADDING_CELLS: usize = 2;

/// Component label of a grid cell that no flood fill has reached yet.
const UNLABELLED: u32 = u32::MAX;

/// A caption label at the start of a line: the float kind ("Figure",
/// "Table", "Algorithm", ...), its number ("3", "IV", "A.2", "S1") and the
/// punctuation that follows it, if any. A label followed by punctuation or
/// standing alone is a caption; a bare "Fig. 3 shows" is a reference.
static CAPTION: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"^(?P<kind>Supplementary\s+Figure|Supplementary\s+Table|Extended\s+Data\s+Fig\.?|Extended\s+Data\s+Table|Figure|Fig\.?|FIGURE|FIG\.?|Table|TABLE|Tab\.|Algorithm|ALGORITHM|Listing|Scheme|Chart|Plate)\s*(?P<num>\d+(?:\.\d+)*[a-z]?|[IVXLC]+|[A-Z]\.?\d+|S\d+)\s*(?P<punct>[:.|—–-]|$)?",
    )
    .unwrap()
});

/// A numbered section heading ("3.2 Results", "IV. Method", "A. Proofs"):
/// such a line next to a drawing is never absorbed as a sub-figure title.
static HEADING_LIKE: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:\d{1,2}(?:\.\d{1,2})*\.?|[IVX]+\.|[A-Z]\.)\s+\p{Lu}").unwrap());

/// The marker that starts the sub-caption of a panel of a figure: "(b) An
/// example of ...", "(c)".
static PANEL_MARKER: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\([a-hA-H]\)(\s|$)").unwrap());

/// Tuning parameters of float detection. Part of [`LayoutConfig`](crate::config::LayoutConfig).
///
/// Lengths are in PDF points (`_pt`) or in multiples of a font size (`_em`,
/// of the line's own size unless stated otherwise); `_ratio` fields are
/// fractions between 0 and 1.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct FloatsConfig {
    // --- running text ---
    /// A line with at least this many characters may be running prose
    /// rather than a label inside a figure. Also used to find the left
    /// margin of the running text and to keep long lines out of the
    /// sub-figure labels.
    pub body_min_chars: usize,
    /// A prose line is also wider than this many body font sizes: about a
    /// column of text, much wider than any axis label or table cell.
    pub body_min_width_em: f32,

    // --- captions ---
    /// The label of a caption counts as bold when at least this many tenths
    /// of its glyphs are set in a bold font (and fewer than half of the
    /// glyphs of the rest are).
    pub caption_label_bold_tenths: usize,
    /// How many lines above a caption candidate are searched for a
    /// paragraph it would continue.
    pub caption_lookback_count: usize,
    /// A line above the candidate continues into it when its baseline is
    /// more than this many sizes above (so it is not on the same row)...
    pub continuation_min_dy_em: f32,
    /// ... and less than this many sizes above: normal leading of a
    /// paragraph.
    pub continuation_max_dy_em: f32,
    /// ... and its font size differs by less than this.
    pub continuation_size_tol_pt: f32,
    /// ... and it overlaps the candidate horizontally by more than this
    /// fraction of the narrower of the two lines.
    pub continuation_overlap_ratio: f32,
    /// ... and it has more than this many characters (a real text line, not
    /// a stray label).
    pub continuation_min_chars: usize,
    /// A shorter line above (a narrow margin caption) still runs on into
    /// the label when it has at least this many words, ends mid-sentence
    /// (with a lowercase letter or a comma) and starts within
    /// `continuation_left_tol_pt` of the label's left edge.
    pub continuation_short_min_words_count: usize,
    /// See `continuation_short_min_words_count`.
    pub continuation_left_tol_pt: f32,
    /// The second line of a caption starts at most this many sizes below
    /// the first, or at the body's leading (times `caption_step_max_leading`,
    /// plus `caption_step_slack_pt`): small captions set at the body's
    /// leading (ACL) are further apart than their size suggests.
    pub caption_first_step_max_em: f32,
    /// Further caption lines follow at most this multiple of the leading
    /// measured between the first two lines...
    pub caption_step_max_leading: f32,
    /// ... plus this slack.
    pub caption_step_slack_pt: f32,
    /// A caption line is at least this many sizes below the previous one;
    /// closer lines are on the same row (sub- and superscripts).
    pub caption_step_min_em: f32,
    /// Caption lines differ in font size by at most this.
    pub caption_size_tol_pt: f32,
    /// A caption line may start at most this many sizes left of the caption
    /// so far (hanging indentation of the label).
    pub caption_left_overhang_em: f32,
    /// A caption line may end at most this far right of the caption so far.
    pub caption_right_overhang_pt: f32,
    /// A caption at most this wide (in sizes of its text) is a narrow one,
    /// set in a margin: its lines are ragged on the right, so a line flush
    /// with its left edge continues it however far right it ends (within
    /// that width).
    pub narrow_caption_max_width_em: f32,
    /// A narrow caption beside a component (left or right of it, its top
    /// within the component's height) claims it when the gap between them
    /// is at most this (points): a book that sets its captions in the
    /// margin beside the figure.
    pub beside_max_gap_pt: f32,
    /// The same for a caption of two lines or more, which is surely in the
    /// margin (a short caption of one line in a two-column paper is narrow
    /// too): a figure in the text column may stand that far away.
    pub beside_far_max_gap_pt: f32,
    /// A line that starts with its own punctuated label within this
    /// distance of the caption's left edge starts the next caption.
    pub caption_next_label_tol_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 caption_word_space_em: f32,
    /// A previous line that ends earlier than this before the caption's
    /// right edge although the next word would have fit ends the caption.
    pub caption_short_line_slack_pt: f32,
    /// The caption stops growing after more than this many lines; guards
    /// against swallowing a whole column.
    pub caption_max_lines_count: usize,
    /// A horizontal rule at least this wide (in points) that runs between two
    /// lines of text and under the lower one ends a caption: the lower line
    /// is the header row of the table, not more caption.
    pub caption_rule_min_width_pt: f32,
    /// A rule separates two caption lines only if it lies this far (in font
    /// sizes) above the baseline of the lower one: at least the height of
    /// its lowercase letters.
    pub caption_rule_clear_em: f32,

    // --- joining bare labels ---
    /// A bare label and its text are on the same baseline within this.
    pub label_join_baseline_tol_pt: f32,
    /// A bare label and its text differ in font size by less than this.
    pub label_join_size_tol_pt: f32,
    /// The text starts less than this many sizes right of the label.
    pub label_join_max_gap_em: f32,

    // --- clustering of graphics ---
    /// Side of a cell of the clustering grid. Smaller cells separate
    /// drawings that are close together, at the cost of a larger grid.
    pub grid_cell_pt: f32,
    /// Every element is grown by this much before it is drawn into the
    /// grid, so that elements this close together form one component.
    pub cluster_dilate_pt: f32,
    /// Images covering more than this fraction of the page are page
    /// backgrounds (scans, watermarks) and are ignored.
    pub background_image_area_ratio: f32,
    /// ... except on the first or the last page when it has at most this
    /// many lines of text: that is the cover (or the back cover) of a book,
    /// a picture with its title and authors on it, and it is kept as a
    /// figure.
    pub cover_max_lines_count: usize,
    /// Paths spanning more than this fraction of the page in both
    /// directions are page frames or backgrounds and are ignored.
    pub background_path_extent_ratio: f32,
    /// A filled, unstroked path behind at least this many lines of running
    /// text (of [`body_min_chars`](Self::body_min_chars) characters) is the
    /// shading of a text box (an example, a note), not a drawing: it is
    /// ignored, and the pictures inside the box stay figures of their own.
    pub shaded_box_min_lines_count: usize,
    /// A shaded box is also the shading of a text box when one line inside
    /// it is prose across it: its glyphs inside the box span at least this
    /// share of the box's width...
    pub shaded_box_line_fill_ratio: f32,
    /// ... with at least this many characters (no plot has such a line).
    pub shaded_box_wide_line_min_chars: usize,
    /// A light shading (every colour channel at least this) at least
    /// `background_panel_min_width_ratio` of the page wide that holds other
    /// drawings is the background of a box (a worked example holding a
    /// figure), not a drawing: the drawings inside it are the figure.
    pub background_panel_min_channel: u8,
    /// See `background_panel_min_channel`.
    pub background_panel_min_width_ratio: f32,
    /// ... or behind the captions of this many floats.
    pub shaded_box_min_captions_count: usize,
    /// A vertical rule with at least this many lines of running text
    /// beside it ...
    pub side_rule_min_lines_count: usize,
    /// ... starting at most this many font sizes to its right is the bar
    /// that marks a box of text (an example), not a drawing: it is ignored.
    pub side_rule_max_gap_em: f32,
    /// Paths with an alpha value below this are invisible and ignored.
    pub min_path_alpha: u8,
    /// A component needs at least this many paths to be a ruled table.
    pub ruled_min_paths_count: usize,
    /// A component is a ruled table when at least this many tenths of its
    /// paths are straight rules (and it has no image).
    pub ruled_rule_tenths: usize,

    // --- tables made of horizontal rules only (booktabs) ---
    /// Horizontal rules shorter than this are not table rules.
    pub booktabs_min_rule_width_pt: f32,
    /// Pages with more rules than this are not searched (the grouping is
    /// quadratic, and such pages are drawings, not tables).
    pub booktabs_max_rules_count: usize,
    /// Rules of one table start and end within this of each other.
    pub booktabs_extent_tol_pt: f32,
    /// A group of rules lower than this is not a table.
    pub booktabs_min_height_pt: f32,
    /// A caption between two rules splits the group when it overlaps the
    /// upper rule by more than this fraction of the narrower of the two.
    pub booktabs_caption_overlap_ratio: f32,
    /// Two consecutive rules farther apart than this belong to different
    /// tables.
    pub booktabs_max_rule_gap_pt: f32,

    // --- candidate components ---
    /// Components narrower or lower than this are ignored (bullets, rules
    /// under a word, logos).
    pub min_component_pt: f32,
    /// A component covering more than this fraction of the page ...
    pub page_sized_area_ratio: f32,
    /// ... on a page with more than this many lines is a page decoration,
    /// not a float.
    pub page_sized_min_lines_count: usize,
    /// A rule table within this distance of a drawing component is part of
    /// it (or contains it).
    pub rule_table_containment_tol_pt: f32,
    /// A ruled drawing that holds a rule table and sticks out of its left or
    /// right edge by more than this is the table plus stray rules (a
    /// fraction bar of an equation in the next column): it shrinks to the
    /// table.
    pub rule_table_overhang_pt: f32,

    // --- votes for the table caption convention ---
    /// A table is next to its caption when it overlaps the caption
    /// horizontally by at least this fraction of the narrower of the two...
    pub vote_overlap_ratio: f32,
    /// ... and the vertical gap between them is at least this (negative:
    /// a slight overlap is allowed) ...
    pub vote_min_gap_pt: f32,
    /// ... and at most this.
    pub vote_max_gap_pt: f32,

    // --- pairing captions and components ---
    /// A caption can claim a component that overlaps it horizontally by at
    /// least this fraction of the narrower of the two.
    pub pair_overlap_ratio: f32,
    /// A component lies above (below) a caption when it ends (starts) within
    /// this of the caption's top (bottom) edge.
    pub side_tol_pt: f32,
    /// A caption only claims components at most this far away.
    pub pair_max_dist_pt: f32,
    /// A prose line lies between a caption and a component when it overlaps
    /// the caption by more than this fraction of its own width.
    pub body_between_overlap_ratio: f32,
    /// Score penalty for a figure below its caption (figure captions are
    /// usually set below the figure).
    pub penalty_figure_below_pt: f32,
    /// Score penalty for a table on the side of its caption that contradicts
    /// the document's convention.
    pub penalty_table_against_convention_pt: f32,
    /// Score penalty for a table above its caption when the document has no
    /// clear convention (table captions are more often above).
    pub penalty_table_above_pt: f32,
    /// Score penalty for an algorithm above its caption.
    pub penalty_algorithm_above_pt: f32,
    /// Score penalty for a figure caption claiming a ruled table.
    pub penalty_figure_on_table_pt: f32,
    /// Score penalty for a table caption claiming a drawing that is not a
    /// ruled table.
    pub penalty_table_on_drawing_pt: f32,
    /// Score penalty for a caption whose centre is off the component's
    /// centre by the full width of the wider of the two.
    pub misalign_weight_pt: f32,

    // --- growing caption regions ---
    /// An unclaimed component within this distance of a region joins it.
    pub grow_touch_pt: f32,
    /// A component stacked on a region joins it when it overlaps the region
    /// horizontally by more than this fraction of the narrower of the two...
    pub grow_vertical_overlap_ratio: f32,
    /// ... and the vertical gap is at most this (and no prose in between).
    pub grow_max_vgap_pt: f32,
    /// A component next to a region joins it when it lies within the
    /// caption's extent widened by this on both sides...
    pub grow_caption_margin_pt: f32,
    /// ... and it overlaps the region vertically by more than this fraction
    /// of the lower of the two...
    pub grow_horizontal_overlap_ratio: f32,
    /// ... or, for a one-line caption, the horizontal gap is at most this.
    pub grow_max_hgap_pt: f32,
    /// The panels of a figure whose caption stands beside it (in the
    /// margin) join its region across a gap of at most this many points.
    pub beside_grow_max_hgap_pt: f32,

    // --- figures whose panels are partly text ---
    /// A figure caption that found no drawing next to it may claim a drawing
    /// above it when the panels between them have sub-captions ("(b) ...",
    /// "(c) ..."); the drawing is at most this far above the caption (in
    /// points).
    pub panel_max_span_pt: f32,
    /// The last sub-caption is at most this far above the caption (in
    /// points).
    pub panel_max_caption_gap_pt: f32,
    /// A sub-caption must overlap the width of the caption by at least this
    /// fraction of its own width.
    pub panel_overlap_ratio: f32,

    // --- uncaptioned graphics ---
    /// An unclaimed component with an image is kept as a graphic when it is
    /// at least this wide and high.
    pub graphic_image_min_pt: f32,
    /// An unclaimed drawing is kept when it has at least this many paths...
    pub graphic_min_paths_count: usize,
    /// ... and is at least this wide ...
    pub graphic_min_width_pt: f32,
    /// ... and at least this high.
    pub graphic_min_height_pt: f32,
    /// An unclaimed ruled table is kept when it has at least this many
    /// rules.
    pub graphic_min_rules_count: usize,
    /// Uncaptioned graphics within this distance of each other are merged.
    pub graphic_merge_pt: f32,
    /// A horizontal rule whose middle lies within a text line, at least this
    /// fraction of the line's height away from its top and bottom, and with
    /// text of that line beside it, is part of the text (a fraction bar, an
    /// overline): not a table rule or a drawing.
    pub inline_rule_band_ratio: f32,
    /// ... or a piece of the formula is within this many font sizes of
    /// the bar's end.
    pub inline_rule_max_gap_em: f32,
    /// A horizontal rule at most this far (in em of the line's font size)
    /// below the baseline of a text line ...
    pub underline_max_drop_em: f32,
    /// ... and within that line's extent, give or take this (in em), is an
    /// underline of the text: not a table rule or a drawing. Table rules are
    /// at least a strut's depth below the baseline of the row above them and
    /// span several cells.
    pub underline_overhang_em: f32,

    // --- tables without graphics ---
    /// A line with at least this many characters ...
    pub fallback_prose_min_chars: usize,
    /// ... that is at least this fraction of the caption's width ...
    pub fallback_prose_width_ratio: f32,
    /// ... (with the caption counted as at least this wide) is prose and
    /// ends the table rows.
    pub fallback_prose_min_width_pt: f32,
    /// Table rows overlap the caption widened by this on both sides.
    pub fallback_x_margin_pt: f32,
    /// A caption whose centre is further than this fraction of the page
    /// width from the page's centre is in one column; its table's rows are
    /// looked for within that column only.
    pub fallback_column_offset_ratio: f32,
    /// Table rows may overlap the caption vertically by this much.
    pub fallback_edge_tol_pt: f32,
    /// A gap between rows larger than this many body sizes ends the table.
    pub fallback_max_row_gap_em: f32,
    /// At least this many rows make a table.
    pub fallback_min_rows_count: usize,
    /// The rows must span more than this many body sizes.
    pub fallback_min_height_em: f32,
    /// A narrow caption in the margin with no graphic takes the lines
    /// beside it, level with it, that are not prose: lines with a gap
    /// wider than this many font sizes between two glyphs (table cells)
    /// are never prose.
    pub beside_cell_gap_em: f32,
    /// A figure region beside its caption takes those rows only when they
    /// stay within its height, give or take this many body font sizes...
    pub beside_rows_height_tol_em: f32,
    /// ... and its graphics cover at most this share of the rows' area (a
    /// diagram mostly made of text).
    pub beside_rows_max_graphics_ratio: f32,

    // --- absorbing text into a region ---
    /// Lines touching the region are absorbed over at most this many
    /// passes (each pass may grow the region).
    pub absorb_max_passes_count: usize,
    /// A line touches the region when it overlaps the region grown by this.
    pub absorb_probe_pt: f32,
    /// A line inside the region grown by this is inside it.
    pub absorb_inside_tol_pt: f32,
    /// A touching line overlaps the probe vertically by at least this
    /// fraction of its height...
    pub absorb_touch_y_ratio: f32,
    /// ... and horizontally by at least this fraction of its width (or has
    /// its centre in the probe).
    pub absorb_touch_x_ratio: f32,

    // --- sub-figure labels around a drawing ---
    /// A label may overlap the drawing by up to this much (negative gap).
    pub label_min_gap_pt: f32,
    /// A label above or below the drawing is at most this far from it.
    pub label_max_vgap_pt: f32,
    /// A label left or right of the drawing is at most this far from it.
    pub label_max_hgap_pt: f32,
    /// A label overlaps the drawing by at least this fraction of its own
    /// width (stacked) or height (beside).
    pub label_overlap_ratio: f32,
    /// A label right above or below the drawing also counts as stacked on it
    /// when its centre is over the drawing and it overlaps the drawing's
    /// width by at least this fraction of its own: the title of one panel
    /// can stick out over the edge of a wide drawing.
    pub label_centred_overlap_ratio: f32,
    /// A label beside the drawing has fewer than this many characters.
    pub side_label_max_chars: usize,
    /// A tick label (a number at the end of an axis, which may stick out
    /// over the drawing's edge) has at most this many characters.
    pub tick_label_max_chars: usize,
    /// ... and sits at most this far (points) from the drawing.
    pub tick_label_max_gap_pt: f32,
    /// A bold line is the drawing's title, not a heading, when its centre
    /// is within this fraction of the drawing's width of the drawing's
    /// centre...
    pub title_center_tol_ratio: f32,
    /// ... (with the drawing counted as at least this wide) ...
    pub title_min_width_pt: f32,
    /// ... and it starts more than this right of the text margin.
    pub title_min_indent_pt: f32,
    /// ... or starts within this distance (in points) of the drawing's left
    /// edge (a chart title set flush left).
    pub title_edge_tol_pt: f32,
    /// Labels around a drawing are looked for in this many passes, each
    /// against the drawing grown by the labels found before.
    pub label_max_passes_count: usize,
    /// A heading is at least the body size minus this.
    pub heading_size_tol_pt: f32,
    /// A bold line with at least this many characters may be a heading.
    pub heading_min_chars: usize,
    /// A line with at least this fraction of bold glyphs is bold.
    pub heading_bold_ratio: f32,
    /// A label is part of a paragraph when another line of a font size
    /// within this ...
    pub attached_size_tol_pt: f32,
    /// ... is more than this many sizes above or below it ...
    pub attached_min_dy_em: f32,
    /// ... and less than this many (normal leading) ...
    pub attached_max_dy_em: f32,
    /// ... and has at least this many characters.
    pub attached_min_chars: usize,

    // --- text between a drawing and its caption ---
    /// Lines between the drawing and the caption may overlap either by this.
    pub between_tol_pt: f32,
    /// Such a line overlaps the drawing by more than this fraction of its
    /// width.
    pub between_overlap_ratio: f32,

    // --- final region ---
    /// The region stops this far before a caption.
    pub caption_clearance_pt: f32,
    /// Clipping against a caption never makes the region lower than this.
    pub min_region_height_pt: f32,
    /// The final region is grown by this margin before it is rendered.
    pub region_margin_pt: f32,
    /// Rules inside a region shorter than this are not table rules.
    pub inner_rule_min_pt: f32,
    /// A filled, unstroked path with at most this many elements is cell
    /// shading.
    pub shading_max_elements_count: u16,
    /// A region with more than this many other paths (not rules, not
    /// shading) is complex.
    pub complex_other_paths_count: usize,
}

impl Default for FloatsConfig {
    #[allow(clippy::too_many_lines, reason = "a flat list of default values, no logic")]
    fn default() -> Self {
        Self {
            body_min_chars: 45,
            body_min_width_em: 18.0,
            caption_label_bold_tenths: 8,
            caption_lookback_count: 40,
            continuation_min_dy_em: 0.4,
            continuation_max_dy_em: 1.45,
            continuation_size_tol_pt: 0.3,
            continuation_overlap_ratio: 0.6,
            continuation_min_chars: 20,
            continuation_short_min_words_count: 2,
            continuation_left_tol_pt: 2.0,
            caption_first_step_max_em: 1.38,
            caption_step_max_leading: 1.15,
            caption_step_slack_pt: 0.5,
            caption_step_min_em: 0.5,
            caption_size_tol_pt: 0.4,
            caption_left_overhang_em: 2.0,
            caption_right_overhang_pt: 2.0,
            narrow_caption_max_width_em: 15.0,
            beside_max_gap_pt: 150.0,
            beside_far_max_gap_pt: 300.0,
            caption_next_label_tol_pt: 2.0,
            caption_word_space_em: 0.3,
            caption_short_line_slack_pt: 2.0,
            caption_max_lines_count: 60,
            caption_rule_min_width_pt: 30.0,
            caption_rule_clear_em: 0.6,
            label_join_baseline_tol_pt: 0.6,
            label_join_size_tol_pt: 0.4,
            label_join_max_gap_em: 4.0,
            grid_cell_pt: 4.0,
            cluster_dilate_pt: 3.0,
            background_image_area_ratio: 0.92,
            cover_max_lines_count: 12,
            background_path_extent_ratio: 0.95,
            shaded_box_min_lines_count: 3,
            shaded_box_line_fill_ratio: 0.8,
            shaded_box_wide_line_min_chars: 30,
            background_panel_min_channel: 235,
            background_panel_min_width_ratio: 0.5,
            shaded_box_min_captions_count: 2,
            side_rule_min_lines_count: 3,
            side_rule_max_gap_em: 3.0,
            min_path_alpha: 8,
            ruled_min_paths_count: 3,
            ruled_rule_tenths: 9,
            booktabs_min_rule_width_pt: 30.0,
            booktabs_max_rules_count: 600,
            booktabs_extent_tol_pt: 3.0,
            booktabs_min_height_pt: 12.0,
            booktabs_caption_overlap_ratio: 0.3,
            booktabs_max_rule_gap_pt: 420.0,
            min_component_pt: 12.0,
            page_sized_area_ratio: 0.8,
            page_sized_min_lines_count: 30,
            rule_table_containment_tol_pt: 2.0,
            rule_table_overhang_pt: 8.0,
            vote_overlap_ratio: 0.5,
            vote_min_gap_pt: -4.0,
            vote_max_gap_pt: 30.0,
            pair_overlap_ratio: 0.5,
            side_tol_pt: 4.0,
            pair_max_dist_pt: 48.0,
            body_between_overlap_ratio: 0.5,
            penalty_figure_below_pt: 14.0,
            penalty_table_against_convention_pt: 30.0,
            penalty_table_above_pt: 3.0,
            penalty_algorithm_above_pt: 3.0,
            penalty_figure_on_table_pt: 10.0,
            penalty_table_on_drawing_pt: 6.0,
            misalign_weight_pt: 40.0,
            grow_touch_pt: 3.0,
            grow_vertical_overlap_ratio: 0.3,
            grow_max_vgap_pt: 32.0,
            grow_caption_margin_pt: 12.0,
            grow_horizontal_overlap_ratio: 0.3,
            grow_max_hgap_pt: 36.0,
            beside_grow_max_hgap_pt: 72.0,
            panel_max_span_pt: 320.0,
            panel_max_caption_gap_pt: 30.0,
            panel_overlap_ratio: 0.5,
            graphic_image_min_pt: 30.0,
            graphic_min_paths_count: 8,
            graphic_min_width_pt: 60.0,
            graphic_min_height_pt: 40.0,
            graphic_min_rules_count: 3,
            graphic_merge_pt: 8.0,
            inline_rule_band_ratio: 0.2,
            inline_rule_max_gap_em: 0.6,
            underline_max_drop_em: 0.3,
            underline_overhang_em: 0.5,
            fallback_prose_min_chars: 50,
            fallback_prose_width_ratio: 0.8,
            fallback_prose_min_width_pt: 150.0,
            fallback_x_margin_pt: 40.0,
            fallback_column_offset_ratio: 0.15,
            fallback_edge_tol_pt: 2.0,
            fallback_max_row_gap_em: 2.4,
            fallback_min_rows_count: 3,
            fallback_min_height_em: 2.5,
            beside_cell_gap_em: 1.5,
            beside_rows_height_tol_em: 3.0,
            beside_rows_max_graphics_ratio: 0.5,
            absorb_max_passes_count: 4,
            absorb_probe_pt: 5.0,
            absorb_inside_tol_pt: 1.0,
            absorb_touch_y_ratio: 0.4,
            absorb_touch_x_ratio: 0.5,
            label_min_gap_pt: -2.0,
            label_max_vgap_pt: 14.0,
            label_max_hgap_pt: 16.0,
            label_overlap_ratio: 0.8,
            label_centred_overlap_ratio: 0.7,
            side_label_max_chars: 30,
            tick_label_max_chars: 8,
            tick_label_max_gap_pt: 4.0,
            title_center_tol_ratio: 0.1,
            title_min_width_pt: 40.0,
            title_min_indent_pt: 15.0,
            title_edge_tol_pt: 4.0,
            label_max_passes_count: 6,
            heading_size_tol_pt: 0.5,
            heading_min_chars: 4,
            heading_bold_ratio: 0.6,
            attached_size_tol_pt: 0.4,
            attached_min_dy_em: 0.5,
            attached_max_dy_em: 1.6,
            attached_min_chars: 30,
            between_tol_pt: 2.0,
            between_overlap_ratio: 0.5,
            caption_clearance_pt: 0.5,
            min_region_height_pt: 1.0,
            region_margin_pt: 3.0,
            inner_rule_min_pt: 6.0,
            shading_max_elements_count: 6,
            complex_other_paths_count: 2,
        }
    }
}

/// A figure, table, algorithm or uncaptioned graphic found on a page.
#[derive(Debug, Clone)]
pub struct Float {
    /// What the float is, from its caption label (`Graphic` without one).
    pub kind: FloatKind,
    /// Index of the page it is on.
    pub page: usize,
    /// Area of the page to render as the float's image.
    pub region: Option<Rect>,
    /// The caption lines, in reading order; empty for an uncaptioned graphic.
    pub caption: Vec<Line>,
    /// E.g. "Figure 2".
    pub label: Option<String>,
    /// Region plus caption.
    pub bbox: Rect,
    /// Text found inside the region (labels, table cells), for alt text.
    pub inner_text: String,
    /// The lines inside the region.
    pub inner_lines: Vec<Line>,
    /// The region looks like a table (ruled, or tabular rows of text).
    pub table_like: bool,
    /// Horizontal rules inside the region with their line width.
    pub hrules: Vec<(Rect, f32)>,
    /// Vertical rules inside the region.
    pub vrules: Vec<Rect>,
    /// The region contains images or drawings other than rules and fills.
    pub complex: bool,
}

/// A caption found on the page.
struct Caption {
    /// Indices of its lines in `PageData::lines`, top to bottom.
    lines: Vec<usize>,
    /// Union of the line boxes.
    bbox: Rect,
    /// Kind of float the label announces.
    kind: FloatKind,
    /// Normalised label, e.g. "Figure 2".
    label: String,
}

/// A connected group of graphics (images, paths, rotated text), or a group
/// of booktabs rules, that a caption may claim.
#[derive(Debug, Clone)]
struct Component {
    /// Union of the element boxes.
    bbox: Rect,
    /// Number of paths and rotated texts.
    n_paths: usize,
    /// Number of images.
    n_images: usize,
    /// Made (almost) only of straight rules: a ruled table.
    table_like: bool,
    /// Number of paths that are horizontal or vertical rules.
    n_rules: usize,
    /// Index of the caption that claimed it.
    owner: Option<usize>,
}

/// One graphic element of the page, as input to the clustering.
struct GraphicElement {
    /// Its bounding box.
    bbox: Rect,
    /// It is an image (otherwise a path or rotated text).
    image: bool,
    /// It is a path that is a horizontal or vertical rule.
    rule: bool,
}

/// A coarse occupancy grid over the page, used to cluster graphic elements
/// into connected components.
struct CellGrid {
    /// Number of columns.
    width: usize,
    /// Number of rows.
    height: usize,
    /// Side of a cell.
    cell_pt: f32,
    /// Growth of each element before it is drawn into the grid.
    dilate_pt: f32,
    /// Occupied cells, row by row.
    filled: Vec<bool>,
}

impl CellGrid {
    /// An empty grid covering `page`, with the cell size and dilation of
    /// `cfg`.
    fn new(page: &PageData, cfg: &FloatsConfig) -> Self {
        let width = (page.width / cfg.grid_cell_pt).ceil() as usize + GRID_PADDING_CELLS;
        let height = (page.height / cfg.grid_cell_pt).ceil() as usize + GRID_PADDING_CELLS;
        Self {
            width,
            height,
            cell_pt: cfg.grid_cell_pt,
            dilate_pt: cfg.cluster_dilate_pt,
            filled: vec![false; width * height],
        }
    }

    /// The cell index of coordinate `coord` along an axis of `len` cells,
    /// clamped to the grid.
    fn cell_index(&self, coord: f32, len: usize) -> usize {
        ((coord / self.cell_pt).floor().max(0.0) as usize).min(len - 1)
    }

    /// The inclusive cell range `(x0, y0, x1, y1)` covered by `rect` after
    /// dilation.
    fn cell_range(&self, rect: &Rect) -> (usize, usize, usize, usize) {
        let col0 = self.cell_index(rect.x0 - self.dilate_pt, self.width);
        let row0 = self.cell_index(rect.y0 - self.dilate_pt, self.height);
        let col1 = self.cell_index(rect.x1 + self.dilate_pt, self.width);
        let row1 = self.cell_index(rect.y1 + self.dilate_pt, self.height);
        (col0, row0, col1, row1)
    }

    /// The index in `filled` of the first cell covered by `rect`.
    fn first_cell(&self, rect: &Rect) -> usize {
        let (col0, row0, _, _) = self.cell_range(rect);
        row0 * self.width + col0
    }

    /// Marks the cells covered by the dilated `rect` as occupied.
    fn mark(&mut self, rect: &Rect) {
        let (col0, row0, col1, row1) = self.cell_range(rect);
        for row in row0..=row1 {
            self.filled[row * self.width + col0..=row * self.width + col1].fill(true);
        }
    }

    /// Labels the connected components of occupied cells (4-connectivity)
    /// by flood fill, in row-major order of their first cell. Returns the
    /// label of every cell ([`UNLABELLED`] for empty cells) and the number
    /// of components.
    fn label_components(&self) -> (Vec<u32>, u32) {
        let width = self.width;
        let n_cells = width * self.height;
        let mut labels = vec![UNLABELLED; n_cells];
        let mut n_labels = 0u32;
        let mut stack = Vec::new();
        for start in 0..n_cells {
            if !self.filled[start] || labels[start] != UNLABELLED {
                continue;
            }
            labels[start] = n_labels;
            stack.push(start);
            while let Some(cell) = stack.pop() {
                let (x, y) = (cell % width, cell / width);
                let mut visit = |neighbour: usize| {
                    if self.filled[neighbour] && labels[neighbour] == UNLABELLED {
                        labels[neighbour] = n_labels;
                        stack.push(neighbour);
                    }
                };
                if x > 0 {
                    visit(cell - 1);
                }
                if x + 1 < width {
                    visit(cell + 1);
                }
                if y > 0 {
                    visit(cell - width);
                }
                if y + 1 < self.height {
                    visit(cell + width);
                }
            }
            n_labels += 1;
        }
        (labels, n_labels)
    }
}

/// A float being built: its region grows while text is absorbed.
struct PendingFloat {
    /// What the float is.
    kind: FloatKind,
    /// Its region so far, if it has one.
    region: Option<Rect>,
    /// Index of its caption, `None` for an uncaptioned graphic.
    cap: Option<usize>,
    /// The region is above the caption.
    above: bool,
    /// The region looks like a table.
    table_like: bool,
}

/// Everything about the page that the steps of [`detect_floats`] read.
struct PageContext<'a> {
    /// The page.
    page: &'a PageData,
    /// Document-wide font statistics.
    stats: &'a DocStats,
    /// The document's fonts.
    fonts: &'a [FontInfo],
    /// The captions of the page.
    captions: &'a [Caption],
    /// For every line of the page, whether it belongs to a caption.
    is_caption_line: &'a [bool],
    /// The thresholds.
    cfg: &'a FloatsConfig,
}

impl PageContext<'_> {
    /// Whether a line of running prose (not a caption line) lies vertically
    /// between `top` and `bottom` and horizontally over `column`: a caption
    /// and a drawing with prose between them do not belong together.
    fn body_between(&self, top: f32, bottom: f32, column: &Rect) -> bool {
        self.page.lines.iter().enumerate().any(|(i, line)| {
            !self.is_caption_line[i]
                && line.bbox.cy() > top
                && line.bbox.cy() < bottom
                && line.bbox.x_overlap(column) > self.cfg.body_between_overlap_ratio * line.bbox.width()
                && body_like(line, self.stats, self.cfg)
        })
    }
}

/// A caption label can be separated from its text by a gap wide enough to
/// break the line in two ("Table 2:      SQuAD results ..."). Joins a bare
/// label with the text that follows it on the same baseline.
///
/// The nearest line to the right on the same baseline and of the same size
/// is merged into the label line; lines that are not bare labels, or have no
/// such neighbour, are left alone.
pub fn join_caption_labels(page: &mut PageData, cfg: &FloatsConfig, lines_cfg: &LinesConfig) {
    let mut i = 0;
    while i < page.lines.len() {
        let text = page.lines[i].text();
        let bare = CAPTION
            .find(&text)
            .is_some_and(|label| label.end() == text.trim_end().len());
        if !bare {
            i += 1;
            continue;
        }
        let (baseline, size, x1) = (page.lines[i].baseline, page.lines[i].size, page.lines[i].bbox.x1);
        let next = page
            .lines
            .iter()
            .enumerate()
            .filter(|(j, line)| {
                *j != i
                    && (line.baseline - baseline).abs() < cfg.label_join_baseline_tol_pt
                    && (line.size - size).abs() < cfg.label_join_size_tol_pt
                    && line.bbox.x0 > x1
                    && line.bbox.x0 - x1 < cfg.label_join_max_gap_em * size
            })
            .min_by(|a, b| a.1.bbox.x0.total_cmp(&b.1.bbox.x0))
            .map(|(j, _)| j);
        let Some(j) = next else {
            i += 1;
            continue;
        };
        let other = page.lines.remove(j);
        let label_idx = if j < i { i - 1 } else { i };
        let label = page.lines[label_idx].clone();
        page.lines[label_idx] = super::lines::merge_row(page.index, vec![label, other], lines_cfg);
        i = label_idx + 1;
    }
}

/// Collects evidence on whether table captions are set above or below the
/// table in this document: returns (votes for above, votes for below) from
/// captions that have a table on one side only. A page without table
/// captions returns `(0, 0)`.
pub fn table_caption_votes(
    page: &PageData,
    stats: &DocStats,
    fonts: &[FontInfo],
    cfg: &FloatsConfig,
) -> (usize, usize) {
    let captions = find_captions(page, stats.leading, fonts, cfg);
    if !captions.iter().any(|caption| caption.kind == FloatKind::Table) {
        return (0, 0);
    }
    let mut comps: Vec<Component> = cluster_graphics(page, cfg)
        .into_iter()
        .filter(|comp| large_enough(comp, cfg))
        .collect();
    comps.extend(rule_tables(page, &captions, cfg));
    let (mut above, mut below) = (0, 0);
    for caption in captions.iter().filter(|caption| caption.kind == FloatKind::Table) {
        let has_below = comps.iter().any(|comp| table_next_to(caption, comp, true, cfg));
        let has_above = comps.iter().any(|comp| table_next_to(caption, comp, false, cfg));
        match (has_above, has_below) {
            (false, true) => above += 1,
            (true, false) => below += 1,
            _ => {}
        }
    }
    (above, below)
}

/// Finds the floats of a page and removes their captions and the text
/// inside them from `page.lines`.
///
/// `table_caption_above`: the document's convention for table captions, if
/// it could be established (see [`table_caption_votes`]).
///
/// Captions claim the best-scoring nearby graphic component, grow their
/// region over adjacent components, and absorb the text inside and around
/// it. Large uncaptioned graphics become `Graphic` floats; table captions
/// without graphics take the tabular rows next to them. The floats are
/// returned captions first (in caption order), then uncaptioned graphics.
pub fn detect_floats(
    page: &mut PageData,
    stats: &DocStats,
    fonts: &[FontInfo],
    table_caption_above: Option<bool>,
    cfg: &FloatsConfig,
) -> Vec<Float> {
    let captions = find_captions(page, stats.leading, fonts, cfg);
    let is_caption_line = caption_line_mask(&captions, page.lines.len());
    let mut absorbed: Vec<Option<usize>> = vec![None; page.lines.len()]; // float index
    let floats = {
        let ctx = PageContext {
            page,
            stats,
            fonts,
            captions: &captions,
            is_caption_line: &is_caption_line,
            cfg,
        };
        let mut comps = candidate_components(page, &captions, cfg);
        let mut cap_region = pair_captions(&ctx, &mut comps, table_caption_above);
        grow_caption_regions(&ctx, &mut comps, &mut cap_region);
        claim_paneled_figures(&ctx, &mut comps, &mut cap_region);
        let graphic_regions = uncaptioned_regions(&comps, cfg);
        let text_left = text_left_margin(&page.lines, cfg);
        let mut pending = pending_floats(&captions, &comps, &cap_region, graphic_regions);
        for float in pending.iter_mut() {
            tabular_fallback(&ctx, float);
            beside_fallback(&ctx, float);
        }
        for (float_idx, float) in pending.iter_mut().enumerate() {
            settle_region(&ctx, &mut absorbed, float_idx, float, text_left);
        }
        pending
            .iter()
            .enumerate()
            .filter_map(|(float_idx, float)| build_float(&ctx, &absorbed, float_idx, float))
            .collect()
    };
    remove_float_lines(&mut page.lines, &is_caption_line, &absorbed);
    floats
}

/// The float kind announced by the label word of a caption ("Table",
/// "Fig.", "Algorithm", ...).
fn caption_kind(word: &str) -> FloatKind {
    let lower = word.to_ascii_lowercase();
    if lower.contains("tab") {
        FloatKind::Table
    } else if lower.contains("algorithm") || lower.contains("listing") {
        FloatKind::Algorithm
    } else {
        FloatKind::Figure
    }
}

/// A line that looks like running prose (as opposed to a label inside a
/// figure or a table cell).
fn body_like(line: &Line, stats: &DocStats, cfg: &FloatsConfig) -> bool {
    line.char_count() >= cfg.body_min_chars && line.bbox.width() > cfg.body_min_width_em * stats.body_size
}

/// Finds the captions of a page. Lines are sorted by baseline; a line that
/// starts with a caption label starts a caption, and the following lines of
/// the same size and column are added to it. Every line belongs to at most
/// one caption.
fn find_captions(page: &PageData, body_leading: f32, fonts: &[FontInfo], cfg: &FloatsConfig) -> Vec<Caption> {
    let lines = &page.lines;
    let rules: Vec<Rect> = page
        .paths
        .iter()
        .filter(|path| path.is_hrule() && path.bbox.width() >= cfg.caption_rule_min_width_pt)
        .map(|path| path.bbox)
        .collect();
    let mut used = vec![false; lines.len()];
    let mut captions = Vec::new();
    for i in 0..lines.len() {
        if used[i] {
            continue;
        }
        let Some(caption) = caption_at(lines, &used, &rules, i, body_leading, fonts, cfg) else {
            continue;
        };
        for &j in &caption.lines {
            used[j] = true;
        }
        captions.push(caption);
    }
    captions
}

/// The caption starting at line `first`, or `None` when that line does not
/// start with a caption label, or the label is a mere reference (no
/// punctuation, not alone, not bold), or the line continues the paragraph
/// above it (unless the label is bold).
fn caption_at(
    lines: &[Line],
    used: &[bool],
    rules: &[Rect],
    first: usize,
    body_leading: f32,
    fonts: &[FontInfo],
    cfg: &FloatsConfig,
) -> Option<Caption> {
    let line = &lines[first];
    let text = line.text();
    let captures = CAPTION.captures(&text)?;
    let whole = captures.get(0).unwrap();
    let label_len = whole.as_str().chars().filter(|ch| !ch.is_whitespace()).count();
    let has_punct = captures.name("punct").is_some_and(|punct| !punct.as_str().is_empty());
    let label_alone = whole.end() == text.len();
    let label_bold = label_is_bold(line, label_len, fonts, cfg);

    if !(has_punct || label_alone || label_bold) {
        return None;
    }
    // "Figure 3. Shows ..." at the start of a line inside a sentence is
    // rejected here; a lone "Fig. 3" reference with trailing lowercase text
    // and no punctuation never gets here.
    if !label_bold && continues_paragraph(lines, first, cfg) {
        return None;
    }
    let (idxs, bbox) = collect_caption_lines(lines, used, rules, first, body_leading, cfg);
    Some(Caption {
        lines: idxs,
        bbox,
        kind: caption_kind(&captures["kind"]),
        label: format!("{} {}", captures["kind"].trim(), &captures["num"]),
    })
}

/// Whether the label (the first `label_len` non-space characters of the
/// line) is set in bold. The caption text after it may be bold too (OpenStax
/// sets whole captions in bold): a reference to a figure in the running
/// text is set like the text around it.
fn label_is_bold(line: &Line, label_len: usize, fonts: &[FontInfo], cfg: &FloatsConfig) -> bool {
    let mut seen = 0;
    let (mut bold_label, mut n_label) = (0, 0);
    for glyph in &line.glyphs {
        if seen >= label_len {
            break;
        }
        n_label += 1;
        bold_label += fonts[glyph.font as usize].bold as usize;
        seen += glyph.text.chars().count();
    }
    n_label > 0 && bold_label * 10 >= n_label * cfg.caption_label_bold_tenths
}

/// Whether line `idx` continues a paragraph: a line of the same size right
/// above it, at normal leading, that overlaps it horizontally.
fn continues_paragraph(lines: &[Line], idx: usize, cfg: &FloatsConfig) -> bool {
    let line = &lines[idx];
    lines[..idx].iter().rev().take(cfg.caption_lookback_count).any(|above| {
        let dy = line.baseline - above.baseline;
        dy > cfg.continuation_min_dy_em * line.size
            && dy < cfg.continuation_max_dy_em * line.size
            && (above.size - line.size).abs() < cfg.continuation_size_tol_pt
            && above.bbox.x_overlap(&line.bbox)
                > cfg.continuation_overlap_ratio * line.bbox.width().min(above.bbox.width())
            && (above.char_count() > cfg.continuation_min_chars || runs_on_short(above, line, cfg))
    })
}

/// Whether the short line `above` runs on into `line` (see
/// [`FloatsConfig::continuation_short_min_words_count`]): "from the
/// rightmost two columns of" above "Table 8.2. We are" in a margin caption.
fn runs_on_short(above: &Line, line: &Line, cfg: &FloatsConfig) -> bool {
    let text = above.text();
    let text = text.trim();
    let mid_sentence = text.ends_with(',') || text.chars().last().is_some_and(char::is_lowercase);
    mid_sentence
        && text.split_whitespace().count() >= cfg.continuation_short_min_words_count
        && (above.bbox.x0 - line.bbox.x0).abs() <= cfg.continuation_left_tol_pt
}

/// Baseline distances a caption's lines are measured against.
#[derive(Clone, Copy)]
struct Leading {
    /// Between the caption's first two lines, once known.
    caption: Option<f32>,
    /// Of the running text.
    body: f32,
}

/// Collects the lines of the caption that starts at line `first` (`rules` are
/// the page's horizontal rules): returns
/// their indices (top to bottom) and their bounding box. The caption ends at
/// a gap, at the next caption, or after a line that ended early.
fn collect_caption_lines(
    lines: &[Line],
    used: &[bool],
    rules: &[Rect],
    first: usize,
    body_leading: f32,
    cfg: &FloatsConfig,
) -> (Vec<usize>, Rect) {
    let head_size = lines[first].size;
    let mut idxs = vec![first];
    let mut bbox = lines[first].bbox;
    let mut prev = first;
    let mut leading: Option<f32> = None;
    loop {
        let prev_line = &lines[prev];
        let Some(j) = next_caption_line(
            lines,
            used,
            prev,
            head_size,
            &bbox,
            Leading {
                caption: leading,
                body: body_leading,
            },
            cfg,
        ) else {
            break;
        };
        let next = &lines[j];
        let next_caption = starts_next_caption(next, &bbox, cfg) && !runs_on_short(prev_line, next, cfg);
        if next_caption || rule_between(rules, prev_line, next, cfg) {
            break;
        }
        // The previous line ended early although the next word would
        // have fit: the caption is over. Not for a narrow caption in a
        // margin, set ragged right, whose lines end early anyway.
        let narrow = bbox.width() <= cfg.narrow_caption_max_width_em * head_size;
        if idxs.len() > 1
            && !narrow
            && prev_line.bbox.x1 + cfg.caption_word_space_em * head_size + unbreakable_start_width(next)
                < bbox.x1 - cfg.caption_short_line_slack_pt
        {
            break;
        }
        if leading.is_none() {
            leading = Some(next.baseline - prev_line.baseline);
        }
        idxs.push(j);
        bbox = bbox.union(&next.bbox);
        prev = j;
        if idxs.len() > cfg.caption_max_lines_count {
            break;
        }
    }
    (idxs, bbox)
}

/// The width of what `line` starts with that cannot be broken across
/// lines: its first word, or a label such as "Table 8.2" (TeX ties the
/// number to its word).
fn unbreakable_start_width(line: &Line) -> f32 {
    let words = if CAPTION.is_match(&line.text()) { 2 } else { 1 };
    let mut seen = 0;
    let mut end = line.bbox.x0;
    for (i, glyph) in line.glyphs.iter().enumerate() {
        if i > 0 && glyph.space_before {
            seen += 1;
            if seen == words {
                break;
            }
        }
        end = end.max(glyph.x1);
    }
    end - line.bbox.x0
}

/// Whether a horizontal rule lies between the lines `upper` and `lower` and
/// spans `lower`: the table's top rule, which ends a caption set above it.
fn rule_between(rules: &[Rect], upper: &Line, lower: &Line, cfg: &FloatsConfig) -> bool {
    rules.iter().any(|rule| {
        let y = rule.cy();
        y > upper.baseline
            && y < lower.baseline - cfg.caption_rule_clear_em * lower.size
            && rule.x0 <= lower.bbox.x0
            && rule.x1 >= lower.bbox.x1
    })
}

/// The index of the line that may continue a caption after line `prev`:
/// the first unused line below it, within the expected leading (`leading`,
/// measured between the first two lines, or a default from `head_size`),
/// of the caption's size and within its horizontal extent `bbox`. `None`
/// when the next line is too far below.
fn next_caption_line(
    lines: &[Line],
    used: &[bool],
    prev: usize,
    head_size: f32,
    bbox: &Rect,
    leading: Leading,
    cfg: &FloatsConfig,
) -> Option<usize> {
    let prev_line = &lines[prev];
    for (j, line) in lines.iter().enumerate().skip(prev + 1) {
        let dy = line.baseline - prev_line.baseline;
        let max_dy = match leading.caption {
            Some(lead) => cfg.caption_step_max_leading * lead + cfg.caption_step_slack_pt,
            None => (cfg.caption_step_max_leading * leading.body + cfg.caption_step_slack_pt)
                .max(cfg.caption_first_step_max_em * head_size),
        };
        if dy > max_dy {
            return None;
        }
        if used[j] || dy < cfg.caption_step_min_em * head_size {
            continue;
        }
        // Smaller text set inside the caption (URLs in a footnote-sized
        // font) can make a line's dominant size differ: the line still
        // continues the caption when some of its glyphs have the caption's
        // size, or when it goes on with the size the previous line ended in.
        let near = |a: f32, b: f32| (a - b).abs() <= cfg.caption_size_tol_pt;
        let visible = |glyph: &&LineGlyph| !glyph.text.trim().is_empty();
        let prev_tail = prev_line.glyphs.iter().rev().find(visible).map(|glyph| glyph.size);
        if !near(line.size, head_size)
            && !line
                .glyphs
                .iter()
                .filter(visible)
                .any(|glyph| near(glyph.size, head_size))
            && !prev_tail.is_some_and(|size| near(line.size, size))
        {
            continue;
        }
        if line.bbox.x_overlap(bbox) <= 0.0 {
            continue;
        }
        // A narrow caption (in a margin) is ragged on the right: a line
        // flush with its left edge continues it, however long.
        let narrow_max = cfg.narrow_caption_max_width_em * head_size;
        let ragged = bbox.width() <= narrow_max
            && (line.bbox.x0 - bbox.x0).abs() <= cfg.caption_right_overhang_pt
            && line.bbox.x1 <= bbox.x0 + narrow_max;
        if line.bbox.x0 < bbox.x0 - cfg.caption_left_overhang_em * head_size
            || (line.bbox.x1 > bbox.x1 + cfg.caption_right_overhang_pt && !ragged)
        {
            continue;
        }
        return Some(j);
    }
    None
}

/// Whether `line`, directly below a caption with box `bbox`, starts the
/// next caption: it is aligned with the caption's left edge and starts with
/// a punctuated label of its own.
fn starts_next_caption(line: &Line, bbox: &Rect, cfg: &FloatsConfig) -> bool {
    if line.bbox.x0 <= bbox.x0 + cfg.caption_next_label_tol_pt {
        let text = line.text();
        CAPTION
            .captures(&text)
            .is_some_and(|captures| captures.name("punct").is_some_and(|punct| !punct.as_str().is_empty()))
    } else {
        false
    }
}

/// Clusters the images, paths and rotated text of the page into connected
/// components (elements closer than the dilation join). Returns an empty
/// list when the page has no graphics.
fn cluster_graphics(page: &PageData, cfg: &FloatsConfig) -> Vec<Component> {
    let elements = graphic_elements(page, cfg);
    if elements.is_empty() {
        return Vec::new();
    }
    let mut grid = CellGrid::new(page, cfg);
    for element in &elements {
        grid.mark(&element.bbox);
    }
    let (labels, n_labels) = grid.label_components();
    let mut comps: Vec<Component> = (0..n_labels)
        .map(|_| Component {
            bbox: Rect::EMPTY,
            n_paths: 0,
            n_images: 0,
            table_like: false,
            n_rules: 0,
            owner: None,
        })
        .collect();
    for element in &elements {
        let comp = &mut comps[labels[grid.first_cell(&element.bbox)] as usize];
        comp.bbox = comp.bbox.union(&element.bbox);
        if element.image {
            comp.n_images += 1;
        } else {
            comp.n_paths += 1;
            comp.n_rules += element.rule as usize;
        }
    }
    // A drawing made (almost) only of straight rules is a ruled table.
    for comp in comps.iter_mut() {
        comp.table_like = comp.n_images == 0
            && comp.n_paths >= cfg.ruled_min_paths_count
            && comp.n_rules * 10 >= comp.n_paths * cfg.ruled_rule_tenths;
    }
    comps
}

/// The graphic elements of the page that can be part of a float: images
/// that are not page backgrounds (a book cover is not a background), rotated text (axis labels belong to the
/// drawing they are part of, arXiv stamps do not), and visible paths that
/// are not page frames or white fills.
fn graphic_elements(page: &PageData, cfg: &FloatsConfig) -> Vec<GraphicElement> {
    let page_area = page.width * page.height;
    let mut elements: Vec<GraphicElement> = Vec::new();
    let cover = (page.index == 0 || page.last) && page.lines.len() <= cfg.cover_max_lines_count;
    for image in &page.images {
        if image.bbox.area() > cfg.background_image_area_ratio * page_area && !cover {
            continue;
        }
        elements.push(GraphicElement {
            bbox: image.bbox,
            image: true,
            rule: false,
        });
    }
    for rotated in &page.rotated {
        let compact: String = rotated.text.chars().filter(|ch| !ch.is_whitespace()).collect();
        if compact.starts_with("arXiv:") || rotated.bbox.is_unset() {
            continue;
        }
        elements.push(GraphicElement {
            bbox: rotated.bbox,
            image: false,
            rule: false,
        });
    }
    let captioned = page.lines.iter().any(|line| CAPTION.is_match(&line.text()));
    let drawn: Vec<&PathBox> = page
        .paths
        .iter()
        .filter(|path| path_is_drawing(page, path, captioned, cfg))
        .collect();
    for path in &drawn {
        if is_background_panel(page, path, &drawn, &elements, cfg) {
            continue;
        }
        elements.push(GraphicElement {
            bbox: path.bbox,
            image: false,
            rule: path.is_hrule() || path.is_vrule(),
        });
    }
    elements
}

/// Whether `path` is the light background of a box that holds other
/// drawings (`paths`, or the images and rotated text in `elements`), see
/// [`FloatsConfig::background_panel_min_channel`].
fn is_background_panel(
    page: &PageData,
    path: &PathBox,
    paths: &[&PathBox],
    elements: &[GraphicElement],
    cfg: &FloatsConfig,
) -> bool {
    let light = path.color[..3]
        .iter()
        .all(|&channel| channel >= cfg.background_panel_min_channel);
    if !(path.filled && !path.stroked && light) || path.bbox.width() < cfg.background_panel_min_width_ratio * page.width
    {
        return false;
    }
    let inside = |bbox: &Rect| bbox.area() < path.bbox.area() && path.bbox.contains(bbox);
    paths
        .iter()
        .any(|other| !std::ptr::eq(*other, path) && inside(&other.bbox))
        || elements.iter().any(|element| inside(&element.bbox))
}

/// Whether `path` is part of a drawing: not a page frame, not the shading
/// or (on a page without captions, `captioned`) the frame of a box of text
/// (a framed figure of text is still a figure), not a white fill or an
/// invisible path, and not a rule that belongs to the text (a fraction bar,
/// an underline, the bar beside a box of text).
fn path_is_drawing(page: &PageData, path: &PathBox, captioned: bool, cfg: &FloatsConfig) -> bool {
    if path.bbox.width() > cfg.background_path_extent_ratio * page.width
        && path.bbox.height() > cfg.background_path_extent_ratio * page.height
    {
        return false;
    }
    let shading = path.filled && !path.stroked;
    let frame =
        path.stroked && !path.is_hrule() && !path.is_vrule() && !captioned && !holds_unreadable(page, &path.bbox);
    if (shading && path.is_white()) || ((shading || frame) && shades_text(page, &path.bbox, cfg)) {
        return false;
    }
    if path.color[3] < cfg.min_path_alpha {
        return false;
    }
    if path.is_hrule() && (inline_rule(page, &path.bbox, cfg) || underline(page, &path.bbox, cfg)) {
        return false;
    }
    !(path.is_vrule() && marks_text(page, &path.bbox, cfg))
}

/// Whether the area `bbox` holds lines of running text, or the captions of
/// several floats: the shading of a box (see
/// [`FloatsConfig::shaded_box_min_lines_count`]).
fn shades_text(page: &PageData, bbox: &Rect, cfg: &FloatsConfig) -> bool {
    let inside = || page.lines.iter().filter(|line| bbox.contains(&line.bbox));
    // A line of the box can still run on into a margin note on its row:
    // only its glyphs inside the box count.
    let rows = || {
        page.lines
            .iter()
            .filter(|line| line.bbox.y0 >= bbox.y0 && line.bbox.y1 <= bbox.y1)
    };
    let text_lines = rows()
        .filter(|line| glyphs_width_inside(line, bbox) >= cfg.body_min_chars)
        .take(cfg.shaded_box_min_lines_count)
        .count();
    let prose_across = rows().any(|line| {
        glyphs_width_inside(line, bbox) >= cfg.shaded_box_wide_line_min_chars
            && glyphs_extent_inside(line, bbox) >= cfg.shaded_box_line_fill_ratio * bbox.width()
    });
    let captions = inside()
        .filter(|line| CAPTION.is_match(&line.text()))
        .take(cfg.shaded_box_min_captions_count)
        .count();
    text_lines >= cfg.shaded_box_min_lines_count || prose_across || captions >= cfg.shaded_box_min_captions_count
}

/// Whether text inside `bbox` has characters with no Unicode mapping: the
/// box stays a picture, which shows them.
fn holds_unreadable(page: &PageData, bbox: &Rect) -> bool {
    page.lines
        .iter()
        .any(|line| bbox.contains(&line.bbox) && line.glyphs.iter().any(|glyph| glyph.text.contains('\u{FFFD}')))
}

/// The length of `line` in Latin characters: its characters other than
/// spaces, a wide (CJK) character counting as two.
/// [`text_width`] of the glyphs of `line` whose middle is inside `bbox`.
fn glyphs_width_inside(line: &Line, bbox: &Rect) -> usize {
    line.glyphs
        .iter()
        .filter(|glyph| {
            let mid = (glyph.x0 + glyph.x1) / 2.0;
            mid >= bbox.x0 && mid <= bbox.x1
        })
        .flat_map(|glyph| glyph.text.chars())
        .filter(|ch| !ch.is_whitespace())
        .map(|ch| if is_wide(ch) { 2 } else { 1 })
        .sum()
}

/// The width spanned by the glyphs of `line` whose middle is inside `bbox`.
fn glyphs_extent_inside(line: &Line, bbox: &Rect) -> f32 {
    let (mut x0, mut x1) = (f32::INFINITY, f32::NEG_INFINITY);
    for glyph in &line.glyphs {
        let mid = (glyph.x0 + glyph.x1) / 2.0;
        if mid >= bbox.x0 && mid <= bbox.x1 && !glyph.text.trim().is_empty() {
            x0 = x0.min(glyph.x0);
            x1 = x1.max(glyph.x1);
        }
    }
    (x1 - x0).max(0.0)
}

/// A character set twice as wide as a Latin letter: CJK ideographs, kana,
/// hangul and fullwidth forms.
fn is_wide(ch: char) -> bool {
    matches!(ch, '\u{1100}'..='\u{115F}' | '\u{2E80}'..='\u{9FFF}' | '\u{AC00}'..='\u{D7AF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF00}'..='\u{FF60}')
}

/// Whether a vertical rule runs along lines of running text that start
/// just right of it: the bar beside a box of text (see
/// [`FloatsConfig::side_rule_min_lines_count`]).
fn marks_text(page: &PageData, rule: &Rect, cfg: &FloatsConfig) -> bool {
    page.lines
        .iter()
        .filter(|line| {
            line.char_count() >= cfg.body_min_chars
                && line.bbox.y0 >= rule.y0
                && line.bbox.y1 <= rule.y1
                && line.bbox.x0 >= rule.x1
                && line.bbox.x0 - rule.x1 <= cfg.side_rule_max_gap_em * line.size
        })
        .take(cfg.side_rule_min_lines_count)
        .count()
        >= cfg.side_rule_min_lines_count
}

/// Whether a horizontal rule underlines text: it lies just below the
/// baseline of a line and within that line's extent (see
/// [`FloatsConfig::underline_max_drop_em`]).
fn underline(page: &PageData, rule: &Rect, cfg: &FloatsConfig) -> bool {
    let cy = rule.cy();
    page.lines.iter().any(|line| {
        let overhang = cfg.underline_overhang_em * line.size;
        cy > line.baseline
            && cy - line.baseline <= cfg.underline_max_drop_em * line.size
            && rule.x0 >= line.bbox.x0 - overhang
            && rule.x1 <= line.bbox.x1 + overhang
    })
}

/// Whether a horizontal rule is a fraction bar in an equation
/// ("R(T) ≤ D²/2α …"): its middle is inside a line of text that goes on to
/// its left or right, and a numerator and a denominator sit right above and
/// below it, within its width. Table rules sit between rows with nothing
/// running through them; chart gridlines have labels beside them but no
/// text stacked on them.
fn inline_rule(page: &PageData, rule: &Rect, cfg: &FloatsConfig) -> bool {
    let cy = rule.cy();
    // Lines whose middle band holds the bar and that reach it: the text runs
    // across the bar (a numerator glyph's line), or a piece of the formula
    // sits right next to it ("+", the next fraction). The other column's
    // text beside a table rule is a gutter away.
    let reaching = |side: Option<bool>| {
        page.lines.iter().any(|line| {
            let b = &line.bbox;
            let band = cfg.inline_rule_band_ratio * b.height();
            let beside = b.x0 < rule.x0 - line.size || b.x1 > rule.x1 + line.size;
            let close = cfg.inline_rule_max_gap_em * line.size;
            let placed = match side {
                None => b.x0 < rule.x1 && b.x1 > rule.x0,
                Some(true) => b.x1 <= rule.x0 + line.size && rule.x0 - b.x1 <= close,
                Some(false) => b.x0 >= rule.x1 - line.size && b.x0 - rule.x1 <= close,
            };
            // A line beside the bar ("; ", "+") may be short; one through it
            // must reach past it.
            cy > b.y0 + band && cy < b.y1 - band && placed && (side.is_some() || beside)
        })
    };
    let through = reaching(None) || reaching(Some(true)) || reaching(Some(false));
    // Glyphs, not lines: numerators of several fractions on one baseline
    // make one wide line.
    let stacked = |above: bool| {
        page.lines.iter().any(|line| {
            line.glyphs.iter().any(|glyph| {
                let ink = &glyph.ink;
                let gap = if above { cy - ink.y1 } else { ink.y0 - cy };
                !ink.is_unset() && ink.cx() > rule.x0 && ink.cx() < rule.x1 && gap > 0.0 && gap < line.size
            })
        })
    };
    through && stacked(true) && stacked(false)
}

/// Groups of horizontal rules with the same extent: tables set with booktabs
/// (or algorithm floats) have no other graphics. Returns one table-like
/// component per group of at least two rules; a group is split where a
/// caption sits between two rules or the rules are implausibly far apart.
fn rule_tables(page: &PageData, captions: &[Caption], cfg: &FloatsConfig) -> Vec<Component> {
    let mut rules: Vec<Rect> = page
        .paths
        .iter()
        .filter(|path| {
            path.is_hrule()
                && path.bbox.width() >= cfg.booktabs_min_rule_width_pt
                && !(path.filled && !path.stroked && path.is_white())
                && !inline_rule(page, &path.bbox, cfg)
        })
        .map(|path| path.bbox)
        .collect();
    if rules.len() < 2 || rules.len() > cfg.booktabs_max_rules_count {
        return Vec::new();
    }
    rules.sort_by(|a, b| a.y0.total_cmp(&b.y0));
    let mut out = Vec::new();
    for (_, group) in group_rules_by_extent(&rules, cfg) {
        if group.len() < 2 {
            continue;
        }
        split_rule_group(&group, captions, &mut out, cfg);
    }
    out
}

/// Groups `rules` (sorted top to bottom) into sets that start and end at
/// the same x, transitively (union-find). Each group keeps the rules in
/// their order; groups are keyed by their root index.
fn group_rules_by_extent(rules: &[Rect], cfg: &FloatsConfig) -> BTreeMap<usize, Vec<Rect>> {
    let mut group_of: Vec<usize> = (0..rules.len()).collect();
    for i in 0..rules.len() {
        for j in i + 1..rules.len() {
            if (rules[i].x0 - rules[j].x0).abs() <= cfg.booktabs_extent_tol_pt
                && (rules[i].x1 - rules[j].x1).abs() <= cfg.booktabs_extent_tol_pt
            {
                let (a, b) = (find_root(&mut group_of, i), find_root(&mut group_of, j));
                if a != b {
                    group_of[b] = a;
                }
            }
        }
    }
    let mut groups: BTreeMap<usize, Vec<Rect>> = BTreeMap::default();
    for (i, rule) in rules.iter().enumerate() {
        let root = find_root(&mut group_of, i);
        groups.entry(root).or_default().push(*rule);
    }
    groups
}

/// The root of `i` in the union-find forest `parents`, compressing the path
/// on the way.
fn find_root(parents: &mut [usize], i: usize) -> usize {
    let mut root = i;
    while parents[root] != root {
        root = parents[root];
    }
    let mut cur = i;
    while parents[cur] != root {
        let next = parents[cur];
        parents[cur] = root;
        cur = next;
    }
    root
}

/// Splits a group of aligned rules (top to bottom) into tables where a
/// caption starts between two rules, or where two rules are implausibly far
/// apart, and appends each table to `out`.
fn split_rule_group(group: &[Rect], captions: &[Caption], out: &mut Vec<Component>, cfg: &FloatsConfig) {
    let mut cur: Vec<Rect> = vec![group[0]];
    for pair in group.windows(2) {
        let (upper, lower) = (&pair[0], &pair[1]);
        let cap_between = captions.iter().any(|caption| {
            caption.bbox.cy() > upper.y1
                && caption.bbox.cy() < lower.y0
                && caption.bbox.x_overlap(upper)
                    > cfg.booktabs_caption_overlap_ratio * caption.bbox.width().min(upper.width())
        });
        if cap_between || lower.y0 - upper.y1 > cfg.booktabs_max_rule_gap_pt {
            flush_rule_table(&mut cur, out, cfg);
        }
        cur.push(*lower);
    }
    flush_rule_table(&mut cur, out, cfg);
}

/// Turns the rules collected in `cur` into a table component (if there are
/// at least two and they are high enough), appends it to `out`, and clears
/// `cur`.
fn flush_rule_table(cur: &mut Vec<Rect>, out: &mut Vec<Component>, cfg: &FloatsConfig) {
    if cur.len() >= 2 {
        let bbox = cur.iter().fold(Rect::EMPTY, |acc, rule| acc.union(rule));
        if bbox.height() >= cfg.booktabs_min_height_pt {
            out.push(Component {
                bbox,
                n_paths: cur.len(),
                n_images: 0,
                table_like: true,
                n_rules: cur.len(),
                owner: None,
            });
        }
    }
    cur.clear();
}

/// Whether a component is large enough in both directions to be a float.
fn large_enough(comp: &Component, cfg: &FloatsConfig) -> bool {
    comp.bbox.width() >= cfg.min_component_pt && comp.bbox.height() >= cfg.min_component_pt
}

/// Whether `comp` sits right below (`table_below`) or right above the
/// caption, overlapping it horizontally: evidence for the caption position
/// convention.
fn table_next_to(caption: &Caption, comp: &Component, table_below: bool, cfg: &FloatsConfig) -> bool {
    let overlaps =
        caption.bbox.x_overlap(&comp.bbox) >= cfg.vote_overlap_ratio * caption.bbox.width().min(comp.bbox.width());
    let gap = if table_below {
        comp.bbox.y0 - caption.bbox.y1
    } else {
        caption.bbox.y0 - comp.bbox.y1
    };
    overlaps && (cfg.vote_min_gap_pt..=cfg.vote_max_gap_pt).contains(&gap)
}

/// For every line of the page, whether it belongs to one of `captions`.
fn caption_line_mask(captions: &[Caption], n_lines: usize) -> Vec<bool> {
    let mut mask = vec![false; n_lines];
    for caption in captions {
        for &i in &caption.lines {
            mask[i] = true;
        }
    }
    mask
}

/// The graphic components a caption may claim: clustered graphics that are
/// large enough and not page-sized decorations, plus booktabs tables that
/// are not part of a drawing (a table that contains drawings replaces them).
fn candidate_components(page: &PageData, captions: &[Caption], cfg: &FloatsConfig) -> Vec<Component> {
    let page_area = page.width * page.height;
    let mut comps: Vec<Component> = cluster_graphics(page, cfg)
        .into_iter()
        .filter(|comp| large_enough(comp, cfg))
        .filter(|comp| {
            !(comp.bbox.area() > cfg.page_sized_area_ratio * page_area
                && page.lines.len() > cfg.page_sized_min_lines_count)
        })
        .collect();
    let tol = cfg.rule_table_containment_tol_pt;
    let tables = rule_tables(page, captions, cfg);
    split_side_by_side_tables(&mut comps, &tables, captions, tol);
    trim_stray_rules(&mut comps, &tables, cfg);
    for table in tables {
        if comps
            .iter()
            .any(|comp| comp.bbox.inflate(tol, tol).contains(&table.bbox))
        {
            continue;
        }
        comps.retain(|comp| !table.bbox.inflate(tol, tol).contains(&comp.bbox));
        comps.push(table);
    }
    comps
}

/// Shrinks a ruled drawing to the one rule table inside it when it sticks
/// out of the table's left or right edge by more than
/// `FloatsConfig::rule_table_overhang_pt`: the extra rules are not part of
/// the table. Drawings with no or several rule tables are left alone.
fn trim_stray_rules(comps: &mut [Component], tables: &[Component], cfg: &FloatsConfig) {
    let tol = cfg.rule_table_containment_tol_pt;
    for comp in comps.iter_mut().filter(|comp| comp.table_like) {
        let mut inside = tables
            .iter()
            .filter(|table| comp.bbox.inflate(tol, tol).contains(&table.bbox));
        let (Some(table), None) = (inside.next(), inside.next()) else {
            continue;
        };
        if comp.bbox.x0 < table.bbox.x0 - cfg.rule_table_overhang_pt
            || comp.bbox.x1 > table.bbox.x1 + cfg.rule_table_overhang_pt
        {
            *comp = table.clone();
        }
    }
}

/// Replaces a ruled drawing that is really two tables set side by side (their
/// borders are closer than the clustering distance) by those tables.
///
/// `tables` are the tables found from the rules alone. A table-like
/// component is split when it contains at least two of them, none overlapping
/// another horizontally, and each has a table caption over its own columns
/// only. `tol` is the slack (in points) of the containment test.
fn split_side_by_side_tables(comps: &mut Vec<Component>, tables: &[Component], captions: &[Caption], tol: f32) {
    let own_caption = |table: &Component, others: &[&Component]| {
        captions.iter().any(|caption| {
            caption.kind == FloatKind::Table
                && caption.bbox.x_overlap(&table.bbox) > 0.0
                && others.iter().all(|other| caption.bbox.x_overlap(&other.bbox) <= 0.0)
        })
    };
    let mut split: Vec<Component> = Vec::new();
    comps.retain(|comp| {
        let inside: Vec<&Component> = tables
            .iter()
            .filter(|table| comp.bbox.inflate(tol, tol).contains(&table.bbox))
            .collect();
        let disjoint = inside.iter().enumerate().all(|(i, table)| {
            inside
                .iter()
                .skip(i + 1)
                .all(|other| table.bbox.x_overlap(&other.bbox) <= 0.0)
        });
        let captioned = inside.iter().enumerate().all(|(i, table)| {
            let others: Vec<&Component> = inside
                .iter()
                .enumerate()
                .filter(|(j, _)| *j != i)
                .map(|(_, other)| *other)
                .collect();
            own_caption(table, &others)
        });
        let side_by_side = comp.table_like && inside.len() >= 2 && disjoint && captioned;
        if side_by_side {
            split.extend(inside.into_iter().cloned());
        }
        !side_by_side
    });
    comps.extend(split);
}

/// Assigns each caption at most one component, best score first, each
/// component to at most one caption. Marks the claimed components' owner and
/// returns, per caption, the claimed region and whether it is above the
/// caption.
fn pair_captions(
    ctx: &PageContext,
    comps: &mut [Component],
    table_caption_above: Option<bool>,
) -> Vec<Option<(Rect, bool)>> {
    // Seed assignment: (score, caption, component, above?).
    let mut pairs: Vec<(f32, usize, usize, bool)> = Vec::new();
    for (cap_idx, caption) in ctx.captions.iter().enumerate() {
        for (comp_idx, comp) in comps.iter().enumerate() {
            if let Some((score, above)) = pair_score(ctx, caption, comp, table_caption_above) {
                pairs.push((score, cap_idx, comp_idx, above));
            }
        }
    }
    pairs.sort_by(|a, b| a.0.total_cmp(&b.0));
    let mut cap_region: Vec<Option<(Rect, bool)>> = vec![None; ctx.captions.len()];
    for &(_, cap_idx, comp_idx, above) in &pairs {
        if cap_region[cap_idx].is_some() || comps[comp_idx].owner.is_some() {
            continue;
        }
        comps[comp_idx].owner = Some(cap_idx);
        cap_region[cap_idx] = Some((comps[comp_idx].bbox, above));
    }
    pair_left_captions(&pairs, comps, &mut cap_region);
    cap_region
}

/// Gives a component to the captions left without one: a caption takes
/// the component of another caption that can move to a component nobody
/// claimed (two margin figures with their captions above them: the second
/// caption, right below the first figure, took it). `pairs` are the
/// possible pairs, best first.
fn pair_left_captions(
    pairs: &[(f32, usize, usize, bool)],
    comps: &mut [Component],
    cap_region: &mut [Option<(Rect, bool)>],
) {
    for &(_, cap_idx, comp_idx, above) in pairs {
        if cap_region[cap_idx].is_some() {
            continue;
        }
        let Some(owner) = comps[comp_idx].owner else { continue };
        let Some(&(_, _, free_idx, owner_above)) = pairs
            .iter()
            .find(|&&(_, other_cap, other_comp, _)| other_cap == owner && comps[other_comp].owner.is_none())
        else {
            continue;
        };
        comps[free_idx].owner = Some(owner);
        cap_region[owner] = Some((comps[free_idx].bbox, owner_above));
        comps[comp_idx].owner = Some(cap_idx);
        cap_region[cap_idx] = Some((comps[comp_idx].bbox, above));
    }
}

/// The score (lower is better) of `caption` claiming `comp`, and whether the
/// component is above the caption. `None` when they cannot belong together:
/// no horizontal overlap, the component is beside the caption or too far,
/// or prose lies between them.
fn pair_score(
    ctx: &PageContext,
    caption: &Caption,
    comp: &Component,
    table_caption_above: Option<bool>,
) -> Option<(f32, bool)> {
    let cfg = ctx.cfg;
    let (cap_box, comp_box) = (&caption.bbox, &comp.bbox);
    let overlap = cap_box.x_overlap(comp_box);
    if overlap <= 0.0
        && let Some(score) = beside_score(ctx, caption, comp)
    {
        return Some(score);
    }
    if overlap < cfg.pair_overlap_ratio * cap_box.width().min(comp_box.width()) {
        return None;
    }
    let (dist, above) = if comp_box.y1 <= cap_box.y0 + cfg.side_tol_pt {
        ((cap_box.y0 - comp_box.y1).max(0.0), true)
    } else if comp_box.y0 >= cap_box.y1 - cfg.side_tol_pt {
        ((comp_box.y0 - cap_box.y1).max(0.0), false)
    } else {
        return None;
    };
    if dist > cfg.pair_max_dist_pt {
        return None;
    }
    let (top, bottom) = if above {
        (comp_box.y1, cap_box.y0)
    } else {
        (cap_box.y1, comp_box.y0)
    };
    if ctx.body_between(top, bottom, cap_box) {
        return None;
    }
    let penalty = side_penalty(caption.kind, above, table_caption_above, cfg);
    let mismatch = kind_mismatch(caption.kind, comp.table_like, cfg);
    let misalign = misalignment(cap_box, comp_box, cfg);
    Some((dist + penalty + mismatch + misalign, above))
}

/// The score of a narrow caption set beside a component, in the margin
/// (see [`FloatsConfig::beside_max_gap_pt`]): the gap between them, and
/// whether the component is above the caption (its middle is higher).
/// `None` when the caption is not narrow, not beside the component, or not
/// level with it.
fn beside_score(ctx: &PageContext, caption: &Caption, comp: &Component) -> Option<(f32, bool)> {
    let cfg = ctx.cfg;
    let (cap_box, comp_box) = (&caption.bbox, &comp.bbox);
    let size = ctx.page.lines[*caption.lines.first()?].size.max(1.0);
    if cap_box.width() > cfg.narrow_caption_max_width_em * size {
        return None;
    }
    let gap = (cap_box.x0 - comp_box.x1).max(comp_box.x0 - cap_box.x1);
    // Side by side: the caption's rows overlap the component's height (its
    // top may stand a little above a plot frame, level with an axis label).
    let level = cap_box.y1 >= comp_box.y0 - cfg.side_tol_pt && cap_box.y0 <= comp_box.y1;
    let max_gap = if caption.lines.len() >= 2 {
        cfg.beside_far_max_gap_pt
    } else {
        cfg.beside_max_gap_pt
    };
    (gap >= 0.0 && gap <= max_gap && level).then(|| (gap, comp_box.cy() < cap_box.cy()))
}

/// Score penalty for a float on an unusual side of its caption.
/// `drawing_above`: the drawing is above its caption.
fn side_penalty(kind: FloatKind, drawing_above: bool, table_caption_above: Option<bool>, cfg: &FloatsConfig) -> f32 {
    match (kind, drawing_above) {
        (FloatKind::Figure, false) => cfg.penalty_figure_below_pt,
        (FloatKind::Table, _) => match table_caption_above {
            Some(caption_above) if caption_above == drawing_above => cfg.penalty_table_against_convention_pt,
            Some(_) => 0.0,
            None if drawing_above => cfg.penalty_table_above_pt,
            None => 0.0,
        },
        (FloatKind::Algorithm, true) => cfg.penalty_algorithm_above_pt,
        _ => 0.0,
    }
}

/// Score penalty for a caption kind that does not fit the component: a
/// ruled table fits a table caption, a drawing fits a figure.
fn kind_mismatch(kind: FloatKind, table_like: bool, cfg: &FloatsConfig) -> f32 {
    match (kind, table_like) {
        (FloatKind::Figure, true) => cfg.penalty_figure_on_table_pt,
        (FloatKind::Table, false) => cfg.penalty_table_on_drawing_pt,
        _ => 0.0,
    }
}

/// Score penalty for a caption off-centre from the component: captions are
/// centred on (or aligned with) their float.
fn misalignment(cap_box: &Rect, comp_box: &Rect, cfg: &FloatsConfig) -> f32 {
    (comp_box.cx() - cap_box.cx()).abs() / cap_box.width().max(comp_box.width()).max(1.0) * cfg.misalign_weight_pt
}

/// Grows the region of every caption over adjacent unclaimed components on
/// the same side of the caption, until nothing more joins.
fn grow_caption_regions(ctx: &PageContext, comps: &mut [Component], cap_region: &mut [Option<(Rect, bool)>]) {
    for (cap_idx, caption) in ctx.captions.iter().enumerate() {
        let Some((mut region, above)) = cap_region[cap_idx] else {
            continue;
        };
        loop {
            let mut grew = false;
            for comp in comps.iter_mut() {
                if comp.owner.is_some() {
                    continue;
                }
                if joins_region(ctx, caption, &region, above, &comp.bbox) {
                    comp.owner = Some(cap_idx);
                    region = region.union(&comp.bbox);
                    grew = true;
                }
            }
            if !grew {
                break;
            }
        }
        cap_region[cap_idx] = Some((region, above));
    }
}

/// Gives a figure caption that found no drawing the drawing above it when
/// the panels in between are announced by sub-captions: a figure of a
/// histogram and two diagrams set as text ("(b) ...", "(c) ...") has only
/// the histogram as a graphic, but all of it belongs to the figure.
///
/// The region runs from the top of the nearest unclaimed drawing above the
/// caption, across the width of the caption, down to the last sub-caption
/// (the lines inside are absorbed later). Nothing is claimed when no
/// sub-caption stands within [`FloatsConfig::panel_max_caption_gap_pt`] of the
/// caption, or when prose lies between that sub-caption and the caption.
fn claim_paneled_figures(ctx: &PageContext, comps: &mut [Component], cap_region: &mut [Option<(Rect, bool)>]) {
    let cfg = ctx.cfg;
    for (cap_idx, caption) in ctx.captions.iter().enumerate() {
        if caption.kind != FloatKind::Figure || cap_region[cap_idx].is_some() {
            continue;
        }
        let cap_box = caption.bbox;
        let Some(comp_idx) = comps
            .iter()
            .enumerate()
            .filter(|(_, comp)| {
                comp.owner.is_none()
                    && !comp.table_like
                    && comp.bbox.y1 <= cap_box.y0
                    && cap_box.y0 - comp.bbox.y0 <= cfg.panel_max_span_pt
                    && comp.bbox.x_overlap(&cap_box) > 0.0
            })
            .max_by(|a, b| a.1.bbox.y1.total_cmp(&b.1.bbox.y1))
            .map(|(i, _)| i)
        else {
            continue;
        };
        let top = comps[comp_idx].bbox.y0;
        let markers: Vec<&Line> = ctx
            .page
            .lines
            .iter()
            .enumerate()
            .filter(|(i, line)| {
                !ctx.is_caption_line[*i]
                    && PANEL_MARKER.is_match(&line.text())
                    && line.bbox.y0 >= top
                    && line.bbox.y1 <= cap_box.y0
                    && line.bbox.x_overlap(&cap_box) >= cfg.panel_overlap_ratio * line.bbox.width()
            })
            .map(|(_, line)| line)
            .collect();
        let Some(bottom) = markers.iter().map(|line| line.bbox.y1).max_by(|a, b| a.total_cmp(b)) else {
            continue;
        };
        if cap_box.y0 - bottom > cfg.panel_max_caption_gap_pt || ctx.body_between(bottom, cap_box.y0, &cap_box) {
            continue;
        }
        let mut region = comps[comp_idx].bbox;
        region.y1 = region.y1.max(bottom);
        region.x0 = region.x0.min(cap_box.x0);
        region.x1 = region.x1.max(cap_box.x1);
        comps[comp_idx].owner = Some(cap_idx);
        cap_region[cap_idx] = Some((region, true));
    }
}

/// Whether the component with box `comp_box` joins a caption's `region`:
/// it is on the same side of the caption (`above`) and touches the region,
/// is stacked on it with no prose in between, or sits beside it.
fn joins_region(ctx: &PageContext, caption: &Caption, region: &Rect, above: bool, comp_box: &Rect) -> bool {
    let cfg = ctx.cfg;
    // A caption beside its figure (in the margin): the panels of the figure
    // stand side by side, away from the caption.
    let beside = caption.bbox.x_overlap(region) <= 0.0;
    if beside {
        let caption_left = caption.bbox.cx() < region.cx();
        let away = if caption_left {
            comp_box.x0 >= caption.bbox.x1
        } else {
            comp_box.x1 <= caption.bbox.x0
        };
        let x_ov = comp_box.x_overlap(region);
        let y_ov = comp_box.y_overlap(region);
        let touching = comp_box.intersects(&region.inflate(cfg.grow_touch_pt, cfg.grow_touch_pt));
        let side_by_side = y_ov > cfg.grow_horizontal_overlap_ratio * comp_box.height().min(region.height())
            && -x_ov <= cfg.beside_grow_max_hgap_pt;
        // Panels one above the other: figures only (a table does not grow
        // over what follows it).
        let stacked = caption.kind == FloatKind::Figure
            && x_ov > cfg.grow_vertical_overlap_ratio * comp_box.width().min(region.width())
            && -y_ov <= cfg.grow_max_vgap_pt
            && {
                let (top, bottom) = if comp_box.cy() < region.cy() {
                    (comp_box.y1, region.y0)
                } else {
                    (region.y1, comp_box.y0)
                };
                !ctx.body_between(top, bottom, comp_box)
            };
        return away && (touching || side_by_side || stacked);
    }
    let same_side = if above {
        comp_box.y1 <= caption.bbox.y0 + cfg.side_tol_pt
    } else {
        comp_box.y0 >= caption.bbox.y1 - cfg.side_tol_pt
    };
    if !same_side {
        return false;
    }
    let x_ov = comp_box.x_overlap(region);
    let y_ov = comp_box.y_overlap(region);
    let touching = comp_box.intersects(&region.inflate(cfg.grow_touch_pt, cfg.grow_touch_pt));
    let vertical = x_ov > cfg.grow_vertical_overlap_ratio * comp_box.width().min(region.width())
        && -y_ov <= cfg.grow_max_vgap_pt
        && {
            let (top, bottom) = if comp_box.cy() < region.cy() {
                (comp_box.y1, region.y0)
            } else {
                (region.y1, comp_box.y0)
            };
            !ctx.body_between(top, bottom, comp_box)
        };
    let within_caption = comp_box.x0 >= caption.bbox.x0 - cfg.grow_caption_margin_pt
        && comp_box.x1 <= caption.bbox.x1 + cfg.grow_caption_margin_pt;
    let horizontal = y_ov > cfg.grow_horizontal_overlap_ratio * comp_box.height().min(region.height())
        && (within_caption || (-x_ov <= cfg.grow_max_hgap_pt && caption.lines.len() == 1));
    touching || vertical || horizontal
}

/// Regions of the unclaimed components that are large enough to matter,
/// overlapping ones merged, with whether they are (all) table-like.
fn uncaptioned_regions(comps: &[Component], cfg: &FloatsConfig) -> Vec<(Rect, bool)> {
    let mut graphic_regions: Vec<(Rect, bool)> = Vec::new();
    for comp in comps.iter().filter(|comp| comp.owner.is_none()) {
        if !significant_graphic(comp, cfg) {
            continue;
        }
        // Merge with an overlapping graphic region if there is one.
        if let Some(region) = graphic_regions.iter_mut().find(|region| {
            region
                .0
                .inflate(cfg.graphic_merge_pt, cfg.graphic_merge_pt)
                .intersects(&comp.bbox)
        }) {
            region.0 = region.0.union(&comp.bbox);
            region.1 &= comp.table_like;
        } else {
            graphic_regions.push((comp.bbox, comp.table_like));
        }
    }
    graphic_regions
}

/// Whether an uncaptioned component is worth keeping as a graphic: a large
/// enough image, a large drawing of many paths, or a ruled table.
fn significant_graphic(comp: &Component, cfg: &FloatsConfig) -> bool {
    let (width, height) = (comp.bbox.width(), comp.bbox.height());
    (comp.n_images >= 1 && width >= cfg.graphic_image_min_pt && height >= cfg.graphic_image_min_pt)
        || (!comp.table_like
            && comp.n_paths >= cfg.graphic_min_paths_count
            && width >= cfg.graphic_min_width_pt
            && height >= cfg.graphic_min_height_pt)
        || (comp.table_like && comp.n_rules >= cfg.graphic_min_rules_count)
}

/// Left margin of the running text on the page (0 when it has no long
/// line).
fn text_left_margin(lines: &[Line], cfg: &FloatsConfig) -> f32 {
    let text_left = lines
        .iter()
        .filter(|line| line.char_count() >= cfg.body_min_chars)
        .map(|line| line.bbox.x0)
        .fold(f32::INFINITY, f32::min);
    if text_left.is_finite() { text_left } else { 0.0 }
}

/// The floats to build: one per caption (with the region it claimed, if
/// any), then one per uncaptioned graphic region.
fn pending_floats(
    captions: &[Caption],
    comps: &[Component],
    cap_region: &[Option<(Rect, bool)>],
    graphic_regions: Vec<(Rect, bool)>,
) -> Vec<PendingFloat> {
    let mut pending: Vec<PendingFloat> = Vec::new();
    for (cap_idx, caption) in captions.iter().enumerate() {
        let table_like = comps.iter().any(|comp| comp.owner == Some(cap_idx) && comp.table_like);
        pending.push(PendingFloat {
            kind: caption.kind,
            region: cap_region[cap_idx].map(|region| region.0),
            cap: Some(cap_idx),
            above: cap_region[cap_idx].map(|region| region.1).unwrap_or(true),
            table_like,
        });
    }
    for (region, table_like) in graphic_regions {
        pending.push(PendingFloat {
            kind: FloatKind::Graphic,
            region: Some(region),
            cap: None,
            above: true,
            table_like,
        });
    }
    pending
}

/// Fallback for tables without any graphics: gives a table caption that
/// claimed nothing the tabular rows below it, or else above it. Other
/// floats are left alone.
fn tabular_fallback(ctx: &PageContext, float: &mut PendingFloat) {
    if float.region.is_some() || !matches!(float.kind, FloatKind::Table) {
        return;
    }
    let caption = &ctx.captions[float.cap.expect("table floats come from a caption")];
    for &down in &[true, false] {
        if let Some(region) = tabular_rows(ctx, caption, down) {
            float.region = Some(region);
            float.above = !down;
            float.table_like = true;
            break;
        }
    }
}

/// The region of the rows of text directly below (`down`) or above the
/// caption, up to a large gap or a line of prose. `None` when there are too
/// few rows, or they are too low to be a table.
/// Gives a narrow caption set in the margin, still without a region, the
/// rows of text beside it: a table without rules, or a diagram made of
/// labels and thin arrows (see [`beside_rows`]).
///
/// A figure beside its caption whose graphics were found takes those rows
/// too when they reach its region, stay within its height and are mostly
/// text (see [`FloatsConfig::beside_rows_height_tol_em`]): the labels of a
/// diagram drawn with thin arrows, of which only the arrow heads are
/// graphics.
fn beside_fallback(ctx: &PageContext, float: &mut PendingFloat) {
    let Some(cap_idx) = float.cap else { return };
    let caption = &ctx.captions[cap_idx];
    let Some(&first) = caption.lines.first() else { return };
    if caption.bbox.width() > ctx.cfg.narrow_caption_max_width_em * ctx.page.lines[first].size.max(1.0) {
        return;
    }
    let Some(rows) = beside_rows(ctx, caption) else { return };
    match float.region {
        None => {
            float.region = Some(rows);
            float.above = false;
            float.table_like = float.kind == FloatKind::Table;
        }
        Some(region)
            if float.kind == FloatKind::Figure
                && caption.bbox.x_overlap(&region) <= 0.0
                && rows.intersects(&region)
                && rows.y0 >= region.y0 - ctx.cfg.beside_rows_height_tol_em * ctx.stats.body_size
                && rows.y1 <= region.y1 + ctx.cfg.beside_rows_height_tol_em * ctx.stats.body_size
                && region.area() <= ctx.cfg.beside_rows_max_graphics_ratio * rows.area() =>
        {
            float.region = Some(region.union(&rows));
        }
        Some(_) => {}
    }
}

/// The lines beside the narrow caption `caption`, on the side away from
/// the margin, from level with its top down to the first prose line or
/// wide gap. `None` when they are too few or too low.
fn beside_rows(ctx: &PageContext, caption: &Caption) -> Option<Rect> {
    let cfg = ctx.cfg;
    let cap_box = caption.bbox;
    let caption_left = cap_box.cx() < ctx.page.width / 2.0;
    let prose = |line: &Line| {
        let wide_gap = line
            .glyphs
            .windows(2)
            .any(|pair| pair[1].x0 - pair[0].x1 > cfg.beside_cell_gap_em * line.size);
        line.char_count() >= cfg.fallback_prose_min_chars && !wide_gap
    };
    let mut candidates: Vec<&Line> = ctx
        .page
        .lines
        .iter()
        .enumerate()
        .filter(|(i, line)| {
            let away = if caption_left {
                line.bbox.x0 >= cap_box.x1
            } else {
                line.bbox.x1 <= cap_box.x0
            };
            !ctx.is_caption_line[*i] && away && line.bbox.y0 >= cap_box.y0 - cfg.fallback_max_row_gap_em * line.size
        })
        .map(|(_, line)| line)
        .collect();
    candidates.sort_by(|a, b| a.bbox.y0.total_cmp(&b.bbox.y0));
    let mut region = Rect::EMPTY;
    let mut edge = cap_box.y0;
    let mut rows = 0;
    for line in candidates {
        if line.bbox.y0 - edge > cfg.fallback_max_row_gap_em * ctx.stats.body_size || prose(line) {
            break;
        }
        region = region.union(&line.bbox);
        edge = edge.max(line.bbox.y1);
        rows += 1;
    }
    (rows >= cfg.fallback_min_rows_count && region.height() > cfg.fallback_min_height_em * ctx.stats.body_size)
        .then_some(region)
}

fn tabular_rows(ctx: &PageContext, caption: &Caption, down: bool) -> Option<Rect> {
    let cfg = ctx.cfg;
    let cap_box = caption.bbox;
    let prose = |line: &Line| {
        line.char_count() >= cfg.fallback_prose_min_chars
            && line.bbox.width()
                >= cfg.fallback_prose_width_ratio * cap_box.width().max(cfg.fallback_prose_min_width_pt)
    };
    let column = cap_box.inflate(cfg.fallback_x_margin_pt, 0.0);
    // A caption in one half of the page heads a table in its column: the
    // other column's lines on the same baselines are not rows of it.
    let in_column = (cap_box.cx() - ctx.page.width / 2.0).abs() > cfg.fallback_column_offset_ratio * ctx.page.width;
    let mut candidates: Vec<&Line> = ctx
        .page
        .lines
        .iter()
        .enumerate()
        .filter(|(i, line)| {
            !ctx.is_caption_line[*i]
                && line.bbox.x_overlap(&column) > 0.0
                && (!in_column || (line.bbox.x0 >= column.x0 && line.bbox.x1 <= column.x1))
                && if down {
                    line.bbox.y0 >= cap_box.y1 - cfg.fallback_edge_tol_pt
                } else {
                    line.bbox.y1 <= cap_box.y0 + cfg.fallback_edge_tol_pt
                }
        })
        .map(|(_, line)| line)
        .collect();
    candidates.sort_by(|a, b| {
        if down {
            a.bbox.y0.total_cmp(&b.bbox.y0)
        } else {
            b.bbox.y1.total_cmp(&a.bbox.y1)
        }
    });
    let mut region = Rect::EMPTY;
    let mut edge = if down { cap_box.y1 } else { cap_box.y0 };
    let mut rows = 0;
    for line in candidates {
        let gap = if down { line.bbox.y0 - edge } else { edge - line.bbox.y1 };
        if gap > cfg.fallback_max_row_gap_em * ctx.stats.body_size || prose(line) {
            break;
        }
        region = region.union(&line.bbox);
        edge = if down {
            edge.max(line.bbox.y1)
        } else {
            edge.min(line.bbox.y0)
        };
        rows += 1;
    }
    (rows >= cfg.fallback_min_rows_count && region.height() > cfg.fallback_min_height_em * ctx.stats.body_size)
        .then_some(region)
}

/// Fixes the final region of float `float_idx`: absorbs the text inside and
/// around it into `absorbed`, keeps it off every caption, and adds the
/// margin. Floats without a region are left alone.
fn settle_region(
    ctx: &PageContext,
    absorbed: &mut [Option<usize>],
    float_idx: usize,
    float: &mut PendingFloat,
    text_left: f32,
) {
    let Some(region) = float.region else { return };
    let mut region = absorb_inner_lines(ctx, absorbed, float_idx, region, float.table_like);
    // A chart drawn only with straight lines (bars, grid) looks like a ruled
    // table, but a figure caption says it is a drawing with labels.
    if !float.table_like || float.kind == FloatKind::Figure {
        region = absorb_side_labels(ctx, absorbed, float_idx, region, text_left);
        region = absorb_rotated_labels(ctx, region);
        region = absorb_edge_ticks(ctx, absorbed, float_idx, region);
    }
    // A caption beside its float (in the margin) neither bounds it above or
    // below nor has lines between them to take.
    let beside = float
        .cap
        .is_some_and(|cap_idx| ctx.captions[cap_idx].bbox.x_overlap(&region) <= 0.0);
    if let Some(cap_idx) = float.cap.filter(|_| !beside) {
        let caption = &ctx.captions[cap_idx];
        region = absorb_between_caption(ctx, absorbed, float_idx, region, caption, float.above);
        // Never let the image overlap its own caption.
        if float.above {
            end_above(&mut region, &caption.bbox, ctx.cfg);
        } else {
            start_below(&mut region, &caption.bbox, ctx.cfg);
        }
    }
    float.region = Some(clear_other_captions(ctx, float.cap, region));
}

/// Absorbs the lines inside or touching `region` (in up to a few passes, as
/// each absorbed line may grow the region) and returns the grown region.
/// Prose that merely touches a non-table region is not part of it.
fn absorb_inner_lines(
    ctx: &PageContext,
    absorbed: &mut [Option<usize>],
    float_idx: usize,
    mut region: Rect,
    table_like: bool,
) -> Rect {
    let cfg = ctx.cfg;
    for _ in 0..cfg.absorb_max_passes_count {
        let mut grew = false;
        let probe = region.inflate(cfg.absorb_probe_pt, cfg.absorb_probe_pt);
        for (i, line) in ctx.page.lines.iter().enumerate() {
            if ctx.is_caption_line[i] || absorbed[i].is_some() {
                continue;
            }
            if !belongs_to_region(ctx, &region, &probe, line, table_like) {
                continue;
            }
            absorbed[i] = Some(float_idx);
            let union = region.union(&line.ink.union(&line.bbox));
            if union != region {
                region = union;
                grew = true;
            }
        }
        if !grew {
            break;
        }
    }
    region
}

/// Whether `line` belongs to `region`: it is inside it, or it touches the
/// `probe` (the region grown a little) and is not prose (unless the region
/// is a table). Prose with its centre outside the region never belongs.
fn belongs_to_region(ctx: &PageContext, region: &Rect, probe: &Rect, line: &Line, table_like: bool) -> bool {
    let cfg = ctx.cfg;
    let tol = cfg.absorb_inside_tol_pt;
    let inside = region.inflate(tol, tol).contains(&line.bbox);
    let touches = (probe.y_overlap(&line.bbox) >= cfg.absorb_touch_y_ratio * line.bbox.height()
        && probe.x_overlap(&line.bbox) >= cfg.absorb_touch_x_ratio * line.bbox.width())
        || probe.contains_point(line.bbox.cx(), line.bbox.cy());
    if !(inside || (touches && (!body_like(line, ctx.stats, cfg) || table_like))) {
        return false;
    }
    // Prose that merely touches the region is not part of it.
    !(!inside
        && body_like(line, ctx.stats, cfg)
        && !region.inflate(tol, tol).contains_point(line.bbox.cx(), line.bbox.cy()))
}

/// Absorbs short isolated labels right above, below or beside the drawing
/// (titles of sub-figures, axis titles), as long as they are not headings
/// or paragraph ends. A few passes, each against the region grown by the
/// labels found before: a chart title sits above its axis title. Returns the
/// grown region.
fn absorb_side_labels(
    ctx: &PageContext,
    absorbed: &mut [Option<usize>],
    float_idx: usize,
    region: Rect,
    text_left: f32,
) -> Rect {
    let cfg = ctx.cfg;
    let mut grown = region;
    for _ in 0..cfg.label_max_passes_count {
        let before = grown;
        for (i, line) in ctx.page.lines.iter().enumerate() {
            if ctx.is_caption_line[i] || absorbed[i].is_some() || line.char_count() >= cfg.body_min_chars {
                continue;
            }
            // A label the grown drawing now encloses (a tick label left of
            // the axis, once the legend above widened the drawing).
            let inside = before
                .inflate(cfg.absorb_inside_tol_pt, cfg.absorb_inside_tol_pt)
                .contains(&line.bbox);
            let stacked = stacked_label(&before, line, cfg);
            if !(inside || stacked || beside_label(&before, line, cfg)) {
                continue;
            }
            if heading_like(ctx, &before, line, stacked, text_left) {
                continue;
            }
            if !attached_to_paragraph(ctx, absorbed, i) {
                absorbed[i] = Some(float_idx);
                grown = grown.union(&line.bbox);
            }
        }
        if grown == before {
            break;
        }
    }
    grown
}

/// Grows `region` by the rotated text right beside it (a y-axis title),
/// which is too thin to be a component of the drawing on its own.
fn absorb_rotated_labels(ctx: &PageContext, region: Rect) -> Rect {
    let cfg = ctx.cfg;
    let mut grown = region;
    for rotated in &ctx.page.rotated {
        let compact: String = rotated.text.chars().filter(|ch| !ch.is_whitespace()).collect();
        if compact.starts_with("arXiv:") || rotated.bbox.is_unset() {
            continue;
        }
        let hgap = if rotated.bbox.cx() < region.cx() {
            region.x0 - rotated.bbox.x1
        } else {
            rotated.bbox.x0 - region.x1
        };
        let vgap = if rotated.bbox.cy() < region.cy() {
            region.y0 - rotated.bbox.y1
        } else {
            rotated.bbox.y0 - region.y1
        };
        let beside = hgap <= cfg.label_max_hgap_pt
            && rotated.bbox.y_overlap(&region) >= cfg.label_overlap_ratio * rotated.bbox.height();
        let stacked = vgap <= cfg.label_max_vgap_pt
            && rotated.bbox.x_overlap(&region) >= cfg.label_overlap_ratio * rotated.bbox.width();
        if beside || stacked {
            grown = grown.union(&rotated.bbox);
        }
    }
    grown
}

/// Whether `line` sits right above or below `region`, mostly within its
/// width.
fn stacked_label(region: &Rect, line: &Line, cfg: &FloatsConfig) -> bool {
    let vgap = if line.bbox.cy() < region.cy() {
        region.y0 - line.bbox.y1
    } else {
        line.bbox.y0 - region.y1
    };
    (cfg.label_min_gap_pt..=cfg.label_max_vgap_pt).contains(&vgap)
        && (line.bbox.x_overlap(region) >= cfg.label_overlap_ratio * line.bbox.width()
            || (line.bbox.cx() > region.x0
                && line.bbox.cx() < region.x1
                && line.bbox.x_overlap(region) >= cfg.label_centred_overlap_ratio * line.bbox.width()))
}

/// Absorbs the tick labels at the ends of the drawing's axes, which stick
/// out over its edge ("200" at the top of the y axis, "130" at the end of
/// the x axis): the labels above, below or beside the drawing are only
/// taken when they lie mostly against it. One pass against the settled
/// region, so that they do not draw in more text.
fn absorb_edge_ticks(ctx: &PageContext, absorbed: &mut [Option<usize>], float_idx: usize, region: Rect) -> Rect {
    let cfg = ctx.cfg;
    let crosses = |lo: f32, hi: f32, edge: f32| lo < edge && edge < hi;
    let near = |gap: f32| (cfg.label_min_gap_pt..=cfg.tick_label_max_gap_pt).contains(&gap);
    let mut grown = region;
    for (i, line) in ctx.page.lines.iter().enumerate() {
        if ctx.is_caption_line[i] || absorbed[i].is_some() || !is_tick_label(line, cfg) {
            continue;
        }
        let bbox = &line.bbox;
        let hgap = (region.x0 - bbox.x1).max(bbox.x0 - region.x1);
        let vgap = (region.y0 - bbox.y1).max(bbox.y0 - region.y1);
        let beside = near(hgap)
            && bbox.cy() > region.y0
            && bbox.cy() < region.y1
            && (crosses(bbox.y0, bbox.y1, region.y0) || crosses(bbox.y0, bbox.y1, region.y1));
        let stacked = near(vgap)
            && bbox.cx() > region.x0
            && bbox.cx() < region.x1
            && (crosses(bbox.x0, bbox.x1, region.x0) || crosses(bbox.x0, bbox.x1, region.x1));
        // Half inside: over the corner of the plot area.
        let straddles = bbox.intersects(&region) && !region.contains(bbox);
        if beside || stacked || straddles {
            absorbed[i] = Some(float_idx);
            grown = grown.union(bbox);
        }
    }
    grown
}

/// Whether `line` is a tick label of an axis: a short number ("130",
/// "0.025", "-2", "40%").
fn is_tick_label(line: &Line, cfg: &FloatsConfig) -> bool {
    let text = line.text();
    let text = text.trim();
    text.chars().count() <= cfg.tick_label_max_chars
        && text.chars().any(|ch| ch.is_ascii_digit())
        && text
            .chars()
            .all(|ch| ch.is_ascii_digit() || ".,-+%$\u{2212}".contains(ch))
}

/// Whether `line` is a short label right left or right of `region`, mostly
/// within its height.
fn beside_label(region: &Rect, line: &Line, cfg: &FloatsConfig) -> bool {
    let hgap = if line.bbox.cx() < region.cx() {
        region.x0 - line.bbox.x1
    } else {
        line.bbox.x0 - region.x1
    };
    (cfg.label_min_gap_pt..=cfg.label_max_hgap_pt).contains(&hgap)
        && line.bbox.y_overlap(region) >= cfg.label_overlap_ratio * line.bbox.height()
        && line.char_count() < cfg.side_label_max_chars
}

/// Whether a label next to `region` looks like a section heading: at body
/// size and numbered, or bold -- unless it is centred over the drawing
/// (`stacked`) and away from the text margin `text_left`, which makes it the
/// drawing's title.
fn heading_like(ctx: &PageContext, region: &Rect, line: &Line, stacked: bool, text_left: f32) -> bool {
    let cfg = ctx.cfg;
    // A title over a drawing is centred on it, starts at its left edge (a
    // chart title), or is set in the drawing's own font (sans-serif labels
    // in a serif paper); a heading starts at the text margin.
    let centred =
        (line.bbox.cx() - region.cx()).abs() <= cfg.title_center_tol_ratio * region.width().max(cfg.title_min_width_pt);
    let at_edge = (line.bbox.x0 - region.x0).abs() <= cfg.title_edge_tol_pt;
    let body_sans = ctx
        .fonts
        .get(ctx.stats.body_font as usize)
        .is_some_and(|font| font.sans);
    let own_font = !body_sans && line.font_frac(ctx.fonts, |font| font.sans) >= cfg.heading_bold_ratio;
    let centred_title =
        (centred || at_edge || own_font) && line.bbox.x0 > text_left + cfg.title_min_indent_pt && stacked;
    line.size >= ctx.stats.body_size - cfg.heading_size_tol_pt
        && (HEADING_LIKE.is_match(&line.text())
            || (line.char_count() >= cfg.heading_min_chars
                && line.font_frac(ctx.fonts, |font| font.bold) >= cfg.heading_bold_ratio
                && !centred_title))
}

/// Whether line `idx` is part of a paragraph: another unabsorbed line of the
/// same size at normal leading on the far side.
fn attached_to_paragraph(ctx: &PageContext, absorbed: &[Option<usize>], idx: usize) -> bool {
    let cfg = ctx.cfg;
    let line = &ctx.page.lines[idx];
    ctx.page.lines.iter().enumerate().any(|(j, other)| {
        j != idx
            && absorbed[j].is_none()
            && (other.size - line.size).abs() < cfg.attached_size_tol_pt
            && (other.baseline - line.baseline).abs() > cfg.attached_min_dy_em * line.size
            && (other.baseline - line.baseline).abs() < cfg.attached_max_dy_em * line.size
            && other.bbox.x_overlap(&line.bbox) > 0.0
            && other.char_count() >= cfg.attached_min_chars
            // The rest of a paragraph is running text; the other entries
            // of a legend are short labels themselves.
            && body_like(other, ctx.stats, cfg)
    })
}

/// Absorbs the sub-captions and labels between the drawing `region` and its
/// `caption` (`above`: the drawing is above the caption) and returns the
/// grown region.
fn absorb_between_caption(
    ctx: &PageContext,
    absorbed: &mut [Option<usize>],
    float_idx: usize,
    mut region: Rect,
    caption: &Caption,
    above: bool,
) -> Rect {
    let cfg = ctx.cfg;
    let (top, bottom) = if above {
        (region.y1 - cfg.between_tol_pt, caption.bbox.y0 + cfg.between_tol_pt)
    } else {
        (caption.bbox.y1 - cfg.between_tol_pt, region.y0 + cfg.between_tol_pt)
    };
    for (i, line) in ctx.page.lines.iter().enumerate() {
        if ctx.is_caption_line[i] || absorbed[i].is_some() || body_like(line, ctx.stats, cfg) {
            continue;
        }
        if line.bbox.y0 >= top
            && line.bbox.y1 <= bottom
            && line.bbox.x_overlap(&region) > cfg.between_overlap_ratio * line.bbox.width()
        {
            absorbed[i] = Some(float_idx);
            region = region.union(&line.bbox);
        }
    }
    region
}

/// Moves the bottom of `region` above `obstacle`, keeping a minimum height.
fn end_above(region: &mut Rect, obstacle: &Rect, cfg: &FloatsConfig) {
    region.y1 = region
        .y1
        .min(obstacle.y0 - cfg.caption_clearance_pt)
        .max(region.y0 + cfg.min_region_height_pt);
}

/// Moves the top of `region` below `obstacle`, keeping a minimum height.
fn start_below(region: &mut Rect, obstacle: &Rect, cfg: &FloatsConfig) {
    region.y0 = region
        .y0
        .max(obstacle.y1 + cfg.caption_clearance_pt)
        .min(region.y1 - cfg.min_region_height_pt);
}

/// Adds the margin to `region`, clips it to the page and keeps it off every
/// caption other than its own (`own_caption`).
fn clear_other_captions(ctx: &PageContext, own_caption: Option<usize>, region: Rect) -> Rect {
    let margin = ctx.cfg.region_margin_pt;
    let mut region = region.inflate(margin, margin).intersect(&ctx.page.rect());
    for (cap_idx, caption) in ctx.captions.iter().enumerate() {
        if own_caption == Some(cap_idx) || !region.intersects(&caption.bbox) {
            continue;
        }
        if caption.bbox.cy() < region.cy() {
            start_below(&mut region, &caption.bbox, ctx.cfg);
        } else {
            end_above(&mut region, &caption.bbox, ctx.cfg);
        }
    }
    region
}

/// Builds the float `float_idx` from its pending state and the lines
/// absorbed into it. `None` when it has neither a region nor a caption.
fn build_float(ctx: &PageContext, absorbed: &[Option<usize>], float_idx: usize, float: &PendingFloat) -> Option<Float> {
    let page = ctx.page;
    let caption: Vec<Line> = float
        .cap
        .map(|cap_idx| {
            ctx.captions[cap_idx]
                .lines
                .iter()
                .map(|&i| page.lines[i].clone())
                .collect()
        })
        .unwrap_or_default();
    let mut inner: Vec<&Line> = page
        .lines
        .iter()
        .enumerate()
        .filter(|(i, _)| absorbed[*i] == Some(float_idx))
        .map(|(_, line)| line)
        .collect();
    inner.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
    let inner_text = inner.iter().map(|line| line.text()).collect::<Vec<_>>().join(" ");
    let mut bbox = float.region.unwrap_or(Rect::EMPTY);
    if let Some(cap_idx) = float.cap {
        bbox = bbox.union(&ctx.captions[cap_idx].bbox);
    }
    if bbox.is_unset() {
        return None;
    }
    let (hrules, vrules, complex) = match float.region {
        Some(region) => inner_rules(page, &region, ctx.cfg),
        None => (Vec::new(), Vec::new(), false),
    };
    Some(Float {
        kind: float.kind,
        page: page.index,
        region: float.region,
        caption,
        label: float.cap.map(|cap_idx| ctx.captions[cap_idx].label.clone()),
        bbox,
        inner_text,
        inner_lines: inner.iter().map(|line| (*line).clone()).collect(),
        table_like: float.table_like,
        hrules,
        vrules,
        complex,
    })
}

/// The horizontal rules (with their line width) and vertical rules whose
/// centre is inside `region`, and whether the region is complex: it holds an
/// image, or more than a few paths that are neither rules nor cell shading.
fn inner_rules(page: &PageData, region: &Rect, cfg: &FloatsConfig) -> (Vec<(Rect, f32)>, Vec<Rect>, bool) {
    let (mut hrules, mut vrules) = (Vec::new(), Vec::new());
    let inside = |rect: &Rect| region.contains_point(rect.cx(), rect.cy());
    let mut complex = page.images.iter().any(|image| region.intersects(&image.bbox));
    let mut other = 0;
    for path in page
        .paths
        .iter()
        .chain(&page.pixel_rules)
        .filter(|path| inside(&path.bbox))
    {
        let white_fill = path.filled && !path.stroked && path.is_white();
        if path.is_hrule() && path.bbox.width() >= cfg.inner_rule_min_pt && !white_fill {
            hrules.push((path.bbox, path.line_width.max(path.bbox.height())));
        } else if path.is_vrule() && path.bbox.height() >= cfg.inner_rule_min_pt && !white_fill {
            vrules.push(path.bbox);
        } else if path.filled && !path.stroked && path.elements <= cfg.shading_max_elements_count {
            // Cell shading.
        } else {
            other += 1;
        }
    }
    complex |= other > cfg.complex_other_paths_count;
    (hrules, vrules, complex)
}

/// Removes the caption lines and the lines absorbed into a float from the
/// text flow.
fn remove_float_lines(lines: &mut Vec<Line>, is_caption_line: &[bool], absorbed: &[Option<usize>]) {
    let mut i = 0;
    lines.retain(|_| {
        let keep = !is_caption_line[i] && absorbed[i].is_none();
        i += 1;
        keep
    });
}

#[cfg(test)]
mod caption_label_tests {
    use super::CAPTION;

    fn label(text: &str) -> Option<(String, bool)> {
        CAPTION.captures(text).map(|captures| {
            let punct = captures.name("punct").is_some_and(|punct| !punct.as_str().is_empty());
            (captures["num"].to_string(), punct)
        })
    }

    #[test]
    fn chapter_numbers_are_part_of_the_label() {
        // A reference in the running text has no punctuation after its number...
        assert_eq!(
            label("Table 1.12 lists the different data values"),
            Some(("1.12".into(), false))
        );
        // ... a caption has.
        assert_eq!(
            label("Figure 5.24. Four rolling die mazes"),
            Some(("5.24".into(), true))
        );
        assert_eq!(label("Figure 3: Results"), Some(("3".into(), true)));
        assert_eq!(label("Figure 3. The model"), Some(("3".into(), true)));
    }
}