pdf-engine 1.2.0

Unified PDF rendering engine — page rendering, text extraction, thumbnails.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
// Copyright (c) 2026 Innovation Trigger B.V.
//
// PDFluent is available under two licences, at your option: the GNU AGPLv3, or
// the PDFluent Commercial Licence. See the LICENSE file in this repository --
// that file travels with the copy you received, which a URL does not.

//! Stitch a table across its wrapped labels and header rows (#574).
//!
//! WHERE AND WHY. [`super::tables::judge_regions`] calls this after
//! [`super::judge::verdict`] chooses, before blocks are assigned to tables.
//! The judge cuts tables short where a row label wraps over two or three lines
//! with the figures on its last one, where a section label row carries no
//! figures, or where year headers stand above the first figure row: the rest
//! of the statement becomes a second table, or prose. This pass works on the
//! judge's own line sets and changes only which lines a chosen set holds; it
//! proposes no region and touches no grid.
//!
//! LINES AND WORDS. A judge [`Line`][super::judge::Line] carries a bbox and
//! joined text; the stitch reads each line's words from the page's
//! [`PageWord`][super::features::PageWord]s, regrouped with
//! [`lines_of`][super::lines::lines_of] -- the same grouping the judge read,
//! so line indices align one to one. Where they do not, the page is left
//! alone.
//!
//! PIECES, NOT ROWS. A line here is a `lines_of` piece: a statement row whose
//! label stands a column gap from its figures arrives as two or more lines at
//! the same height. The walk vets same-height lines left to right, so a label
//! piece is held before its figure piece joins and commits it; the pitch
//! counts only positive gaps between tops, so paired pieces do not read as a
//! zero pitch.
//!
//! WHAT COUNTS AS A FIGURE. A figure token has the shape the table needs --
//! digits, currency, `%`, parentheses, dashes standing for nil -- and stands
//! where a figure stands: first on its piece, or a word space past the word
//! before it ([`FIGURE_GAP_EM`]; leader dots are looked through), or after
//! another figure. Without the position half, a label ending in digits (`Note
//! 12`) would drag the stub edge into the labels and every label would read as
//! prose crossing it; the stub reads only clustered tokens, so even a loose
//! digit that counts cannot drag it alone.
//!
//! THE WALK. Per chosen set, from its figure columns (right-edge clusters with
//! [`MIN_COLUMN_SUPPORT`] lines behind them), its stub edge (the smallest
//! figure left edge less [`STUB_INSET_PT`]), its pitch (the median positive
//! gap between tops) and its median text size: unclaimed lines x-overlapping
//! the hull are vetted outward, downward then upward, nearest first. Downward
//! a line at most [`GAP_FACTOR`] pitches out joins as a label-only line (held
//! until a figure row commits the tight chain back from it, the rest dropped
//! at the walk's end) or a figure row; upward it joins as a header row, a
//! figure row, or the stub cell of either on the same line -- or a lone
//! stub-only line is held, and only a header or figure row joining above
//! commits it, the section label under the column heads. A second consecutive
//! stub-only line caps the table at its top edge, as does a held line nothing
//! commits, released at the walk's end. Vetting for a merge the same line vets
//! like any label, so the walk still crosses it to the set beyond. A header row
//! is a year row whatever its alignment, or words inside the columns' span
//! grouped per column with at most [`HEADER_MAX_WORDS`] a group, or a group
//! spanning two or more columns with a label centred on the columns between
//! its neighbours. An oversize line, a
//! short caption, a downward header or year row, and unaligned figures are
//! stepped over without joining; prose crossing the stub, an outdented label,
//! a second consecutive stub-only line upward while absorbing, and a wider gap
//! end the walk.
//! Sets are walked bottom-up so a lower set has taken its own header before an
//! upper set may reach it.
//!
//! THE MERGE. Where the walk reaches another chosen set whose columns match --
//! [`MERGE_MIN_COLUMNS`] within [`TOL_PT`], [`MERGE_MIN_SHARE`] of them -- the
//! two become one with the lines between, and the walk goes on. No merge
//! across a title, a caption, or a header row between them, and none into a
//! set that starts with its own header: two stacked statements with the same
//! columns stay two.
//!
//! THREE SWITCHES. Absorbing headers upward (`table_stitch_header`), absorbing
//! rows downward (`table_stitch_rows`), and merging sets (`table_stitch_merge`)
//! are measured apart: where its switch is off, the walk vets without claiming
//! and only a merge takes the vetted lines between.
//!
//! EVERY THRESHOLD below is a named constant, each with a test at its boundary
//! value.

use super::features::PageWord;
use super::judge::Line;
use super::lines::lines_of;

/// The geometric tolerance, in points: figure right edges cluster and match
/// within it, and a label may start this far left of the table's edge.
const TOL_PT: f64 = 4.0;
/// How far left of the leftmost figure token the stub edge stands, in points:
/// a gutter, so a label ending where the figures start still ends left of it.
const STUB_INSET_PT: f64 = 2.0;
/// How large the gap to the next line may be, in pitches of the set's own
/// lines, before the walk ends.
const GAP_FACTOR: f64 = 1.6;
/// How much larger than the set's median text size a line may be and still
/// join; above it the line is a heading and never joins.
const TEXT_GROWTH: f64 = 1.15;
/// How many words may stand between two figure columns in an upward header row
/// before it reads as a sentence.
const HEADER_MAX_WORDS: usize = 4;
/// How many of the reached set's figure columns must stand on this set's
/// before the two merge (with [`MERGE_MIN_SHARE`] of them).
const MERGE_MIN_COLUMNS: usize = 2;
/// What share of the reached set's figure columns must stand on this set's
/// before the two merge.
const MERGE_MIN_SHARE: f64 = 0.6;
/// How many lines must carry a figure column before it is one.
const MIN_COLUMN_SUPPORT: usize = 2;
/// How far past the previous word on its piece, in ems of the line's own
/// size, a figure-shaped token must stand to count as a figure; closer and it
/// is label text that happens to hold digits (`Note 12`). A word space is
/// about a third of an em, a column gap more than one.
const FIGURE_GAP_EM: f64 = 0.6;
/// How close a held label must stand to the figures that commit it, in
/// pitches: a wrap continues line to line, while a title breathes two pitches
/// below it. Held lines past this stay pending to the walk's end, so the
/// figures join without them.
const HELD_COMMIT_PITCHES: f64 = 1.0;
/// A row of four-digit years between this and [`YEAR_MAX`] heads a statement;
/// outside it they are amounts.
const YEAR_MIN: u32 = 1800;
/// See [`YEAR_MIN`].
const YEAR_MAX: u32 = 2199;

/// Float dust for edge comparisons; not a threshold.
const EPSILON: f64 = 1e-6;

/// Punctuation a figure token may be made of where it holds no digits:
/// currency, `%`, parentheses, dashes standing for nil, decimal marks.
const FIGURE_PUNCT: &str = "$€£¥¢₹%‰()[]+-–—−.,";
/// Leader fill looked through when the previous word is measured: the amount
/// past the dots is a figure whatever space the dots leave.
const LEADER_DOTS: &str = ".·…";

/// Whether the token has a figure's shape: a digit anywhere, or nothing but
/// [`FIGURE_PUNCT`].
pub(crate) fn is_figure_shape(text: &str) -> bool {
    !text.is_empty()
        && (text.chars().any(|c| c.is_ascii_digit())
            || text.chars().all(|c| FIGURE_PUNCT.contains(c)))
}

/// Whether the token is leader fill rather than a word.
pub(crate) fn is_leader_dots(text: &str) -> bool {
    !text.is_empty() && text.chars().all(|c| LEADER_DOTS.contains(c))
}

/// Whether the token is a year a statement would head its columns with.
pub(crate) fn is_year(text: &str) -> bool {
    text.len() == 4
        && text.chars().all(|c| c.is_ascii_digit())
        && text
            .parse::<u32>()
            .is_ok_and(|year| (YEAR_MIN..=YEAR_MAX).contains(&year))
}

/// Whether the line's text opens as a captioned table or figure: `Table 2`,
/// `Figure 12`, `Fig. 3` -- a keyword and a number, so `Table of contents` is
/// not one.
fn is_caption(text: &str) -> bool {
    let lower = text.trim_start().to_lowercase();
    // Longest first, so `figures` wins over `fig`.
    for key in [
        "figures", "figure", "tables", "table", "figs.", "fig.", "figs", "fig",
    ] {
        if let Some(rest) = lower.strip_prefix(key) {
            let rest = rest.trim_start_matches([' ', '\t', '(', '[']);
            return rest.chars().next().is_some_and(|c| c.is_ascii_digit());
        }
    }
    false
}

/// Whether the piece reads bold: most of its words in a bold face.
fn is_bold(piece: &[&PageWord]) -> bool {
    !piece.is_empty() && piece.iter().filter(|w| w.bold).count() * 2 > piece.len()
}

/// The middle value, upper of the two in the middle; 0.0 of nothing.
fn median(mut values: Vec<f64>) -> f64 {
    if values.is_empty() {
        return 0.0;
    }
    values.sort_by(f64::total_cmp);
    values[values.len() / 2]
}

/// Which words of a piece count as figures: figure-shaped, letter-free, not
/// leader fill, and opening the piece, [`FIGURE_GAP_EM`] past the previous
/// non-dot word, or after another figure -- and symmetrically followed by a
/// figure or a gap, not by label text at a word space. Piece-first is exact,
/// not a default: pieces break at 1.5 em gaps, so a word opening one stands
/// past a column gap or opens its row. The neighbours are what keep `Note 12`
/// and `Q1 sales` labels while tight figures (`9,898 2,240` at half an em)
/// still count.
fn candidacy(piece: &[&PageWord], size: f64) -> Vec<bool> {
    let em = if size <= 0.0 { 1.0 } else { size };
    let shaped = |word: &PageWord| {
        is_figure_shape(&word.text)
            && !is_leader_dots(&word.text)
            && !word.text.chars().any(|c| c.is_ascii_alphabetic())
    };
    let mut out = vec![false; piece.len()];
    let mut prev: Option<usize> = None;
    for (j, word) in piece.iter().enumerate() {
        out[j] = shaped(word)
            && prev
                .is_none_or(|p| out[p] || (word.bbox[0] - piece[p].bbox[2]) / em >= FIGURE_GAP_EM);
        if !is_leader_dots(&word.text) {
            prev = Some(j);
        }
    }
    let mut next: Option<usize> = None;
    for j in (0..piece.len()).rev() {
        out[j] = out[j]
            && next.is_none_or(|n| {
                out[n] || (piece[n].bbox[0] - piece[j].bbox[2]) / em >= FIGURE_GAP_EM
            });
        if !is_leader_dots(&piece[j].text) {
            next = Some(j);
        }
    }
    out
}

/// A set's figure columns and stub edge from its figure tokens as `(left,
/// right, line)`: right edges clustered with spans of at most [`TOL_PT`], a
/// column the mean of a cluster with [`MIN_COLUMN_SUPPORT`] lines behind it.
/// The stub is the smallest left edge among the clustered tokens less
/// [`STUB_INSET_PT`], not among all of them: a lone digit far left (`Note 12`
/// set loose) is no column and must not drag the edge into the labels.
fn figure_columns(tokens: &[(f64, f64, usize)]) -> (Vec<f64>, f64) {
    let mut edges = tokens.to_vec();
    edges.sort_by(|a, b| a.1.total_cmp(&b.1));
    let mut columns = Vec::new();
    let mut lefts: Vec<f64> = Vec::new();
    let mut start = 0;
    while start < edges.len() {
        let mut end = start + 1;
        while end < edges.len() && edges[end].1 - edges[start].1 <= TOL_PT {
            end += 1;
        }
        let mut supporting: Vec<usize> =
            edges[start..end].iter().map(|&(_, _, line)| line).collect();
        supporting.sort_unstable();
        supporting.dedup();
        if supporting.len() >= MIN_COLUMN_SUPPORT {
            let mean = edges[start..end]
                .iter()
                .map(|&(_, right, _)| right)
                .sum::<f64>()
                / (end - start) as f64;
            columns.push(mean);
            lefts.extend(edges[start..end].iter().map(|&(left, _, _)| left));
        }
        start = end;
    }
    let stub = lefts.into_iter().fold(f64::INFINITY, f64::min) - STUB_INSET_PT;
    (columns, stub)
}

/// The figure columns a spanning header run stands for: every column strictly
/// between its neighbouring runs' ink, or every column where it stands alone
/// on its line. A centred label over eight figure columns spans eight, not
/// the three its own words happen to cover; with header groups left and right
/// it spans only the columns between them.
fn spanning_columns(prev_x1: f64, next_x0: f64, columns: &[f64]) -> Vec<f64> {
    columns
        .iter()
        .copied()
        .filter(|&c| prev_x1 < c && c < next_x0)
        .collect()
}

/// What a chosen set walks with: its figure columns, stub edge, pitch,
/// median text size, and whether its lines read bold -- all read once from
/// its own lines.
struct Params {
    columns: Vec<f64>,
    stub: f64,
    pitch: f64,
    size: f64,
    bold: bool,
}

/// One chosen set while the pass runs.
struct Live {
    members: Vec<usize>,
    hull: [f64; 4],
    /// The claimed edges: what the walk may look past.
    bottom: f64,
    top: f64,
    /// The walked edges: claimed lines plus held or vetted ones, what gaps
    /// are measured from. A three-line wrap puts its figures two pitches past
    /// the set's edge; the held label lines lend the walk their reach, and
    /// where no figure row commits them the edges go back.
    walk_bottom: f64,
    walk_top: f64,
    /// The median text size of its lines as chosen, fixed for the walk.
    size: f64,
    /// Whether most of its lines as chosen read bold.
    bold: bool,
    /// Whether it absorbed a header row upward: it starts with its own
    /// header, and no set merges into that head.
    headed: bool,
    consumed: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Dir {
    Down,
    Up,
}

/// What the walk does with a line.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Class {
    /// It joins now: a figure row, or a label-only line upward.
    Join,
    /// It joins upward as a header row and heads the set.
    Header,
    /// It is label-only downward, held until a figure row commits it -- or a
    /// lone stub-only line upward, held until a header or figure row above
    /// commits it.
    Hold,
    /// It never joins but the walk goes on past it.
    Skip,
    /// It ends the walk: prose, an outdented label, a full-width caption.
    Stop,
}

struct Walker<'a> {
    lines: &'a [Line],
    pieces: Vec<Vec<&'a PageWord>>,
    sizes: Vec<f64>,
    candidates: Vec<Vec<bool>>,
    texts: Vec<String>,
    sets: Vec<Live>,
    owner: Vec<Option<usize>>,
    absorb_header: bool,
    absorb_rows: bool,
    merge: bool,
    split_stacked: bool,
}

impl<'a> Walker<'a> {
    fn new(
        lines: &'a [Line],
        pieces: Vec<Vec<&'a PageWord>>,
        chosen: &[Vec<usize>],
        absorb_header: bool,
        absorb_rows: bool,
        merge: bool,
        split_stacked: bool,
    ) -> Self {
        let sizes: Vec<f64> = pieces
            .iter()
            .zip(lines.iter())
            .map(|(piece, line)| {
                if piece.is_empty() {
                    line.bbox[3] - line.bbox[1]
                } else {
                    median(piece.iter().map(|w| w.size).collect())
                }
            })
            .collect();
        let candidates: Vec<Vec<bool>> = pieces
            .iter()
            .zip(sizes.iter())
            .map(|(piece, &size)| candidacy(piece, size))
            .collect();
        // The lines as their words read: the judge's joined text spaces every
        // glyph fragment out, which no caption opens with.
        let texts: Vec<String> = pieces
            .iter()
            .map(|piece| {
                piece
                    .iter()
                    .map(|word| word.text.as_str())
                    .collect::<Vec<_>>()
                    .join(" ")
            })
            .collect();
        let mut sets = Vec::with_capacity(chosen.len());
        let mut owner = vec![None; lines.len()];
        for set in chosen {
            let mut hull = [
                f64::INFINITY,
                f64::INFINITY,
                f64::NEG_INFINITY,
                f64::NEG_INFINITY,
            ];
            for &i in set {
                let b = lines[i].bbox;
                hull[0] = hull[0].min(b[0]);
                hull[1] = hull[1].min(b[1]);
                hull[2] = hull[2].max(b[2]);
                hull[3] = hull[3].max(b[3]);
                owner[i] = Some(sets.len());
            }
            let bold = set.iter().filter(|&&i| is_bold(&pieces[i])).count() * 2 > set.len();
            sets.push(Live {
                members: set.clone(),
                hull,
                bottom: hull[1],
                top: hull[3],
                walk_bottom: hull[1],
                walk_top: hull[3],
                size: median(set.iter().map(|&i| sizes[i]).collect()),
                bold,
                headed: false,
                consumed: false,
            });
        }
        Self {
            lines,
            pieces,
            sizes,
            candidates,
            texts,
            sets,
            owner,
            absorb_header,
            absorb_rows,
            merge,
            split_stacked,
        }
    }

    /// Whether the walk in `dir` claims the lines it takes: upward the
    /// header switch, downward the rows switch. Where it does not, a taken
    /// line is only vetted, and only a merge takes it.
    fn claims(&self, dir: Dir) -> bool {
        match dir {
            Dir::Down => self.absorb_rows,
            Dir::Up => self.absorb_header,
        }
    }

    /// The walking parameters of a set, or `None` where it has no figure
    /// columns or no pitch to walk with: it is left alone.
    fn params_of(&self, set: usize) -> Option<Params> {
        let (columns, stub) = figure_columns(&self.figure_tokens_of(set));
        if columns.is_empty() {
            return None;
        }
        let mut tops: Vec<f64> = self.sets[set]
            .members
            .iter()
            .map(|&i| self.lines[i].bbox[3])
            .collect();
        tops.sort_by(f64::total_cmp);
        let gaps: Vec<f64> = tops
            .windows(2)
            .map(|pair| pair[1] - pair[0])
            .filter(|&gap| gap > 0.0)
            .collect();
        // Paired pieces of one row share a top; the pitch is the row step, so
        // only positive gaps count. A single line falls back to its height.
        let pitch = if gaps.is_empty() {
            median(
                self.sets[set]
                    .members
                    .iter()
                    .map(|&i| self.lines[i].bbox[3] - self.lines[i].bbox[1])
                    .collect(),
            )
        } else {
            median(gaps)
        };
        if pitch <= 0.0 {
            return None;
        }
        Some(Params {
            columns,
            stub,
            pitch,
            size: self.sets[set].size,
            bold: self.sets[set].bold,
        })
    }

    /// The set's figure tokens as `(left, right, line)`.
    fn figure_tokens_of(&self, set: usize) -> Vec<(f64, f64, usize)> {
        let mut tokens = Vec::new();
        for &i in &self.sets[set].members {
            for (j, word) in self.pieces[i].iter().enumerate() {
                if self.candidates[i][j] {
                    tokens.push((word.bbox[0], word.bbox[2], i));
                }
            }
        }
        tokens
    }

    /// The next line to vet in `dir`: x-overlapping the hull, not the set's
    /// own, not vetted yet. First whatever shares the last vetted line's row,
    /// left to right, so joining one piece never hides its siblings past the
    /// moved edge; then the nearest line past the set's edge, same-height
    /// lines left to right so a label piece is held before its figure piece
    /// joins.
    fn nearest(
        &self,
        set: usize,
        dir: Dir,
        seen: &[bool],
        active: Option<[f64; 4]>,
    ) -> Option<usize> {
        let hull = self.sets[set].hull;
        let (bottom, top) = (self.sets[set].bottom, self.sets[set].top);
        let mut best: Option<usize> = None;
        let mut best_row = false;
        for (i, line) in self.lines.iter().enumerate() {
            if self.owner[i] == Some(set) || seen[i] {
                continue;
            }
            let b = line.bbox;
            if b[0] > hull[2] || b[2] < hull[0] {
                continue;
            }
            let shares_row = active.is_some_and(|a| b[1] < a[3] && b[3] > a[1]);
            let eligible = shares_row
                || match dir {
                    Dir::Down => b[3] <= bottom + EPSILON,
                    Dir::Up => b[1] >= top - EPSILON,
                };
            if !eligible {
                continue;
            }
            let better = match (shares_row, best) {
                (true, Some(k)) if best_row => b[0] < self.lines[k].bbox[0],
                (true, _) => true,
                (false, Some(_)) if best_row => false,
                (false, _) => match dir {
                    Dir::Down => {
                        best.is_none_or(|k| match b[3].total_cmp(&self.lines[k].bbox[3]) {
                            std::cmp::Ordering::Greater => true,
                            std::cmp::Ordering::Equal => b[0] < self.lines[k].bbox[0],
                            std::cmp::Ordering::Less => false,
                        })
                    }
                    Dir::Up => best.is_none_or(|k| match b[1].total_cmp(&self.lines[k].bbox[1]) {
                        std::cmp::Ordering::Less => true,
                        std::cmp::Ordering::Equal => b[0] < self.lines[k].bbox[0],
                        std::cmp::Ordering::Greater => false,
                    }),
                },
            };
            if better {
                best = Some(i);
                best_row = shares_row;
            }
        }
        best
    }

    /// Whether every word right of the stub has a figure column at its right
    /// edge. True of no right words; callers with a stub-only line decide
    /// for it before asking.
    fn is_figure_row(&self, line: usize, right: &[usize], params: &Params) -> bool {
        right.iter().all(|&j| {
            self.candidates[line][j]
                && params
                    .columns
                    .iter()
                    .any(|&c| (self.pieces[line][j].bbox[2] - c).abs() <= TOL_PT)
        })
    }

    /// Whether the words right of the stub read as a heading over the
    /// columns: each within their span, and every run between two columns a
    /// per-column group of at most [`HEADER_MAX_WORDS`] words -- or a group
    /// spanning two or more columns with a centred label, a spanning header.
    /// A row of years is one whatever its alignment. False of no right
    /// words: a header hangs over the columns, and a stub-only line is a
    /// title or a note, never a header.
    fn is_header_row(&self, line: usize, right: &[usize], params: &Params) -> bool {
        if right.is_empty() {
            return false;
        }
        let (Some(&first), Some(&last)) = (params.columns.first(), params.columns.last()) else {
            return false;
        };
        if right.iter().any(|&j| {
            let b = self.pieces[line][j].bbox;
            b[0] < first - TOL_PT || b[2] > last + TOL_PT
        }) {
            return false;
        }
        if right.iter().all(|&j| is_year(&self.pieces[line][j].text)) {
            return true;
        }
        let mut order = right.to_vec();
        order.sort_by(|&a, &b| {
            self.pieces[line][a].bbox[0].total_cmp(&self.pieces[line][b].bbox[0])
        });
        let mut run: Vec<usize> = Vec::new();
        let mut runs: Vec<Vec<usize>> = Vec::new();
        for &j in &order {
            if let Some(&p) = run.last() {
                let between = params
                    .columns
                    .iter()
                    .any(|&c| self.pieces[line][p].bbox[2] < c && c < self.pieces[line][j].bbox[0]);
                if between {
                    runs.push(std::mem::take(&mut run));
                }
            }
            run.push(j);
        }
        runs.push(run);
        let extents: Vec<(f64, f64)> = runs
            .iter()
            .map(|run| {
                let x0 = run
                    .iter()
                    .map(|&j| self.pieces[line][j].bbox[0])
                    .fold(f64::INFINITY, f64::min);
                let x1 = run
                    .iter()
                    .map(|&j| self.pieces[line][j].bbox[2])
                    .fold(f64::NEG_INFINITY, f64::max);
                (x0, x1)
            })
            .collect();
        runs.iter().enumerate().all(|(k, run)| {
            let prev = extents[..k]
                .last()
                .map(|&(_, x1)| x1)
                .unwrap_or(f64::NEG_INFINITY);
            let next = extents
                .get(k + 1)
                .map(|&(x0, _)| x0)
                .unwrap_or(f64::INFINITY);
            self.is_header_group(line, run, prev, next, params)
        })
    }

    /// Whether one run of header words reads as a per-column group or a
    /// spanning header: over at most one column it may hold
    /// [`HEADER_MAX_WORDS`] words; over two or more its label must sit
    /// centred on the columns it spans -- every column between its neighbours,
    /// or every column standing alone -- within [`TOL_PT`], whatever its
    /// length. A wide run off centre is a title, not a header.
    fn is_header_group(
        &self,
        line: usize,
        run: &[usize],
        prev_x1: f64,
        next_x0: f64,
        params: &Params,
    ) -> bool {
        let x0 = run
            .iter()
            .map(|&j| self.pieces[line][j].bbox[0])
            .fold(f64::INFINITY, f64::min);
        let x1 = run
            .iter()
            .map(|&j| self.pieces[line][j].bbox[2])
            .fold(f64::NEG_INFINITY, f64::max);
        let covered: Vec<f64> = params
            .columns
            .iter()
            .copied()
            .filter(|&c| x0 - EPSILON <= c && c <= x1 + EPSILON)
            .collect();
        if covered.len() < 2 {
            return run.len() <= HEADER_MAX_WORDS;
        }
        let span = spanning_columns(prev_x1, next_x0, &params.columns);
        let (first, last) = match (span.first(), span.last()) {
            (Some(&first), Some(&last)) => (first, last),
            _ => (
                covered.first().copied().unwrap_or(x0),
                covered.last().copied().unwrap_or(x1),
            ),
        };
        ((x0 + x1) / 2.0 - (first + last) / 2.0).abs() <= TOL_PT
    }

    /// Whether the stub-only line shares its row with a header or figure
    /// piece: same block, overlapping height, words right of the stub that
    /// read as a header or figure row. That stub cell joins with its row;
    /// without such a sibling the line stands alone.
    fn shares_row_with_table(&self, line: usize, params: &Params) -> bool {
        let (block, bbox) = (self.lines[line].block, self.lines[line].bbox);
        (0..self.lines.len()).any(|j| {
            j != line
                && self.lines[j].block == block
                && self.lines[j].bbox[1] < bbox[3]
                && self.lines[j].bbox[3] > bbox[1]
                && {
                    let right: Vec<usize> = (0..self.pieces[j].len())
                        .filter(|&k| self.pieces[j][k].bbox[2] > params.stub)
                        .collect();
                    !right.is_empty()
                        && (self.is_header_row(j, &right, params)
                            || self.is_figure_row(j, &right, params))
                }
        })
    }

    /// Whether the right words read as prose crossing the stub: a non-figure
    /// among them and no header over the columns.
    fn reads_as_prose(&self, line: usize, right: &[usize], params: &Params) -> bool {
        !self.is_header_row(line, right, params)
            && right
                .iter()
                .any(|&j| !is_figure_shape(&self.pieces[line][j].text))
    }

    /// What the walk does with a line in reach. `held_stub` tells whether the
    /// walk already holds a stub-only line it has not committed: a second
    /// consecutive one upward caps the walk.
    fn classify(
        &self,
        line: usize,
        params: &Params,
        dir: Dir,
        hull: [f64; 4],
        held_stub: bool,
    ) -> Class {
        let right: Vec<usize> = (0..self.pieces[line].len())
            .filter(|&j| self.pieces[line][j].bbox[2] > params.stub)
            .collect();
        // A caption is a boundary marker, never table content: full-width it
        // reads as prose and ends the walk, short it is stepped over and the
        // merge guard refuses to join across it.
        if is_caption(&self.texts[line]) {
            return if self.reads_as_prose(line, &right, params) {
                Class::Stop
            } else {
                Class::Skip
            };
        }
        if self.sizes[line] > TEXT_GROWTH * params.size {
            return Class::Skip;
        }
        if right.is_empty() {
            if self.lines[line].bbox[0] >= hull[0] - TOL_PT {
                if dir == Dir::Down {
                    return Class::Hold;
                }
                // Vetting for a merge the line is only crossed, never taken,
                // so it vets like any label; a bold one over a regular table
                // still caps the walk, as it always did. Only while absorbing
                // does a lone stub-only line cap the table at its top edge.
                if !self.claims(dir) {
                    if !params.bold && is_bold(&self.pieces[line]) {
                        return Class::Stop;
                    }
                    return Class::Join;
                }
                // Upward the stub cell of a header or figure row joins with
                // its row; a lone stub-only line is held, and only a header
                // or figure row joining above commits it -- the section label
                // under the column heads. A second consecutive one is a title
                // over that label and caps the table, as does the bare title
                // nothing commits, released at the walk's end.
                return if self.shares_row_with_table(line, params) {
                    Class::Join
                } else if held_stub {
                    Class::Stop
                } else {
                    Class::Hold
                };
            }
            return Class::Stop;
        }
        if right.iter().all(|&j| is_year(&self.pieces[line][j].text)) {
            return if dir == Dir::Down {
                Class::Skip
            } else {
                Class::Header
            };
        }
        if self.is_figure_row(line, &right, params) {
            return Class::Join;
        }
        if self.is_header_row(line, &right, params) {
            return if dir == Dir::Down {
                Class::Skip
            } else {
                Class::Header
            };
        }
        if right
            .iter()
            .all(|&j| is_figure_shape(&self.pieces[line][j].text))
        {
            return Class::Skip;
        }
        Class::Stop
    }

    /// Take a line into the set: claimed where the direction's switch is on,
    /// tracked where it only vets. A claim moves every edge; a tracked line
    /// only lends the walk its reach, and the edges go back where no merge
    /// takes it.
    fn take(&mut self, set: usize, line: usize, dir: Dir, vetted: &mut Vec<usize>) {
        if self.claims(dir) {
            self.claim(set, line);
        } else {
            vetted.push(line);
            self.stretch_walk(set, line);
        }
    }

    /// Lend the walk a held or vetted line's reach without claiming it.
    fn lend(&mut self, set: usize, line: usize) {
        self.stretch_walk(set, line);
    }

    fn claim(&mut self, set: usize, line: usize) {
        self.owner[line] = Some(set);
        self.sets[set].members.push(line);
        let b = self.lines[line].bbox;
        let live = &mut self.sets[set];
        live.hull[0] = live.hull[0].min(b[0]);
        live.hull[1] = live.hull[1].min(b[1]);
        live.hull[2] = live.hull[2].max(b[2]);
        live.hull[3] = live.hull[3].max(b[3]);
        live.bottom = live.bottom.min(b[1]);
        live.top = live.top.max(b[3]);
        live.walk_bottom = live.walk_bottom.min(b[1]);
        live.walk_top = live.walk_top.max(b[3]);
    }

    fn stretch_walk(&mut self, set: usize, line: usize) {
        let b = self.lines[line].bbox;
        let live = &mut self.sets[set];
        live.hull[0] = live.hull[0].min(b[0]);
        live.hull[1] = live.hull[1].min(b[1]);
        live.hull[2] = live.hull[2].max(b[2]);
        live.hull[3] = live.hull[3].max(b[3]);
        live.walk_bottom = live.walk_bottom.min(b[1]);
        live.walk_top = live.walk_top.max(b[3]);
    }

    fn checkpoint_of(&self, set: usize) -> (f64, f64, f64, f64, [f64; 4]) {
        let live = &self.sets[set];
        (
            live.bottom,
            live.top,
            live.walk_bottom,
            live.walk_top,
            live.hull,
        )
    }

    fn restore(&mut self, set: usize, point: (f64, f64, f64, f64, [f64; 4])) {
        let live = &mut self.sets[set];
        live.bottom = point.0;
        live.top = point.1;
        live.walk_bottom = point.2;
        live.walk_top = point.3;
        live.hull = point.4;
    }

    /// Commit the held stub-only line a header or figure row joins above:
    /// the upward mirror of [`commit_chain`][Self::commit_chain], the tight
    /// chain from the set's top edge up to the joining row, each within
    /// [`HELD_COMMIT_PITCHES`] of the next. At most one line is ever held
    /// upward -- a second consecutive stub-only line stops the walk -- so the
    /// chain is one link either side of it; where either link breathes past a
    /// pitch the line stays pending to the walk's end and the row joins
    /// without it. `edge` is the set's top edge before the joining row was
    /// taken: the take moves it past the held line.
    fn commit_chain_up(
        &mut self,
        set: usize,
        joiner: usize,
        params: &Params,
        held: &mut Vec<usize>,
        edge: f64,
    ) {
        let mut cursor = edge;
        for &h in held.iter() {
            if self.lines[h].bbox[1] - cursor > HELD_COMMIT_PITCHES * params.pitch {
                return;
            }
            cursor = self.lines[h].bbox[3];
        }
        if self.lines[joiner].bbox[1] - cursor > HELD_COMMIT_PITCHES * params.pitch {
            return;
        }
        for h in std::mem::take(held) {
            self.claim(set, h);
        }
    }

    /// Commit the held labels a figure row joins after: the tight chain back
    /// from the figure, each within [`HELD_COMMIT_PITCHES`] of the next. A
    /// wrap commits whole; a label left two pitches behind -- a title the
    /// walk stepped under -- stays pending to the walk's end. Only a merge
    /// takes every held line, with the lines between.
    fn commit_chain(&mut self, set: usize, figure: usize, params: &Params, held: &mut Vec<usize>) {
        let mut cursor = self.lines[figure].bbox[3];
        while let Some(&h) = held.last() {
            if self.lines[h].bbox[1] - cursor > HELD_COMMIT_PITCHES * params.pitch {
                break;
            }
            held.pop();
            self.claim(set, h);
            cursor = self.lines[h].bbox[3];
        }
    }

    /// One walk outward from a set's edge: downward then upward per set, each
    /// set bottom-up across the page.
    fn walk(&mut self, set: usize, dir: Dir) {
        let params = match self.params_of(set) {
            Some(params) => params,
            None => return,
        };
        let mut held: Vec<usize> = Vec::new();
        let mut vetted: Vec<usize> = Vec::new();
        let mut seen = vec![false; self.lines.len()];
        // Held and vetted lines lend the walk their reach; where no figure
        // row or merge takes them the edges go back, so trailing labels leave
        // nothing behind. The checkpoint moves past every claim.
        let mut checkpoint = self.checkpoint_of(set);
        let mut active: Option<[f64; 4]> = None;
        loop {
            let Some(i) = self.nearest(set, dir, &seen, active) else {
                break;
            };
            seen[i] = true;
            active = Some(self.lines[i].bbox);
            let gap = match dir {
                Dir::Down => self.sets[set].walk_bottom - self.lines[i].bbox[3],
                Dir::Up => self.lines[i].bbox[1] - self.sets[set].walk_top,
            };
            if gap > GAP_FACTOR * params.pitch {
                break;
            }
            if let Some(other) = self.owner[i] {
                if self.merge && self.try_merge(set, other, dir, &params, &held, &vetted) {
                    held.clear();
                    vetted.clear();
                    checkpoint = self.checkpoint_of(set);
                    continue;
                }
                break;
            }
            match self.classify(i, &params, dir, self.sets[set].hull, !held.is_empty()) {
                Class::Join => {
                    let edge = self.sets[set].top;
                    self.take(set, i, dir, &mut vetted);
                    if self.claims(dir) {
                        match dir {
                            Dir::Down => self.commit_chain(set, i, &params, &mut held),
                            Dir::Up => self.commit_chain_up(set, i, &params, &mut held, edge),
                        }
                        checkpoint = self.checkpoint_of(set);
                    }
                }
                Class::Header => {
                    let edge = self.sets[set].top;
                    self.take(set, i, dir, &mut vetted);
                    self.sets[set].headed = true;
                    if self.claims(dir) {
                        // Headers only join upward; downward they skip.
                        if dir == Dir::Up {
                            self.commit_chain_up(set, i, &params, &mut held, edge);
                        }
                        checkpoint = self.checkpoint_of(set);
                    }
                }
                Class::Hold => {
                    self.lend(set, i);
                    if self.claims(dir) {
                        held.push(i);
                    } else {
                        vetted.push(i);
                    }
                }
                Class::Skip => {}
                Class::Stop => break,
            }
        }
        self.restore(set, checkpoint);
    }

    /// Whether a title, a caption, or a header row lies between the two sets'
    /// facing edges: kinds the walk stepped over, read against the walking
    /// set's columns. Members of either set do not count: a label the walk
    /// took is content, not a boundary.
    fn blocked_between(&self, walker: usize, reached: usize, dir: Dir, params: &Params) -> bool {
        let hull = self.sets[walker].hull;
        let (low, high) = match dir {
            Dir::Down => (self.sets[reached].top, self.sets[walker].bottom),
            Dir::Up => (self.sets[walker].top, self.sets[reached].bottom),
        };
        let biggest = self.sets[walker].size.max(self.sets[reached].size);
        for (i, line) in self.lines.iter().enumerate() {
            if self.owner[i] == Some(walker) || self.owner[i] == Some(reached) {
                continue;
            }
            let b = line.bbox;
            if b[0] > hull[2] || b[2] < hull[0] {
                continue;
            }
            if b[3] > high + EPSILON || b[1] < low - EPSILON {
                continue;
            }
            if line.kind == "heading"
                || self.sizes[i] > TEXT_GROWTH * biggest
                || is_bold(&self.pieces[i])
            {
                return true;
            }
            if line.kind == "caption" || is_caption(&self.texts[i]) {
                return true;
            }
            let right: Vec<usize> = (0..self.pieces[i].len())
                .filter(|&j| self.pieces[i][j].bbox[2] > params.stub)
                .collect();
            // A figure row reads as a header by shape, so only a header that
            // is no figure row -- or a row of years, which is one -- blocks.
            if self.is_header_row(i, &right, params)
                && (!self.is_figure_row(i, &right, params)
                    || right.iter().all(|&j| is_year(&self.pieces[i][j].text)))
                && !right.is_empty()
            {
                return true;
            }
        }
        false
    }

    /// Whether the lower set starts with its own year head: its topmost line
    /// carries a year right of the stub and reads as no figure row
    /// (`table_split_stacked`, #574). The merge guard refuses into a set that
    /// absorbed a header, but a year head the judge chose the set with --
    /// `Year Ended December 31, 2009` opening the lower of two stacked
    /// statements -- is a member, not an absorbed line, so the merge passed
    /// it and the two came out as one.
    fn starts_with_year_head(&self, lower: usize, params: &Params) -> bool {
        let top = self.sets[lower]
            .members
            .iter()
            .max_by(|&&a, &&b| self.lines[a].bbox[3].total_cmp(&self.lines[b].bbox[3]));
        let Some(&line) = top else {
            return false;
        };
        let right: Vec<usize> = (0..self.pieces[line].len())
            .filter(|&j| self.pieces[line][j].bbox[2] > params.stub)
            .collect();
        !right.is_empty()
            && !self.is_figure_row(line, &right, params)
            && right.iter().any(|&j| is_year(&self.pieces[line][j].text))
    }

    /// Merge the walking set with the reached one where their columns match
    /// and nothing lies between: the reached set and the vetted lines between
    /// join the walker, which walks on. Held labels join with the merge: the
    /// reached set's figure rows stand after them.
    fn try_merge(
        &mut self,
        walker: usize,
        reached: usize,
        dir: Dir,
        params: &Params,
        held: &[usize],
        vetted: &[usize],
    ) -> bool {
        let (columns, _) = figure_columns(&self.figure_tokens_of(reached));
        let matched = columns
            .iter()
            .filter(|&c| params.columns.iter().any(|&a| (a - c).abs() <= TOL_PT))
            .count();
        if matched < MERGE_MIN_COLUMNS {
            return false;
        }
        if matched as f64 / columns.len() as f64 >= MERGE_MIN_SHARE {
            let lower_headed = match dir {
                Dir::Down => self.sets[reached].headed,
                Dir::Up => self.sets[walker].headed,
            };
            let lower = match dir {
                Dir::Down => reached,
                Dir::Up => walker,
            };
            if lower_headed
                || self.blocked_between(walker, reached, dir, params)
                || (self.split_stacked && self.starts_with_year_head(lower, params))
            {
                return false;
            }
            let between = if self.claims(dir) { held } else { vetted };
            for &i in between {
                self.claim(walker, i);
            }
            let members = std::mem::take(&mut self.sets[reached].members);
            for i in members {
                self.claim(walker, i);
            }
            self.sets[reached].consumed = true;
            return true;
        }
        false
    }

    fn finish(mut self) -> Vec<Vec<usize>> {
        let mut out = Vec::new();
        for set in &mut self.sets {
            if set.consumed {
                continue;
            }
            set.members.sort_unstable();
            out.push(std::mem::take(&mut set.members));
        }
        out
    }
}

/// The stitch's words: glyph fragments rejoined into the words the rules read.
///
/// The page's words arrive one per glyph run, down to a character, and every
/// rule here -- figure candidacy, year and caption shapes, header word counts
/// -- was written and tested against whole words. Fragments of one line join
/// where the shared word rule joins them, across neither a style change (a
/// bold run past a regular one is a new word) nor a substantial overlap
/// (overstruck runs are two words); anything else parts with the gap it
/// stands in. Line for line, so the regrouping still aligns with the judge.
fn join_line_words(pieces: &[Vec<&PageWord>]) -> Vec<Vec<PageWord>> {
    pieces
        .iter()
        .map(|line| {
            let mut sorted: Vec<&PageWord> = line.to_vec();
            sorted.sort_by(|a, b| a.bbox[0].total_cmp(&b.bbox[0]));
            let mut words: Vec<PageWord> = Vec::with_capacity(sorted.len());
            for word in sorted {
                let join = match words.last() {
                    None => false,
                    Some(last) => {
                        let em = last.size.max(word.size).max(f64::MIN_POSITIVE);
                        let gap = word.bbox[0] - last.bbox[2];
                        let drift = (word.bbox[1] - last.bbox[1]).abs();
                        last.bold == word.bold
                            && last.italic == word.italic
                            && last.font == word.font
                            && (last.size - word.size).abs() <= 0.1 * em
                            && gap > -0.1 * em
                            && crate::words_join::pieces_join(gap, drift, em)
                    }
                };
                if join {
                    let last = words.last_mut().expect("a join has a last word");
                    last.text.push_str(&word.text);
                    last.bbox[0] = last.bbox[0].min(word.bbox[0]);
                    last.bbox[1] = last.bbox[1].min(word.bbox[1]);
                    last.bbox[2] = last.bbox[2].max(word.bbox[2]);
                    last.bbox[3] = last.bbox[3].max(word.bbox[3]);
                    last.size = last.size.max(word.size);
                } else {
                    words.push((*word).clone());
                }
            }
            words
        })
        .collect()
}

/// Stitch the judge's chosen line sets across wrapped labels and header rows.
///
/// `lines` are the judge's lines of the page and `words` its words, regrouped
/// per block with [`lines_of`][super::lines::lines_of] so piece `i` is line
/// `i`; `chosen` holds line indices. With `absorb_header` the walk takes
/// header rows above each set; with `absorb_rows` it takes label-only lines
/// and figure rows below; with `merge` a set reached across such lines joins
/// the walker where their columns match; with `split_stacked` the merge
/// refuses into a set starting with its own year head. With none of them, or
/// where the regrouping does not align, the sets come back as chosen.
#[allow(clippy::too_many_arguments)]
pub(crate) fn stitch_sets(
    lines: &[Line],
    words: &[PageWord],
    n_blocks: usize,
    chosen: &[Vec<usize>],
    absorb_header: bool,
    absorb_rows: bool,
    merge: bool,
    split_stacked: bool,
) -> Vec<Vec<usize>> {
    if (!absorb_header && !absorb_rows && !merge) || chosen.is_empty() {
        return chosen.to_vec();
    }
    let mut pieces = Vec::with_capacity(lines.len());
    for block in 0..n_blocks {
        for piece in lines_of(block, words) {
            if !piece.is_empty() {
                pieces.push(piece);
            }
        }
    }
    if pieces.len() != lines.len() {
        return chosen.to_vec();
    }
    // The words the rules read: glyph fragments rejoined line for line. The
    // count of lines is unchanged, so the regrouping still aligns with the
    // judge; only the words inside each piece are whole now.
    let joined = join_line_words(&pieces);
    let pieces: Vec<Vec<&PageWord>> = joined.iter().map(|line| line.iter().collect()).collect();
    let mut walker = Walker::new(
        lines,
        pieces,
        chosen,
        absorb_header,
        absorb_rows,
        merge,
        split_stacked,
    );
    // Bottom-up: a lower set takes its own header before an upper set's walk
    // may reach it, so headed sets refuse the merge.
    let mut order: Vec<usize> = (0..chosen.len()).collect();
    order.sort_by(|&a, &b| walker.sets[a].top.total_cmp(&walker.sets[b].top));
    for k in order {
        if walker.sets[k].consumed {
            continue;
        }
        walker.walk(k, Dir::Down);
        walker.walk(k, Dir::Up);
    }
    walker.finish()
}

#[cfg(test)]
mod tests {
    use super::*;

    const SIZE: f64 = 10.0;
    const PITCH: f64 = 12.0;

    /// One word: text and x-span at its row's height.
    struct W<'a> {
        text: &'a str,
        x0: f64,
        x1: f64,
        bold: bool,
    }

    fn w(text: &str, x0: f64, x1: f64) -> W<'_> {
        W {
            text,
            x0,
            x1,
            bold: false,
        }
    }

    fn wb(text: &str, x0: f64, x1: f64) -> W<'_> {
        W {
            text,
            x0,
            x1,
            bold: true,
        }
    }

    /// One visual row: top, size, words left to right.
    struct Row<'a> {
        top: f64,
        size: f64,
        words: Vec<W<'a>>,
    }

    fn row(top: f64, words: Vec<W<'_>>) -> Row<'_> {
        Row {
            top,
            size: SIZE,
            words,
        }
    }

    fn row_at(top: f64, size: f64, words: Vec<W<'_>>) -> Row<'_> {
        Row { top, size, words }
    }

    /// One block: kind and rows. Table rows stand one block per row so pieces
    /// stay in row order; prose stands as one paragraph block.
    struct Blk<'a> {
        kind: &'static str,
        rows: Vec<Row<'a>>,
    }

    fn blk<'a>(kind: &'static str, rows: Vec<Row<'a>>) -> Blk<'a> {
        Blk { kind, rows }
    }

    struct Page {
        words: Vec<PageWord>,
        lines: Vec<Line>,
        n_blocks: usize,
    }

    /// The page as the judge reads it: words grouped into pieces exactly as
    /// `judge::lines_of_page` groups them, so indices align by construction.
    fn page_of(blocks: &[Blk]) -> Page {
        let mut words = Vec::new();
        for (b, block) in blocks.iter().enumerate() {
            for r in &block.rows {
                for word in &r.words {
                    words.push(PageWord {
                        text: word.text.to_string(),
                        bbox: [word.x0, r.top - r.size, word.x1, r.top],
                        block: b,
                        span: 0,
                        size: r.size,
                        bold: word.bold,
                        italic: false,
                        font: None,
                        color: None,
                    });
                }
            }
        }
        let mut lines = Vec::new();
        for (b, block) in blocks.iter().enumerate() {
            for piece in lines_of(b, &words) {
                if piece.is_empty() {
                    continue;
                }
                let mut bbox = [
                    f64::INFINITY,
                    f64::INFINITY,
                    f64::NEG_INFINITY,
                    f64::NEG_INFINITY,
                ];
                for w in &piece {
                    bbox[0] = bbox[0].min(w.bbox[0]);
                    bbox[1] = bbox[1].min(w.bbox[1]);
                    bbox[2] = bbox[2].max(w.bbox[2]);
                    bbox[3] = bbox[3].max(w.bbox[3]);
                }
                lines.push(Line {
                    bbox,
                    text: piece
                        .iter()
                        .map(|w| w.text.as_str())
                        .collect::<Vec<_>>()
                        .join(" "),
                    words: piece.len(),
                    digits: piece
                        .iter()
                        .filter(|w| w.text.chars().any(|c| c.is_ascii_digit()))
                        .count(),
                    kind: block.kind,
                    table: None,
                    grid_fill: f64::NAN,
                    grid_columns: f64::NAN,
                    block: b,
                    list: f64::NAN,
                });
            }
        }
        Page {
            words,
            lines,
            n_blocks: blocks.len(),
        }
    }

    /// A figure row with three tight figures (one figure piece): label at the
    /// stub, columns at 400, 445, 490, stub edge at 358.
    fn figrow<'a>(top: f64, label: &'a str, figs: [&'a str; 3]) -> Row<'a> {
        row(
            top,
            vec![
                w(label, 72.0, 300.0),
                w(figs[0], 360.0, 400.0),
                w(figs[1], 405.0, 445.0),
                w(figs[2], 450.0, 490.0),
            ],
        )
    }

    fn stitch(
        page: &Page,
        chosen: &[Vec<usize>],
        absorb_header: bool,
        absorb_rows: bool,
        merge: bool,
    ) -> Vec<Vec<usize>> {
        stitch_sets(
            &page.lines,
            &page.words,
            page.n_blocks,
            chosen,
            absorb_header,
            absorb_rows,
            merge,
            false,
        )
    }

    /// The line holding `needle`, which must be unique on the page.
    fn find(page: &Page, needle: &str) -> usize {
        let found: Vec<usize> = page
            .lines
            .iter()
            .enumerate()
            .filter(|(_, l)| l.text.contains(needle))
            .map(|(i, _)| i)
            .collect();
        assert_eq!(
            found.len(),
            1,
            "{needle:?} is not unique: {:?}",
            found
                .iter()
                .map(|&i| page.lines[i].text.as_str())
                .collect::<Vec<_>>()
        );
        found[0]
    }

    /// The pieces of the rows labelled `labels`: each label piece and whatever
    /// shares its top to its right in its block. Same block, because a prose
    /// column may share the top from the next block over.
    fn rows_of(page: &Page, labels: &[&str]) -> Vec<usize> {
        let mut set = Vec::new();
        for label in labels {
            let l = find(page, label);
            set.push(l);
            let (top, right, block) = (
                page.lines[l].bbox[3],
                page.lines[l].bbox[2],
                page.lines[l].block,
            );
            for (i, line) in page.lines.iter().enumerate() {
                if i != l
                    && line.block == block
                    && line.bbox[3].total_cmp(&top) == std::cmp::Ordering::Equal
                    && line.bbox[0] > right
                {
                    set.push(i);
                }
            }
        }
        set.sort_unstable();
        set
    }

    fn texts_of(page: &Page, set: &[usize]) -> Vec<String> {
        let mut texts: Vec<String> = set.iter().map(|&i| page.lines[i].text.clone()).collect();
        texts.sort();
        texts
    }

    /// With both switches off the sets come back as chosen. Every behavior
    /// test asserts this alongside an on-effect that differs, so each fails
    /// with the pass removed.
    fn assert_off_is_identity(page: &Page, chosen: &[Vec<usize>]) {
        assert_eq!(stitch(page, chosen, false, false, false), chosen);
    }

    /// Four figure rows and the two sets the judge cut them into: two rows a
    /// set, so either half columns on its own.
    fn split_statement() -> (Page, Vec<usize>, Vec<usize>) {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![figrow(676.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let upper = rows_of(&page, &["alpha", "bravo"]);
        let lower = rows_of(&page, &["charlie", "delta"]);
        (page, upper, lower)
    }

    #[test]
    fn a_wrapped_row_label_keeps_the_statement_one_table() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(
                    676.0,
                    vec![w("Add: stock-based compensation", 72.0, 300.0)],
                )],
            ),
            blk(
                "paragraph",
                vec![row(
                    664.0,
                    vec![w("expense included in reported", 72.0, 300.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    652.0,
                    vec![
                        w("net income, net of tax", 72.0, 300.0),
                        w("7,777", 360.0, 400.0),
                        w("8,888", 405.0, 445.0),
                        w("9,999", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(640.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        // The judge ended the region at the wrap's first line: the statement
        // arrives as two sets with the wrap between them.
        let upper = rows_of(&page, &["alpha", "bravo"]);
        let lower = rows_of(&page, &["net income", "charlie"]);
        let chosen = vec![upper, lower];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1, "the wrap still splits the table");
        let texts = texts_of(&page, &stitched[0]);
        for needle in [
            "Add: stock-based compensation",
            "expense included in reported",
            "net income, net of tax",
            "7,777",
            "alpha",
            "bravo",
            "charlie",
        ] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "the wrap line {needle:?} is not in the table: {texts:?}"
            );
        }
    }

    #[test]
    fn a_section_label_row_does_not_end_the_table() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1);
        let texts = texts_of(&page, &stitched[0]);
        for needle in ["Deferred income taxes:", "charlie", "delta"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join the table: {texts:?}"
            );
        }
        // Without the rows switch nothing below joins: only that switch
        // takes lines downward.
        assert_eq!(
            stitch(&page, &chosen, true, false, true),
            chosen,
            "a row joined with its switch off"
        );
    }

    #[test]
    fn the_year_header_joins_its_table() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1);
        let texts = texts_of(&page, &stitched[0]);
        for needle in ["Fiscal Year", "2003", "2002", "2001"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "the year header did not join: {texts:?}"
            );
        }
        // The table's first row is the header: nothing stands above it.
        let top = stitched[0]
            .iter()
            .map(|&i| page.lines[i].bbox[3])
            .fold(f64::NEG_INFINITY, f64::max);
        let first: Vec<&str> = stitched[0]
            .iter()
            .filter(|&&i| page.lines[i].bbox[3].total_cmp(&top) == std::cmp::Ordering::Equal)
            .map(|&i| page.lines[i].text.as_str())
            .collect();
        assert!(
            first
                .iter()
                .any(|t| t.contains("Fiscal Year") || t.contains("2003")),
            "the header is not the table's first row: {first:?}"
        );
        // Without the header switch the header stays out: only that switch
        // takes lines upward.
        assert_eq!(
            stitch(&page, &chosen, false, true, true),
            chosen,
            "the header joined with its switch off"
        );
    }

    #[test]
    fn a_two_row_column_header_joins_whole() {
        // Four figure columns at 350, 390, 450, 490: a spanning label over
        // all four, centred on them, then years, then a unit row.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    736.0,
                    vec![
                        w("Consolidated", 346.0, 410.0),
                        w("The", 418.0, 440.0),
                        w("Company", 448.0, 494.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    724.0,
                    vec![
                        w("2003", 320.0, 350.0),
                        w("2002", 360.0, 390.0),
                        w("2003", 420.0, 450.0),
                        w("2002", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("$000", 320.0, 350.0),
                        w("$000", 360.0, 390.0),
                        w("$000", 420.0, 450.0),
                        w("$000", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 300.0),
                        w("9,898", 320.0, 350.0),
                        w("2,240", 360.0, 390.0),
                        w("2,598", 420.0, 450.0),
                        w("7,111", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 300.0),
                        w("1,111", 320.0, 350.0),
                        w("2,222", 360.0, 390.0),
                        w("3,333", 420.0, 450.0),
                        w("4,444", 460.0, 490.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1);
        let texts = texts_of(&page, &stitched[0]);
        for needle in ["Consolidated", "The Company", "2003", "2002", "$000"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join the table: {texts:?}"
            );
        }
        // Without the header switch none of the three rows joins.
        assert_eq!(
            stitch(&page, &chosen, false, true, true),
            chosen,
            "a header row joined with its switch off"
        );

        // The same label off centre is a title, not a header: it stays out
        // and caps the walk, while the rows below it still join.
        let tilted = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    736.0,
                    vec![
                        w("Consolidated", 346.0, 400.0),
                        w("The", 408.0, 430.0),
                        w("Company", 438.0, 480.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    724.0,
                    vec![
                        w("2003", 320.0, 350.0),
                        w("2002", 360.0, 390.0),
                        w("2003", 420.0, 450.0),
                        w("2002", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("$000", 320.0, 350.0),
                        w("$000", 360.0, 390.0),
                        w("$000", 420.0, 450.0),
                        w("$000", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 300.0),
                        w("9,898", 320.0, 350.0),
                        w("2,240", 360.0, 390.0),
                        w("2,598", 420.0, 450.0),
                        w("7,111", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 300.0),
                        w("1,111", 320.0, 350.0),
                        w("2,222", 360.0, 390.0),
                        w("3,333", 420.0, 450.0),
                        w("4,444", 460.0, 490.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&tilted, &["alpha", "bravo"])];
        let texts = texts_of(&tilted, &stitch(&tilted, &chosen, true, true, true)[0]);
        assert!(texts.iter().any(|t| t.contains("2003")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("$000")), "{texts:?}");
        assert!(
            !texts.iter().any(|t| t.contains("Consolidated")),
            "an off-centre wide label joined as a header: {texts:?}"
        );
    }

    #[test]
    fn a_centred_spanning_label_longer_than_four_words_joins() {
        // Five words in one run would read as a sentence per column -- but
        // centred over four columns it is a spanning header, whatever its
        // length.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("aa", 346.0, 370.0),
                        w("bb", 378.0, 402.0),
                        w("cc", 410.0, 434.0),
                        w("dd", 442.0, 466.0),
                        w("ee", 470.0, 494.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 300.0),
                        w("9,898", 320.0, 350.0),
                        w("2,240", 360.0, 390.0),
                        w("2,598", 420.0, 450.0),
                        w("7,111", 460.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 300.0),
                        w("1,111", 320.0, 350.0),
                        w("2,222", 360.0, 390.0),
                        w("3,333", 420.0, 450.0),
                        w("4,444", 460.0, 490.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("aa")),
            "a five-word centred spanning label did not join: {texts:?}"
        );
    }

    #[test]
    fn a_centred_spanning_label_over_eight_columns_spans_eight() {
        // Eight figure columns at 200, 230, 260, 290, 320, 350, 390, 430. The
        // label stands alone on its line; its words cover the middle three
        // but sit centred on all eight, so the run spans eight.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Amino", 280.0, 305.0),
                        w("acid", 308.0, 328.0),
                        w("identity", 331.0, 345.0),
                        w("(%)", 346.0, 350.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 150.0),
                        w("1", 180.0, 200.0),
                        w("2", 210.0, 230.0),
                        w("3", 240.0, 260.0),
                        w("4", 270.0, 290.0),
                        w("5", 300.0, 320.0),
                        w("6", 330.0, 350.0),
                        w("7", 370.0, 390.0),
                        w("8", 410.0, 430.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 150.0),
                        w("1", 180.0, 200.0),
                        w("2", 210.0, 230.0),
                        w("3", 240.0, 260.0),
                        w("4", 270.0, 290.0),
                        w("5", 300.0, 320.0),
                        w("6", 330.0, 350.0),
                        w("7", 370.0, 390.0),
                        w("8", 410.0, 430.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Amino")),
            "the spanning label did not join: {texts:?}"
        );
        let walker = walker_of(&page, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert_eq!(
            params.columns.len(),
            8,
            "not eight columns: {:?}",
            params.columns
        );
        // The words cover three columns; the run they stand for spans eight.
        let label = find(&page, "Amino");
        let (x0, x1) = walker.pieces[label]
            .iter()
            .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), word| {
                (lo.min(word.bbox[0]), hi.max(word.bbox[2]))
            });
        let covered = params
            .columns
            .iter()
            .filter(|&&c| x0 - EPSILON <= c && c <= x1 + EPSILON)
            .count();
        assert_eq!(covered, 3, "the words cover {covered}, not three");
        let span = spanning_columns(f64::NEG_INFINITY, f64::INFINITY, &params.columns);
        assert_eq!(span.len(), 8, "the label spans {span:?}, not all eight");
    }

    #[test]
    fn a_spanning_label_between_header_groups_spans_only_between_them() {
        // Six figure columns; a per-column group left and right, a spanning
        // label in the middle. Its words cover two columns but the columns
        // between its neighbours are four, and four is what it spans.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Total", 196.0, 220.0),
                        w("Mid", 270.0, 295.0),
                        w("span", 305.0, 330.0),
                        w("End", 380.0, 404.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 150.0),
                        w("1", 180.0, 200.0),
                        w("2", 220.0, 240.0),
                        w("3", 260.0, 280.0),
                        w("4", 300.0, 320.0),
                        w("5", 340.0, 360.0),
                        w("6", 380.0, 400.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 150.0),
                        w("1", 180.0, 200.0),
                        w("2", 220.0, 240.0),
                        w("3", 260.0, 280.0),
                        w("4", 300.0, 320.0),
                        w("5", 340.0, 360.0),
                        w("6", 380.0, 400.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Mid")),
            "the header line did not join: {texts:?}"
        );
        let walker = walker_of(&page, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert_eq!(
            params.columns.len(),
            6,
            "not six columns: {:?}",
            params.columns
        );
        let span = spanning_columns(220.0, 380.0, &params.columns);
        assert_eq!(
            span,
            vec![240.0, 280.0, 320.0, 360.0],
            "the label spans {span:?}, not the columns between its neighbours"
        );
    }

    #[test]
    fn a_per_column_header_group_is_unchanged() {
        // Two runs over at most one column each: per-column groups, read by
        // word count rather than by centring, as before.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![w("One", 396.0, 405.0), w("Two", 450.0, 460.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        for needle in ["One", "Two"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join as a per-column header: {texts:?}"
            );
        }
    }

    #[test]
    fn a_stub_only_line_never_joins_upward() {
        // The note stands a line above the table, set like a section row --
        // close enough to reach, with nothing stub-only may hide behind. The
        // section row below proves the pass ran.
        let page = page_of(&[
            blk(
                "paragraph",
                vec![row(
                    712.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("5:", 115.0, 135.0),
                        w("Interest", 140.0, 200.0),
                        w("Expense,", 205.0, 270.0),
                        w("Net", 275.0, 300.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Deferred income taxes:")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
        assert!(
            !texts.iter().any(|t| t.contains("Interest Expense")),
            "a stub-only note joined upward: {texts:?}"
        );
    }

    /// A per-column header row over the `figrow` columns (400, 445, 490): two
    /// two-word groups, one per column pair, inside the columns' span.
    fn daterow(top: f64) -> Row<'static> {
        row(
            top,
            vec![
                w("March", 398.0, 430.0),
                w("31,", 432.0, 444.0),
                w("December", 447.0, 480.0),
                w("31,", 482.0, 494.0),
            ],
        )
    }

    #[test]
    fn a_stub_only_section_label_held_upward_commits_with_its_header() {
        // The corp-q1 shape: date headers over a bold section label over
        // figure rows. The label is held, and the header joining above
        // commits it with the chain tight either side.
        let page = page_of(&[
            blk("table_cell", vec![daterow(724.0)]),
            blk(
                "paragraph",
                vec![row(712.0, vec![wb("Liabilities", 72.0, 180.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        for needle in ["March 31,", "December 31,", "Liabilities", "alpha", "bravo"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join with the header: {texts:?}"
            );
        }
        // Without the header switch the label caps the walk as a bold title
        // would while vetting, and the header stays out.
        assert_eq!(
            stitch(&page, &chosen, false, true, true),
            chosen,
            "the header joined with its switch off"
        );
    }

    #[test]
    fn a_second_stub_only_line_upward_stops_the_walk() {
        // A title over the section label: the label is held, the title is the
        // second consecutive stub-only line and caps the walk, so the header
        // above it is never reached.
        let page = page_of(&[
            blk("table_cell", vec![daterow(736.0)]),
            blk(
                "paragraph",
                vec![row(724.0, vec![wb("Regional figures", 72.0, 250.0)])],
            ),
            blk(
                "paragraph",
                vec![row(712.0, vec![wb("Liabilities", 72.0, 180.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        assert_eq!(
            stitch(&page, &chosen, true, true, true),
            chosen,
            "a second stub-only line did not cap the walk"
        );
    }

    #[test]
    fn a_held_stub_at_the_commit_boundary_commits_and_past_it_drops() {
        // Pitch 12: the label a full pitch past the set's edge commits with
        // its header, a hair past it the header joins without it.
        for (top, joins) in [(722.0, true), (722.01, false)] {
            let page = page_of(&[
                blk("table_cell", vec![daterow(top + 12.0)]),
                blk(
                    "paragraph",
                    vec![row(top, vec![w("Loose label", 72.0, 220.0)])],
                ),
                blk(
                    "table_cell",
                    vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
                ),
                blk(
                    "table_cell",
                    vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
                ),
            ]);
            let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
            let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
            assert!(
                texts.iter().any(|t| t.contains("March 31,")),
                "the header did not join at label top {top}: {texts:?}"
            );
            let joined = texts.iter().any(|t| t.contains("Loose label"));
            assert!(
                joined == joins,
                "the held label joined={joined} at top {top}, want {joins}: {texts:?}"
            );
        }
    }

    #[test]
    fn a_figure_row_above_commits_the_held_section_label() {
        // A figure row joining upward commits the held label the same way a
        // header row does: the cut between two figure rows heals whole.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["charlie", "delta"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        for needle in [
            "alpha",
            "bravo",
            "Deferred income taxes:",
            "charlie",
            "delta",
        ] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join upward: {texts:?}"
            );
        }
        // Without the header switch nothing above joins: only that switch
        // takes lines upward.
        assert_eq!(
            stitch(&page, &chosen, false, true, true),
            chosen,
            "a figure row joined upward with its switch off"
        );
    }

    #[test]
    fn in_millions_joins_with_its_header_line() {
        // The unit note stands at the stub on the year header's own line: it
        // joins with that row, though a stub-only line alone never would.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("(in", 72.0, 100.0),
                        w("millions)", 105.0, 170.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let texts = texts_of(&page, &stitch(&page, &chosen, true, true, true)[0]);
        for needle in ["millions", "2003", "2002", "2001"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} did not join with its header line: {texts:?}"
            );
        }
        // Without the header switch the whole line stays out.
        assert_eq!(
            stitch(&page, &chosen, false, true, true),
            chosen,
            "the header line joined with its switch off"
        );
    }

    #[test]
    fn a_note_paragraph_under_a_table_stays_prose() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![
                    row(
                        676.0,
                        vec![
                            w("The", 72.0, 95.0),
                            w("revaluation", 100.0, 170.0),
                            w("was", 175.0, 200.0),
                            w("performed", 205.0, 270.0),
                            w("at", 275.0, 290.0),
                            w("market", 295.0, 340.0),
                            w("value", 345.0, 385.0),
                        ],
                    ),
                    row(664.0, vec![w("during the year.", 72.0, 180.0)]),
                ],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1);
        let texts = texts_of(&page, &stitched[0]);
        // The header above proves the pass ran; the note below stays out.
        assert!(texts.iter().any(|t| t.contains("Fiscal Year")), "{texts:?}");
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("revaluation") || t.contains("during the year")),
            "the note joined the table: {texts:?}"
        );
    }

    #[test]
    fn a_caption_above_with_a_larger_gap_stays_prose() {
        let page = page_of(&[
            blk(
                "paragraph",
                vec![row(
                    740.0,
                    vec![
                        w("Table", 72.0, 110.0),
                        w("2:", 115.0, 135.0),
                        w("Net", 140.0, 165.0),
                        w("sales", 170.0, 205.0),
                        w("by", 210.0, 228.0),
                        w("region", 233.0, 280.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        // The section row below proves the pass ran; the gapped caption stays.
        assert!(
            texts.iter().any(|t| t.contains("Deferred income taxes:")),
            "{texts:?}"
        );
        assert!(!texts.iter().any(|t| t.contains("Table 2:")), "{texts:?}");
    }

    #[test]
    fn two_stacked_tables_with_different_figure_columns_stay_two() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("ratio", 72.0, 120.0),
                        w("1.2", 376.0, 420.0),
                        w("3.4", 446.0, 490.0),
                        w("5.6", 516.0, 560.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    664.0,
                    vec![
                        w("margin", 72.0, 120.0),
                        w("7.8", 376.0, 420.0),
                        w("9.0", 446.0, 490.0),
                        w("1.2", 516.0, 560.0),
                    ],
                )],
            ),
            blk(
                "paragraph",
                vec![row(652.0, vec![w("Trailing remark", 72.0, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![row(
                    640.0,
                    vec![
                        w("spread", 72.0, 120.0),
                        w("2.3", 376.0, 420.0),
                        w("4.5", 446.0, 490.0),
                        w("6.7", 516.0, 560.0),
                    ],
                )],
            ),
        ]);
        let upper = rows_of(&page, &["alpha", "bravo"]);
        let lower = rows_of(&page, &["ratio", "margin"]);
        let chosen = vec![upper, lower];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "different columns merged");
        // The lower table still absorbs its own continuation below.
        let texts = texts_of(&page, &stitched[1]);
        assert!(texts.iter().any(|t| t.contains("spread")), "{texts:?}");
        assert!(!texts.iter().any(|t| t.contains("alpha")), "{texts:?}");
    }

    #[test]
    fn a_two_column_page_of_prose_beside_a_table_is_untouched() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![
                    row(
                        724.0,
                        vec![w("Earlier", 500.0, 550.0), w("prose", 555.0, 590.0)],
                    ),
                    row(
                        700.0,
                        vec![w("Beside", 500.0, 550.0), w("prose", 555.0, 590.0)],
                    ),
                    row(
                        688.0,
                        vec![w("More", 500.0, 540.0), w("beside", 545.0, 590.0)],
                    ),
                    row(
                        664.0,
                        vec![w("Later", 500.0, 545.0), w("prose", 550.0, 590.0)],
                    ),
                ],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1);
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("Fiscal Year")), "{texts:?}");
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("prose") || t.contains("Beside") || t.contains("More")),
            "the prose column joined the table: {texts:?}"
        );
    }

    #[test]
    fn two_stacked_statements_with_their_own_titles_stay_apart() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "heading",
                vec![row_at(
                    676.0,
                    14.0,
                    vec![
                        w("Consolidated", 72.0, 170.0),
                        w("Statements", 175.0, 260.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    660.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(648.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(636.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        // Same figure columns, but the lower statement starts with its own
        // title and year header: separate tables.
        let upper = rows_of(&page, &["alpha", "bravo"]);
        let lower = rows_of(&page, &["charlie", "delta"]);
        let chosen = vec![upper, lower];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "the stacked statements merged");
        let below = texts_of(&page, &stitched[1]);
        assert!(below.iter().any(|t| t.contains("Fiscal Year")), "{below:?}");
        assert!(below.iter().any(|t| t.contains("2003")), "{below:?}");
        assert!(
            !below.iter().any(|t| t.contains("Consolidated")),
            "{below:?}"
        );
        let above = texts_of(&page, &stitched[0]);
        assert!(
            !above
                .iter()
                .any(|t| t.contains("Consolidated") || t.contains("Fiscal")),
            "{above:?}"
        );
    }

    #[test]
    fn a_title_between_two_tables_blocks_their_merge() {
        // Tight enough to reach across (gap 18 of 19.2), so only the title
        // keeps them apart. The year header above proves the pass ran.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "heading",
                vec![row_at(
                    676.0,
                    14.0,
                    vec![w("Second", 72.0, 130.0), w("Statement", 135.0, 230.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(660.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(648.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "the title did not block the merge");
        assert!(
            texts_of(&page, &stitched[0])
                .iter()
                .any(|t| t.contains("Fiscal Year")),
            "the pass did not run"
        );
        for set in &stitched {
            assert!(
                !texts_of(&page, set)
                    .iter()
                    .any(|t| t.contains("Second Statement")),
                "the title joined a table"
            );
        }
    }

    #[test]
    fn a_caption_between_two_tables_blocks_their_merge() {
        // The year header above proves the pass ran.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(
                    676.0,
                    vec![w("Table", 400.0, 438.0), w("2", 443.0, 452.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "the caption did not block the merge");
        assert!(
            texts_of(&page, &stitched[0])
                .iter()
                .any(|t| t.contains("Fiscal Year")),
            "the pass did not run"
        );
        for set in &stitched {
            assert!(
                !texts_of(&page, set).iter().any(|t| t.contains("Table 2")),
                "{set:?}"
            );
        }
    }

    #[test]
    fn a_plain_label_between_two_tables_merges_with_them() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk("paragraph", vec![row(676.0, vec![w("Notes", 72.0, 120.0)])]),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1, "the halves did not merge");
        assert!(texts_of(&page, &stitched[0])
            .iter()
            .any(|t| t.contains("Notes")));
    }

    #[test]
    fn a_label_line_between_two_halves_merges_with_both_absorb_switches_off() {
        // The upper half is set tight (pitch 5, reach 8) and the label stands
        // 9 below its edge, past what its downward walk may cross; the lower
        // half is set loose (pitch 12) and reaches the label upward. Only the
        // upward merge walk crosses it, so with both absorb switches off the
        // halves become one only where a stub-only line still vets upward.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(695.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Capital lease", 72.0, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(660.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(648.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, false, false, true);
        assert_eq!(stitched.len(), 1, "the halves stayed two with both off");
        let texts = texts_of(&page, &stitched[0]);
        for needle in ["Capital lease", "alpha", "bravo", "charlie", "delta"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} is not in the merged table: {texts:?}"
            );
        }
    }

    #[test]
    fn a_merge_into_a_set_starting_with_a_year_head_refuses() {
        // The lower half opens with its own year head -- `Year Ended December
        // 31, 2009` with the year standing right of the stub, off the figure
        // columns -- as the judge chose it: a member, not an absorbed line,
        // so `headed` never sees it and the columns match. With
        // `split_stacked` the merge refuses; without, the halves become one.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("Year", 72.0, 110.0),
                        w("Ended", 115.0, 160.0),
                        w("December", 165.0, 230.0),
                        w("31,", 235.0, 260.0),
                        w("2009", 500.0, 540.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["Year", "charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let merged = stitch(&page, &chosen, false, false, true);
        assert_eq!(merged.len(), 1, "the halves stayed two with the flag off");
        let kept = stitch_sets(
            &page.lines,
            &page.words,
            page.n_blocks,
            &chosen,
            false,
            false,
            true,
            true,
        );
        assert_eq!(kept.len(), 2, "the halves merged past the year head");
        assert!(
            texts_of(&page, &kept[1]).iter().any(|t| t.contains("2009")),
            "the year head is not in the lower half: {:?}",
            texts_of(&page, &kept[1]),
        );
    }

    #[test]
    fn trailing_label_lines_without_figures_after_them_are_dropped() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("See accompanying notes", 72.0, 250.0)])],
            ),
            blk(
                "paragraph",
                vec![row(664.0, vec![w("to the statements", 72.0, 220.0)])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("Fiscal Year")), "{texts:?}");
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("accompanying") || t.contains("to the statements")),
            "trailing labels joined alone: {texts:?}"
        );
    }

    #[test]
    fn a_dot_leader_row_joins_its_table() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "zebra", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("Accumulated", 72.0, 150.0),
                        w("depreciation", 155.0, 240.0),
                        w(".", 245.0, 250.0),
                        w(".", 255.0, 260.0),
                        w(".", 265.0, 270.0),
                        w(".", 275.0, 280.0),
                        w("8,500", 360.0, 400.0),
                        w("8,501", 405.0, 445.0),
                        w("8,502", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "zebra"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("Accumulated")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("8,500")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn digit_labels_do_not_drag_the_stub() {
        // Labels holding digits, one token and two: the figures still own the
        // stub edge, so the wrap below joins as label-only lines rather than
        // reading as prose crossing it.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "Note 12", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "Note 13", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "paragraph",
                vec![row(664.0, vec![w("compensation", 72.0, 180.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "Note 14", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["Note 12", "Note 13"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        for needle in ["Add: stock-based", "compensation", "Note 14"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} stayed out: {texts:?}"
            );
        }
        let words = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("12", 113.0, 137.0),
                        w("9,898", 360.0, 400.0),
                        w("2,240", 405.0, 445.0),
                        w("2,598", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&words, &["Note", "bravo"])];
        let texts = texts_of(&words, &stitch(&words, &chosen, true, true, true)[0]);
        for needle in ["Add: stock-based", "charlie"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} stayed out: {texts:?}"
            );
        }
    }

    #[test]
    fn aligned_non_figure_words_do_not_join_as_a_figure_row() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(
                    676.0,
                    vec![
                        w("apples", 360.0, 400.0),
                        w("pears", 405.0, 445.0),
                        w("plums", 450.0, 490.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("Fiscal Year")), "{texts:?}");
        assert!(!texts.iter().any(|t| t.contains("apples")), "{texts:?}");
    }

    #[test]
    fn a_split_row_is_vetted_left_to_right() {
        // Label and figures 15 pt apart: four pieces at one top. The label is
        // held before its figures join and commit it.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("wide", 72.0, 300.0),
                        w("4,444", 360.0, 400.0),
                        w("5,555", 415.0, 445.0),
                        w("6,666", 460.0, 490.0),
                    ],
                )],
            ),
        ]);
        assert_eq!(
            page.lines.len(),
            8,
            "the row did not split into four pieces"
        );
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        assert!(
            texts.iter().any(|t| t.contains("wide")),
            "the label piece was dropped: {texts:?}"
        );
        for needle in ["4,444", "5,555", "6,666"] {
            assert!(
                texts.iter().any(|t| t.contains(needle)),
                "{needle:?} stayed out: {texts:?}"
            );
        }
    }

    #[test]
    fn a_line_at_the_gap_factor_joins_and_past_it_stops() {
        // Pitch 10, so the reach is exactly 16 pt and the tops are exact.
        assert!((GAP_FACTOR * 10.0).total_cmp(&16.0) == std::cmp::Ordering::Equal);
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(690.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(637.999, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        // Gap 16.0 joins; 16.001 past the joined row ends the walk, so delta stays out.
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
        assert!(!texts.iter().any(|t| t.contains("delta")), "{texts:?}");
    }

    #[test]
    fn a_line_at_the_size_boundary_joins_and_past_it_never_does() {
        let big = TEXT_GROWTH * SIZE;
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row_at(676.0, big + 0.001, vec![w("too big", 72.0, 200.0)])],
            ),
            blk(
                "paragraph",
                vec![row_at(663.0, big, vec![w("joinable", 72.0, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(650.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        // The nearer line is oversize and stepped over; the walk goes on past
        // it to the line at exactly the boundary, which is held and committed
        // by the figure row below.
        assert!(!texts.iter().any(|t| t.contains("too big")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("joinable")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn a_figure_edge_at_the_tolerance_matches_and_past_it_does_not() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("on edge", 72.0, 200.0),
                        w("4,444", 364.0, 404.0),
                        w("5,555", 409.0, 449.0),
                        w("6,666", 454.0, 494.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    664.0,
                    vec![
                        w("past edge", 72.0, 200.0),
                        w("7,777", 364.001, 404.001),
                        w("8,888", 409.001, 449.001),
                        w("9,999", 454.001, 494.001),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "charlie", ["1,010", "2,020", "3,030"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("on edge")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("4,444")), "{texts:?}");
        // Past the tolerance the figures stay out but the walk goes on: the
        // row below still joins, committing the skipped row's label with it.
        assert!(!texts.iter().any(|t| t.contains("7,777")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("past edge")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn a_label_at_the_indent_tolerance_joins_and_past_it_stops() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("flush label", 68.0, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert!(
            texts_of(&page, &stitched[0])
                .iter()
                .any(|t| t.contains("flush label")),
            "a label at exactly H.x0 - 4 did not join"
        );

        let past = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("outdented", 67.999, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        // The outdented label is nearest downward and ends the walk, so the
        // figure row below it is never reached.
        let chosen = vec![rows_of(&past, &["alpha", "bravo"])];
        let grown = stitch(&past, &chosen, true, true, true);
        assert_eq!(grown, chosen, "an outdented label did not end the walk");
    }

    #[test]
    fn a_four_word_header_group_joins_and_five_read_as_prose() {
        let headed = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("qq1", 396.0, 410.0),
                        w("qq2", 412.0, 426.0),
                        w("qq3", 428.0, 442.0),
                        w("qq4", 452.0, 466.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&headed, &["alpha", "bravo"])];
        assert_off_is_identity(&headed, &chosen);
        let stitched = stitch(&headed, &chosen, true, true, true);
        assert!(
            texts_of(&headed, &stitched[0])
                .iter()
                .any(|t| t.contains("qq1")),
            "a four-word header group did not join"
        );

        // Two wide columns, so five words fit between them in one group.
        let wordy = page_of(&[
            blk(
                "paragraph",
                vec![row(724.0, vec![w("never reached", 72.0, 200.0)])],
            ),
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("aa", 405.0, 417.0),
                        w("bb", 419.0, 431.0),
                        w("cc", 433.0, 445.0),
                        w("dd", 447.0, 459.0),
                        w("ee", 461.0, 473.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("alpha", 72.0, 200.0),
                        w("9,898", 360.0, 400.0),
                        w("2,240", 500.0, 540.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("bravo", 72.0, 200.0),
                        w("1,111", 360.0, 400.0),
                        w("3,333", 500.0, 540.0),
                    ],
                )],
            ),
        ]);
        // Five words in one group read as a sentence crossing the stub: prose,
        // ending the walk before the label above.
        let chosen = vec![rows_of(&wordy, &["alpha", "bravo"])];
        let grown = stitch(&wordy, &chosen, true, true, true);
        assert_eq!(grown, chosen, "a five-word group did not end the walk");
    }

    #[test]
    fn one_shared_column_does_not_merge_and_two_do() {
        let one = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![w("single", 72.0, 200.0), w("4,444", 360.0, 400.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    664.0,
                    vec![w("column", 72.0, 200.0), w("5,555", 360.0, 400.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    652.0,
                    vec![w("tail", 72.0, 200.0), w("6,666", 360.0, 400.0)],
                )],
            ),
        ]);
        let chosen = vec![
            rows_of(&one, &["alpha", "bravo"]),
            rows_of(&one, &["single", "column"]),
        ];
        assert_off_is_identity(&one, &chosen);
        let stitched = stitch(&one, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "one shared column merged");
        assert!(
            texts_of(&one, &stitched[1])
                .iter()
                .any(|t| t.contains("tail")),
            "the lower table did not absorb its own tail"
        );

        let two = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("narrow", 72.0, 200.0),
                        w("4,444", 360.0, 400.0),
                        w("5,555", 405.0, 445.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    664.0,
                    vec![
                        w("table", 72.0, 200.0),
                        w("6,666", 360.0, 400.0),
                        w("7,777", 405.0, 445.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![
            rows_of(&two, &["alpha", "bravo"]),
            rows_of(&two, &["narrow", "table"]),
        ];
        let stitched = stitch(&two, &chosen, true, true, true);
        assert_eq!(stitched.len(), 1, "two shared columns did not merge");
    }

    #[test]
    fn a_sixty_percent_column_share_merges_and_below_does_not() {
        /// Five wide columns at 300, 360, 420, 480, 540.
        fn wide<'a>(top: f64, label: &'a str, figs: [(&'a str, f64, f64); 5]) -> Row<'a> {
            let mut words = vec![w(label, 72.0, 200.0)];
            for (text, x0, x1) in figs {
                words.push(w(text, x0, x1));
            }
            row(top, words)
        }
        let fifths: [(&str, f64, f64); 5] = [
            ("1,111", 265.0, 300.0),
            ("2,222", 325.0, 360.0),
            ("3,333", 385.0, 420.0),
            ("4,444", 445.0, 480.0),
            ("5,555", 505.0, 540.0),
        ];
        let three: [(&str, f64, f64); 5] = [
            ("1,111", 265.0, 300.0),
            ("2,222", 325.0, 360.0),
            ("3,333", 385.0, 420.0),
            ("4,444", 465.0, 500.0),
            ("5,555", 525.0, 560.0),
        ];
        let two: [(&str, f64, f64); 5] = [
            ("1,111", 265.0, 300.0),
            ("2,222", 325.0, 360.0),
            ("3,333", 465.0, 500.0),
            ("4,444", 525.0, 560.0),
            ("5,555", 585.0, 620.0),
        ];
        let sixty = page_of(&[
            blk("table_cell", vec![wide(700.0, "alpha", fifths)]),
            blk("table_cell", vec![wide(688.0, "bravo", fifths)]),
            blk("table_cell", vec![wide(676.0, "charlie", three)]),
            blk("table_cell", vec![wide(664.0, "delta", three)]),
        ]);
        let chosen = vec![
            rows_of(&sixty, &["alpha", "bravo"]),
            rows_of(&sixty, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&sixty, &chosen);
        assert_eq!(
            stitch(&sixty, &chosen, true, true, true).len(),
            1,
            "three of five shared columns did not merge"
        );

        let forty = page_of(&[
            blk("table_cell", vec![wide(700.0, "alpha", fifths)]),
            blk("table_cell", vec![wide(688.0, "bravo", fifths)]),
            blk("table_cell", vec![wide(676.0, "charlie", two)]),
            blk("table_cell", vec![wide(664.0, "delta", two)]),
            blk("table_cell", vec![wide(652.0, "tail", two)]),
        ]);
        let chosen = vec![
            rows_of(&forty, &["alpha", "bravo"]),
            rows_of(&forty, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&forty, &chosen);
        let stitched = stitch(&forty, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "two of five shared columns merged");
        assert!(texts_of(&forty, &stitched[1])
            .iter()
            .any(|t| t.contains("tail")));
    }

    #[test]
    fn a_column_needs_two_lines_of_support() {
        let lone = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "paragraph",
                vec![row(688.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(676.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        // One figure row: every cluster stands on one line, so there are no
        // columns and the set is left alone.
        let chosen = vec![rows_of(&lone, &["alpha"])];
        assert_eq!(stitch(&lone, &chosen, true, true, true), chosen);

        let pair = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "extra", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "bravo", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&pair, &["alpha", "extra"])];
        assert_off_is_identity(&pair, &chosen);
        let texts = texts_of(&pair, &stitch(&pair, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Deferred income taxes:")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("bravo")), "{texts:?}");
    }

    #[test]
    fn a_word_ending_at_the_stub_is_label_and_past_it_prose() {
        // The stub stands at 358; a label ending there is held downward and
        // committed by the figure row below.
        let at = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("flush label", 72.0, 358.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&at, &["alpha", "bravo"])];
        assert_off_is_identity(&at, &chosen);
        assert!(
            texts_of(&at, &stitch(&at, &chosen, true, true, true)[0])
                .iter()
                .any(|t| t.contains("flush label")),
            "a word ending at the stub did not read as label"
        );

        // A hair past it the word crosses the stub with non-figures: prose,
        // ending the walk before the row below. The year header above proves
        // the pass ran.
        let past = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("crossing", 72.0, 358.001)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&past, &["alpha", "bravo"])];
        assert_off_is_identity(&past, &chosen);
        let texts = texts_of(&past, &stitch(&past, &chosen, true, true, true)[0]);
        assert!(texts.iter().any(|t| t.contains("Fiscal Year")), "{texts:?}");
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("crossing") || t.contains("charlie")),
            "{texts:?}"
        );
    }

    #[test]
    fn a_digit_at_the_figure_gap_counts_and_below_does_not() {
        // `Note 12` with the digit exactly 0.6 em past `Note` counts as a
        // figure; aligned over two rows it columns and drags the stub left,
        // so the wrap below reads as prose crossing it and the set is
        // unchanged.
        let gap = FIGURE_GAP_EM * SIZE;
        let wide = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("12", 110.0 + gap, 140.0 + gap),
                        w("9,898", 360.0, 400.0),
                        w("2,240", 405.0, 445.0),
                        w("2,598", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("13", 110.0 + gap, 140.0 + gap),
                        w("1,111", 360.0, 400.0),
                        w("2,222", 405.0, 445.0),
                        w("3,333", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&wide, &["Note 12", "Note 13"])];
        assert_eq!(
            stitch(&wide, &chosen, true, true, true),
            chosen,
            "a digit at the figure gap did not count as a figure"
        );

        // A hair closer it stays label text and the wrap joins.
        let tight = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    700.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("12", 110.0 + gap - 0.001, 140.0 + gap - 0.001),
                        w("9,898", 360.0, 400.0),
                        w("2,240", 405.0, 445.0),
                        w("2,598", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![row(
                    688.0,
                    vec![
                        w("Note", 72.0, 110.0),
                        w("13", 110.0 + gap - 0.001, 140.0 + gap - 0.001),
                        w("1,111", 360.0, 400.0),
                        w("2,222", 405.0, 445.0),
                        w("3,333", 450.0, 490.0),
                    ],
                )],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&tight, &["Note 12", "Note 13"])];
        assert_off_is_identity(&tight, &chosen);
        let texts = texts_of(&tight, &stitch(&tight, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Add: stock-based")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn year_rows_skip_down_and_join_up_but_amounts_join_down() {
        // Aligned years step aside downward: the figures stay out while the
        // row below still joins.
        let down = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("Fiscal", 72.0, 200.0),
                        w("1800", 360.0, 400.0),
                        w("2199", 405.0, 445.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&down, &["alpha", "bravo"])];
        assert_off_is_identity(&down, &chosen);
        let texts = texts_of(&down, &stitch(&down, &chosen, true, true, true)[0]);
        assert!(!texts.iter().any(|t| t.contains("1800")), "{texts:?}");
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");

        // Upward the same row heads the table.
        let up = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 200.0),
                        w("2003", 360.0, 400.0),
                        w("2002", 405.0, 445.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
        ]);
        let chosen = vec![rows_of(&up, &["alpha", "bravo"])];
        assert!(
            texts_of(&up, &stitch(&up, &chosen, true, true, true)[0])
                .iter()
                .any(|t| t.contains("2003")),
            "a year row did not join upward"
        );

        // Outside the year range the same shape is a figure row and joins down.
        let amounts = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("shares", 72.0, 200.0),
                        w("1799", 360.0, 400.0),
                        w("2200", 405.0, 445.0),
                    ],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&amounts, &["alpha", "bravo"])];
        let texts = texts_of(&amounts, &stitch(&amounts, &chosen, true, true, true)[0]);
        assert!(texts.iter().any(|t| t.contains("1799")), "{texts:?}");
    }

    #[test]
    fn a_bold_title_caps_the_table_but_a_bold_section_row_joins() {
        let page = page_of(&[
            blk(
                "paragraph",
                vec![row(724.0, vec![w("never reached", 72.0, 200.0)])],
            ),
            blk(
                "paragraph",
                vec![row(712.0, vec![wb("Regional figures", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![wb("Deferred income taxes:", 72.0, 250.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
        ]);
        let chosen = vec![rows_of(&page, &["alpha", "bravo"])];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        let texts = texts_of(&page, &stitched[0]);
        // The bold title ends the upward walk before the label above it; the
        // bold section row between figure rows joins downward like any label.
        assert!(
            !texts.iter().any(|t| t.contains("Regional figures")),
            "{texts:?}"
        );
        assert!(
            !texts.iter().any(|t| t.contains("never reached")),
            "{texts:?}"
        );
        assert!(
            texts.iter().any(|t| t.contains("Deferred income taxes:")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn a_same_size_bold_title_between_tables_blocks_their_merge() {
        // The year header above proves the pass ran.
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![wb("Second Statement", 72.0, 230.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, true);
        assert_eq!(stitched.len(), 2, "the bold title did not block the merge");
        assert!(
            texts_of(&page, &stitched[0])
                .iter()
                .any(|t| t.contains("Fiscal Year")),
            "the pass did not run"
        );
        for set in &stitched {
            assert!(
                !texts_of(&page, set)
                    .iter()
                    .any(|t| t.contains("Second Statement")),
                "{set:?}"
            );
        }
    }

    #[test]
    fn a_held_label_at_the_commit_boundary_commits_and_past_it_drops() {
        let at = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(
                    666.0 - PITCH,
                    "charlie",
                    ["4,444", "5,555", "6,666"],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&at, &["alpha", "bravo"])];
        assert_off_is_identity(&at, &chosen);
        let texts = texts_of(&at, &stitch(&at, &chosen, true, true, true)[0]);
        assert!(
            texts.iter().any(|t| t.contains("Add: stock-based")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");

        // A hair past one pitch the held label stays pending to the walk's
        // end while the figures still join without it.
        let past = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Loose caption", 72.0, 220.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(
                    666.0 - PITCH - 0.001,
                    "charlie",
                    ["4,444", "5,555", "6,666"],
                )],
            ),
        ]);
        let chosen = vec![rows_of(&past, &["alpha", "bravo"])];
        let texts = texts_of(&past, &stitch(&past, &chosen, true, true, true)[0]);
        assert!(
            !texts.iter().any(|t| t.contains("Loose caption")),
            "{texts:?}"
        );
        assert!(texts.iter().any(|t| t.contains("charlie")), "{texts:?}");
    }

    #[test]
    fn caption_shapes_are_recognized() {
        for caption in [
            "Table 2: Net sales",
            "TABLE 1",
            "Figure 12",
            "Fig. 3",
            "Fig 4",
            "Tables 2-4",
            "  table 9 (continued)",
        ] {
            assert!(is_caption(caption), "{caption:?} did not read as a caption");
        }
        for prose in [
            "Table of contents",
            "Tabular data",
            "Figure skating",
            "Fig leaf",
            "Tables",
            "2 Tables",
            "",
        ] {
            assert!(!is_caption(prose), "{prose:?} read as a caption");
        }
    }

    #[test]
    fn without_either_switch_the_sets_come_back_unchanged() {
        let (page, upper, lower) = split_statement();
        // Adjacent halves with matching columns: anything on would merge them.
        let chosen = vec![upper, lower];
        assert_eq!(stitch(&page, &chosen, false, false, false), chosen);
        assert_eq!(stitch(&page, &chosen, true, true, true).len(), 1);
    }

    /// Two halves with a year header above the upper one, a wrap between
    /// them, and a figure row below the lower one: each absorb switch grows
    /// its own direction without joining the halves.
    fn split_with_header_and_tail() -> (Page, Vec<usize>, Vec<usize>) {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![w("Add: stock-based", 72.0, 220.0)])],
            ),
            blk(
                "paragraph",
                vec![row(664.0, vec![w("compensation", 72.0, 180.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(640.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
            blk(
                "table_cell",
                vec![figrow(628.0, "tail", ["1,010", "2,020", "3,030"])],
            ),
        ]);
        let upper = rows_of(&page, &["alpha", "bravo"]);
        let lower = rows_of(&page, &["charlie", "delta"]);
        (page, upper, lower)
    }

    #[test]
    fn absorbing_without_merging_grows_but_does_not_join() {
        let (page, upper, lower) = split_with_header_and_tail();
        let chosen = vec![upper, lower];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, true, true, false);
        assert_eq!(stitched.len(), 2, "absorb-only merged the sets");
        // The upper half takes its header upward, the lower half its tail
        // downward; the wrap between them is held but never committed, so it
        // stays out without a merge.
        let above = texts_of(&page, &stitched[0]);
        assert!(above.iter().any(|t| t.contains("Fiscal Year")), "{above:?}");
        assert!(above.iter().any(|t| t.contains("2003")), "{above:?}");
        assert!(
            !above.iter().any(|t| t.contains("compensation")),
            "{above:?}"
        );
        let below = texts_of(&page, &stitched[1]);
        assert!(below.iter().any(|t| t.contains("tail")), "{below:?}");
        assert!(
            !below
                .iter()
                .any(|t| t.contains("Add: stock-based") || t.contains("compensation")),
            "{below:?}"
        );
    }

    #[test]
    fn absorbing_headers_without_rows_grows_upward_only() {
        let (page, upper, lower) = split_with_header_and_tail();
        let chosen = vec![upper, lower];
        let stitched = stitch(&page, &chosen, true, false, false);
        assert_eq!(stitched.len(), 2, "header-only merged the sets");
        let above = texts_of(&page, &stitched[0]);
        assert!(above.iter().any(|t| t.contains("Fiscal Year")), "{above:?}");
        assert!(above.iter().any(|t| t.contains("2003")), "{above:?}");
        // Nothing downward: the tail figure row and the wrap stay out.
        for set in &stitched {
            let texts = texts_of(&page, set);
            assert!(
                !texts.iter().any(|t| t.contains("tail")
                    || t.contains("Add: stock-based")
                    || t.contains("compensation")),
                "header-only absorbed downward: {texts:?}"
            );
        }
    }

    #[test]
    fn absorbing_rows_without_headers_grows_downward_only() {
        let (page, upper, lower) = split_with_header_and_tail();
        let chosen = vec![upper, lower];
        let stitched = stitch(&page, &chosen, false, true, false);
        assert_eq!(stitched.len(), 2, "rows-only merged the sets");
        let below = texts_of(&page, &stitched[1]);
        assert!(below.iter().any(|t| t.contains("tail")), "{below:?}");
        // Nothing upward: the year header stays out, and the wrap between the
        // halves is held below the upper one but never committed.
        for set in &stitched {
            let texts = texts_of(&page, set);
            assert!(
                !texts.iter().any(|t| t.contains("Fiscal Year")
                    || t.contains("2003")
                    || t.contains("Add: stock-based")
                    || t.contains("compensation")),
                "rows-only absorbed upward: {texts:?}"
            );
        }
    }

    #[test]
    fn merging_without_absorbing_claims_only_between() {
        let page = page_of(&[
            blk(
                "table_cell",
                vec![row(
                    712.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk("paragraph", vec![row(676.0, vec![w("Notes", 72.0, 120.0)])]),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
            blk(
                "table_cell",
                vec![figrow(640.0, "tail", ["1,010", "2,020", "3,030"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&page, &["alpha", "bravo"]),
            rows_of(&page, &["charlie", "delta"]),
        ];
        assert_off_is_identity(&page, &chosen);
        let stitched = stitch(&page, &chosen, false, false, true);
        assert_eq!(stitched.len(), 1, "merge-only did not merge");
        let texts = texts_of(&page, &stitched[0]);
        assert!(texts.iter().any(|t| t.contains("Notes")), "{texts:?}");
        assert!(
            !texts
                .iter()
                .any(|t| t.contains("Fiscal Year") || t.contains("tail")),
            "merge-only absorbed past the merge: {texts:?}"
        );
    }

    /// A walker over the page as [`stitch_sets`] builds it, for calling the
    /// merge guard directly.
    fn walker_of<'x>(
        page: &'x Page,
        chosen: &[Vec<usize>],
        absorb_header: bool,
        absorb_rows: bool,
        merge: bool,
    ) -> Walker<'x> {
        let mut pieces = Vec::new();
        for block in 0..page.n_blocks {
            for piece in lines_of(block, &page.words) {
                if !piece.is_empty() {
                    pieces.push(piece);
                }
            }
        }
        assert_eq!(pieces.len(), page.lines.len());
        Walker::new(
            &page.lines,
            pieces,
            chosen,
            absorb_header,
            absorb_rows,
            merge,
            false,
        )
    }

    #[test]
    fn a_title_caption_or_header_between_blocks_a_merge() {
        // A between-line of each kind, each reached directly so the guard --
        // not the walk -- decides.
        let title = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "heading",
                vec![row_at(
                    676.0,
                    14.0,
                    vec![w("Second Statement", 72.0, 230.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(660.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(648.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&title, &["alpha", "bravo"]),
            rows_of(&title, &["charlie", "delta"]),
        ];
        let mut walker = walker_of(&title, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert!(
            !walker.try_merge(0, 1, Dir::Down, &params, &[], &[]),
            "a title between merged"
        );

        let caption = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(
                    676.0,
                    vec![w("Table", 400.0, 438.0), w("2", 443.0, 452.0)],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&caption, &["alpha", "bravo"]),
            rows_of(&caption, &["charlie", "delta"]),
        ];
        let mut walker = walker_of(&caption, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert!(
            !walker.try_merge(0, 1, Dir::Down, &params, &[], &[]),
            "a caption between merged"
        );

        // An aligned year header: a figure row by shape, a header row by year.
        let header = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "table_cell",
                vec![row(
                    676.0,
                    vec![
                        w("Fiscal", 72.0, 110.0),
                        w("Year", 115.0, 150.0),
                        w("2003", 378.0, 400.0),
                        w("2002", 423.0, 445.0),
                        w("2001", 468.0, 490.0),
                    ],
                )],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&header, &["alpha", "bravo"]),
            rows_of(&header, &["charlie", "delta"]),
        ];
        let mut walker = walker_of(&header, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert!(
            !walker.try_merge(0, 1, Dir::Down, &params, &[], &[]),
            "a header between merged"
        );

        // A same-size bold title between: no size or caption tells it, the
        // face does.
        let bold = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk(
                "paragraph",
                vec![row(676.0, vec![wb("Second Statement", 72.0, 230.0)])],
            ),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&bold, &["alpha", "bravo"]),
            rows_of(&bold, &["charlie", "delta"]),
        ];
        let mut walker = walker_of(&bold, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert!(
            !walker.try_merge(0, 1, Dir::Down, &params, &[], &[]),
            "a bold title between merged"
        );

        // And a plain label between merges.
        let plain = page_of(&[
            blk(
                "table_cell",
                vec![figrow(700.0, "alpha", ["9,898", "2,240", "2,598"])],
            ),
            blk(
                "table_cell",
                vec![figrow(688.0, "bravo", ["1,111", "2,222", "3,333"])],
            ),
            blk("paragraph", vec![row(676.0, vec![w("Notes", 72.0, 120.0)])]),
            blk(
                "table_cell",
                vec![figrow(664.0, "charlie", ["4,444", "5,555", "6,666"])],
            ),
            blk(
                "table_cell",
                vec![figrow(652.0, "delta", ["7,777", "8,888", "9,999"])],
            ),
        ]);
        let chosen = vec![
            rows_of(&plain, &["alpha", "bravo"]),
            rows_of(&plain, &["charlie", "delta"]),
        ];
        let mut walker = walker_of(&plain, &chosen, true, true, true);
        let params = walker.params_of(0).expect("columns");
        assert!(
            walker.try_merge(0, 1, Dir::Down, &params, &[], &[]),
            "clean halves did not merge"
        );
        assert_eq!(walker.finish().len(), 1);
    }
}