pdf-inspector 1.22.0

Fast PDF inspection, classification, and text extraction with smart scanned vs text-based detection
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
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
//! Text extraction from PDF using lopdf
//!
//! This module extracts text with position information for structure detection.

mod base14;
mod clip_boundaries;
pub(crate) mod content_decode;
pub(crate) mod content_stream;
pub(crate) mod display_frame;
pub(crate) mod fonts;
pub(crate) mod geometry;
mod layout;
mod links;
pub(crate) mod page_box;
mod reading_order;
mod scripts;
mod text_paint;
pub(crate) mod underline;
pub(crate) mod word_gaps;
mod xobjects;

use crate::text_utils::{is_cjk_char, is_rtl_text};
use crate::tounicode::FontCMaps;
use crate::types::{PageExtraction, PdfLine, PdfRect, TextItem};
use crate::PdfError;
use log::debug;
use lopdf::{Document, Object, ObjectId};
use std::borrow::Cow;
use std::collections::{HashMap, HashSet};
use std::path::Path;

use content_stream::extract_page_text_items_with_options;
pub(crate) use content_stream::TextExtractionOptions;
pub(crate) use display_frame::DisplayPage;
pub use display_frame::PositionFrame;

/// Options of the positioned-text and region APIs, taken by their
/// `_with_options` variants ([`extract_text_with_positions_mem_with_options`],
/// [`extract_text_with_positions_and_rotations_mem_with_options`],
/// [`extract_text_in_regions_mem_with_options`](crate::extract_text_in_regions_mem_with_options),
/// [`extract_tables_in_regions_mem_with_options`](crate::extract_tables_in_regions_mem_with_options)).
/// The default is what the plain and `_in_frame` variants do.
///
/// ```
/// use pdf_inspector::{PositionFrame, PositionOptions};
///
/// let options = PositionOptions::new()
///     .frame(PositionFrame::Display)
///     .bold_from_weight(true)
///     .bold_weight_threshold(700);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct PositionOptions {
    /// Coordinate frame items are reported in and region rects are read
    /// in; [`PositionFrame::Sheet`] by default.
    pub frame: PositionFrame,
    /// Read bold from the font's weight class as well. When set,
    /// `TextItem::is_bold` is also `true` for items whose
    /// `TextItem::font_weight` is `bold_weight_threshold` (600, SemiBold,
    /// by default) or more, `TextItem::bold_source` says so, and adjacent
    /// runs are merged by that verdict: a run the weight makes bold stays
    /// apart from its plain neighbours, so a heavier run inside a lighter
    /// paragraph keeps its own item, while runs whose weights differ but
    /// agree on bold — both below the threshold, or both at or above it —
    /// merge as usual. Off by default: `is_bold` and item merging are then
    /// exactly what they were before the option existed, and `font_weight`
    /// is reported either way.
    pub bold_from_weight: bool,
    /// The weight class from which `bold_from_weight` reads bold, on the
    /// 100..=900 scale: 600 by default, so SemiBold and heavier faces are
    /// bold. It matters only when `bold_from_weight` is set; a value outside
    /// the scale is clamped into it either way.
    pub bold_weight_threshold: u16,
}

impl Default for PositionOptions {
    fn default() -> Self {
        Self {
            frame: PositionFrame::default(),
            bold_from_weight: false,
            bold_weight_threshold: content_stream::DEFAULT_BOLD_WEIGHT_THRESHOLD,
        }
    }
}

impl PositionOptions {
    /// The defaults: sheet frame, bold not read from the weight class, a
    /// threshold of 600 for when it is.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the coordinate frame.
    pub fn frame(mut self, frame: PositionFrame) -> Self {
        self.frame = frame;
        self
    }

    /// Set whether bold is also read from the weight class.
    pub fn bold_from_weight(mut self, bold_from_weight: bool) -> Self {
        self.bold_from_weight = bold_from_weight;
        self
    }

    /// Set the weight class from which bold is read when `bold_from_weight`
    /// is on: 600 by default, valid values 100..=900.
    pub fn bold_weight_threshold(mut self, threshold: u16) -> Self {
        self.bold_weight_threshold = threshold;
        self
    }

    /// The content-stream switches these options ask for.
    pub(crate) fn text_extraction(self, include_invisible: bool) -> TextExtractionOptions {
        TextExtractionOptions {
            include_invisible,
            bold_from_weight: self.bold_from_weight,
            bold_weight_threshold: self.bold_weight_threshold.clamp(100, 900),
        }
    }
}
use links::{extract_form_fields, extract_page_links};
pub(crate) use page_box::{visible_page_box, PageBox};

// Re-export public types so existing `crate::extractor::X` paths keep working.
pub use crate::text_utils::{is_bold_font, is_italic_font};
pub use crate::types::{ItemType, TextLine};
pub(crate) use fonts::FontStyleCache;
pub(crate) use layout::detect_columns;
#[cfg(test)]
use layout::filter_markdown_page_numbers;
pub(crate) use layout::filter_markdown_page_numbers_with_removed_pages;
pub(crate) use layout::group_into_lines_with_thresholds;
pub(crate) use layout::group_prefiltered_items_into_lines_with_thresholds_and_charts;
pub(crate) use layout::group_prefiltered_items_into_lines_with_thresholds_and_regions;
pub(crate) use layout::is_newspaper_layout;
pub(crate) use layout::ColumnRegion;
pub use layout::{group_into_lines, group_into_lines_preserving_all_text};
pub(crate) use scripts::merge_subscript_items;
pub(crate) use xobjects::FormWalkBudget;

// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------

pub(crate) fn trace_text_preview(text: &str, max_chars: usize) -> &str {
    match text.char_indices().nth(max_chars) {
        Some((idx, _)) => &text[..idx],
        None => text,
    }
}

/// Extract text from PDF file as plain string
pub fn extract_text<P: AsRef<Path>>(path: P) -> Result<String, PdfError> {
    crate::validate_pdf_file(&path)?;
    let (doc, _) = crate::load_document_from_path(&path)?;
    extract_text_from_doc(&doc)
}

/// Extract text from PDF memory buffer
pub fn extract_text_mem(buffer: &[u8]) -> Result<String, PdfError> {
    crate::validate_pdf_bytes(buffer)?;
    let (doc, _) = crate::load_document_from_mem(buffer)?;
    extract_text_from_doc(&doc)
}

/// Extract text from loaded document
fn extract_text_from_doc(doc: &Document) -> Result<String, PdfError> {
    let pages = doc.get_pages();
    let page_nums: Vec<u32> = pages.keys().cloned().collect();

    doc.extract_text(&page_nums)
        .map_err(|e| PdfError::Parse(e.to_string()))
}

/// Extract text with position information from a PDF file.
///
/// # Coordinate frame
///
/// Every positioned item (text, image placeholder, link, form field) is
/// reported in PDF points relative to the page's **visible page box**:
/// `CropBox ∩ MediaBox` when the page has a CropBox, else the MediaBox. The
/// box's lower-left corner is the origin and `y` grows upward. A renderer's
/// page image and the region APIs ([`crate::extract_text_in_regions_mem`]
/// and friends) use the same box from its top-left corner with `y` growing
/// downward, so flipping `y` by the box height moves between the two. Raw
/// content-stream coordinates differ whenever the CropBox or MediaBox origin
/// is not `(0, 0)`. Pages whose text is drawn rotated by 90° are normalized
/// into a synthetic landscape frame before the shift; `/Rotate` is not
/// applied. See [`TextItem`] for the full note.
pub fn extract_text_with_positions<P: AsRef<Path>>(path: P) -> Result<Vec<TextItem>, PdfError> {
    extract_text_with_positions_pages(path, None)
}

/// Extract text with positions from a file, limited to specific pages.
///
/// `page_filter` is an optional set of 1-indexed page numbers to process.
/// When `None`, all pages are processed. Coordinates: see
/// [`extract_text_with_positions`].
pub fn extract_text_with_positions_pages<P: AsRef<Path>>(
    path: P,
    page_filter: Option<&HashSet<u32>>,
) -> Result<Vec<TextItem>, PdfError> {
    let (items, _rects, _lines) =
        extract_text_with_positions_and_rects_with_password(path, page_filter, None)?;
    Ok(items)
}

/// Extract text with positions from a file, limited to specific pages and
/// decrypting with `password` when the PDF is encrypted.
///
/// `page_filter` is an optional set of 1-indexed page numbers to process.
/// When `None`, all pages are processed. Coordinates: see
/// [`extract_text_with_positions`].
pub fn extract_text_with_positions_pages_with_password<P: AsRef<Path>>(
    path: P,
    page_filter: Option<&HashSet<u32>>,
    password: Option<&str>,
) -> Result<Vec<TextItem>, PdfError> {
    let (items, _rects, _lines) =
        extract_text_with_positions_and_rects_with_password(path, page_filter, password)?;
    Ok(items)
}

pub(crate) fn extract_text_with_positions_and_rects_with_password<P: AsRef<Path>>(
    path: P,
    page_filter: Option<&HashSet<u32>>,
    password: Option<&str>,
) -> Result<PageExtraction, PdfError> {
    crate::validate_pdf_file(&path)?;
    let (doc, _) = crate::load_document_from_path_with_password(&path, password)?;
    let font_cmaps = FontCMaps::from_doc(&doc);
    let (extraction, _thresholds, _gid_pages, _page_rotations) =
        extract_positioned_text_from_doc_in_page_box(
            &doc,
            &font_cmaps,
            page_filter,
            PositionOptions::default(),
        )?;
    Ok(extraction)
}

/// Extract text with positions from a memory buffer. Coordinates: see
/// [`extract_text_with_positions`].
pub fn extract_text_with_positions_mem(buffer: &[u8]) -> Result<Vec<TextItem>, PdfError> {
    extract_text_with_positions_mem_pages(buffer, None)
}

/// Extract text with positions from a memory buffer, limited to specific
/// pages. Coordinates: see [`extract_text_with_positions`].
pub fn extract_text_with_positions_mem_pages(
    buffer: &[u8],
    page_filter: Option<&HashSet<u32>>,
) -> Result<Vec<TextItem>, PdfError> {
    extract_text_with_positions_mem_in_frame(buffer, page_filter, PositionFrame::Sheet)
}

/// Extract text with positions from a memory buffer in the given coordinate
/// frame, limited to specific pages.
///
/// [`PositionFrame::Sheet`] is the frame of [`extract_text_with_positions`]:
/// the visible page box as laid out in the content stream, `/Rotate` not
/// applied, with predominantly rotated pages turned so their text reads
/// left-to-right. [`PositionFrame::Display`] reports every item — text and
/// image placeholders, links and form fields alike — in the rendered page's
/// frame instead: the visible box turned clockwise by the page's inheritable
/// `/Rotate`, lower-left origin, `y` up, with the turn of a rotated page
/// undone first. Baseline angles (`TextItem::rotation`) are expressed in the
/// same frame, so text that renders horizontally reads as `0`.
pub fn extract_text_with_positions_mem_in_frame(
    buffer: &[u8],
    page_filter: Option<&HashSet<u32>>,
    frame: PositionFrame,
) -> Result<Vec<TextItem>, PdfError> {
    extract_text_with_positions_mem_with_options(
        buffer,
        page_filter,
        PositionOptions::new().frame(frame),
    )
}

/// [`extract_text_with_positions_mem_in_frame`] with every option of the
/// positioned-text APIs given as a [`PositionOptions`]: the frame, and
/// whether bold is also read from the font's weight class
/// (`bold_from_weight`). The default options are that function with
/// [`PositionFrame::Sheet`].
pub fn extract_text_with_positions_mem_with_options(
    buffer: &[u8],
    page_filter: Option<&HashSet<u32>>,
    options: PositionOptions,
) -> Result<Vec<TextItem>, PdfError> {
    let (items, _page_rotations) =
        extract_text_with_positions_and_rotations_mem_with_options(buffer, page_filter, options)?;
    Ok(items)
}

/// Extract text with positions from a memory buffer, together with the
/// coordinate frame of every page whose text was predominantly rotated.
///
/// Such pages are re-based so their dominant runs read left-to-right (see
/// [`PageRotation`](crate::PageRotation)); their items live in the turned
/// frame, and region boxes given in page coordinates must be turned the same
/// way with [`collect_text_in_region_in_frame`](crate::collect_text_in_region_in_frame).
/// Pages absent from the map are upright. Keys are 1-indexed like
/// `TextItem::page`.
pub fn extract_text_with_positions_and_rotations_mem(
    buffer: &[u8],
) -> Result<(Vec<TextItem>, HashMap<u32, geometry::PageRotation>), PdfError> {
    extract_text_with_positions_and_rotations_mem_in_frame(buffer, None, PositionFrame::Sheet)
}

/// [`extract_text_with_positions_and_rotations_mem`] limited to specific
/// pages and reporting items in the given coordinate frame (see
/// [`extract_text_with_positions_mem_in_frame`]).
///
/// The returned map names the pages whose text was predominantly rotated
/// whatever the frame: in the display frame their turn has already been
/// undone, so the map is informational there.
pub fn extract_text_with_positions_and_rotations_mem_in_frame(
    buffer: &[u8],
    page_filter: Option<&HashSet<u32>>,
    frame: PositionFrame,
) -> Result<(Vec<TextItem>, HashMap<u32, geometry::PageRotation>), PdfError> {
    extract_text_with_positions_and_rotations_mem_with_options(
        buffer,
        page_filter,
        PositionOptions::new().frame(frame),
    )
}

/// [`extract_text_with_positions_and_rotations_mem_in_frame`] with every
/// option given as a [`PositionOptions`] — see
/// [`extract_text_with_positions_mem_with_options`].
pub fn extract_text_with_positions_and_rotations_mem_with_options(
    buffer: &[u8],
    page_filter: Option<&HashSet<u32>>,
    options: PositionOptions,
) -> Result<(Vec<TextItem>, HashMap<u32, geometry::PageRotation>), PdfError> {
    crate::validate_pdf_bytes(buffer)?;
    let (doc, _) = crate::load_document_from_mem(buffer)?;
    let font_cmaps = FontCMaps::from_doc(&doc);
    let ((mut items, _rects, _lines), _thresholds, _gid_pages, page_rotations) =
        extract_positioned_text_from_doc_in_page_box(&doc, &font_cmaps, page_filter, options)?;
    if options.frame == PositionFrame::Display {
        display_frame::document_items_to_display_frame(&doc, &mut items, &page_rotations);
    }
    Ok((items, page_rotations))
}

/// One page's geometry in the visible-page-box frame, from
/// [`extract_page_text_items_in_page_box`].
pub(crate) struct PageBoxExtraction {
    pub(crate) items: Vec<TextItem>,
    pub(crate) rects: Vec<PdfRect>,
    pub(crate) lines: Vec<PdfLine>,
    /// Fonts with unresolvable gid-encoded glyphs were encountered.
    pub(crate) has_gid_fonts: bool,
    /// How the page's frame was turned so its text reads left-to-right
    /// (see `content_stream::correct_rotated_page`); `Upright` when it was
    /// not.
    pub(crate) coords_rotated: geometry::PageRotation,
    /// Invisible (Tr 3) text was skipped and could be recovered with
    /// `include_invisible`.
    pub(crate) skipped_invisible: bool,
    /// The visible page box the geometry was shifted into; its height is the
    /// flip height for top-left-origin region inputs.
    pub(crate) page_box: PageBox,
}

/// Page-scoped extraction for the region APIs: `extract_page_text_items`
/// followed by the visible-page-box shift every one of them must apply, so
/// no caller can translate items but forget rects, or skip the rotated
/// shift. Region bounds then flip `y` with `page_box.height()`.
pub(crate) fn extract_page_text_items_in_page_box(
    doc: &Document,
    page_id: ObjectId,
    page_num: u32,
    font_cmaps: &FontCMaps,
    include_invisible: bool,
    style_cache: &mut FontStyleCache,
    form_budget: &mut FormWalkBudget,
) -> Result<PageBoxExtraction, PdfError> {
    extract_page_text_items_in_page_box_with_options(
        doc,
        page_id,
        page_num,
        font_cmaps,
        TextExtractionOptions {
            include_invisible,
            ..TextExtractionOptions::default()
        },
        style_cache,
        form_budget,
    )
}

/// [`extract_page_text_items_in_page_box`] with every content-stream switch
/// given.
pub(crate) fn extract_page_text_items_in_page_box_with_options(
    doc: &Document,
    page_id: ObjectId,
    page_num: u32,
    font_cmaps: &FontCMaps,
    options: TextExtractionOptions,
    style_cache: &mut FontStyleCache,
    form_budget: &mut FormWalkBudget,
) -> Result<PageBoxExtraction, PdfError> {
    let page_box = visible_page_box(doc, page_id).unwrap_or(PageBox::LETTER);
    let ((mut items, mut rects, mut lines), has_gid_fonts, coords_rotated, skipped_invisible) =
        extract_page_text_items_with_options(
            doc,
            page_id,
            page_num,
            font_cmaps,
            options,
            style_cache,
            form_budget,
        )?;
    page_box.translate_page(&mut items, &mut rects, &mut lines, coords_rotated);
    Ok(PageBoxExtraction {
        items,
        rects,
        lines,
        has_gid_fonts,
        coords_rotated,
        skipped_invisible,
        page_box,
    })
}

// ---------------------------------------------------------------------------
// Orchestration
// ---------------------------------------------------------------------------

/// Per-page adaptive join thresholds from Canva-style letter-spacing detection.
pub(crate) type PageThresholds = HashMap<u32, f32>;

/// Pages (1-indexed, like `TextItem::page`) whose coordinate frame was turned
/// because their text is predominantly rotated; pages absent from the map
/// are upright.
pub(crate) type PageRotations = HashMap<u32, geometry::PageRotation>;

/// Extract positioned text, rectangles, and line segments from a pre-loaded document.
///
/// Also returns per-page adaptive join thresholds for Canva-style pages.
pub(crate) fn extract_positioned_text_from_doc(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    extract_positioned_text_impl(
        doc,
        font_cmaps,
        page_filter,
        TextExtractionOptions::default(),
        None,
        CoordinateFrame::UserSpace,
    )
}

/// [`extract_positioned_text_from_doc`] with every page's geometry shifted
/// into the visible-page-box frame — what the public position APIs return.
/// A page whose frame was turned (see `PageRotation`) gets the equivalently
/// turned shift, so its items, links and form fields agree with region
/// bounds computed from the visible box.
pub(crate) fn extract_positioned_text_from_doc_in_page_box(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
    options: PositionOptions,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    extract_positioned_text_impl(
        doc,
        font_cmaps,
        page_filter,
        options.text_extraction(false),
        None,
        CoordinateFrame::VisiblePageBox,
    )
}

/// Coordinate frame of the geometry a positioned-text extraction returns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CoordinateFrame {
    /// Raw PDF user space, as written in the content stream. The markdown
    /// pipeline works here; its page-edge heuristics never leave it.
    UserSpace,
    /// The visible page box ([`PageBox`]) with its lower-left corner as the
    /// origin — the frame of a rendered page image. Public position APIs
    /// return this so items can be intersected with rendered regions.
    VisiblePageBox,
}

/// Extract selected pages and gather document-wide folio evidence only when a
/// selected page contains an ambiguous contextual page-edge number. Errors on
/// selected pages remain fatal; errors on context-only pages are skipped.
pub(crate) fn extract_positioned_text_with_folio_context(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    extract_positioned_text_with_folio_context_impl(doc, font_cmaps, page_filter, false)
}

/// Invisible-text variant of [`extract_positioned_text_with_folio_context`].
pub(crate) fn extract_positioned_text_include_invisible_with_folio_context(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    extract_positioned_text_with_folio_context_impl(doc, font_cmaps, page_filter, true)
}

fn extract_positioned_text_with_folio_context_impl(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
    include_invisible: bool,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    let options = TextExtractionOptions {
        include_invisible,
        ..TextExtractionOptions::default()
    };
    let Some(required_pages) = page_filter else {
        return extract_positioned_text_impl(
            doc,
            font_cmaps,
            None,
            options,
            None,
            CoordinateFrame::UserSpace,
        );
    };

    let (
        (mut selected_items, mut selected_rects, mut selected_lines),
        mut page_thresholds,
        mut gid_encoded_pages,
        mut page_rotations,
    ) = extract_positioned_text_impl(
        doc,
        font_cmaps,
        Some(required_pages),
        options,
        None,
        CoordinateFrame::UserSpace,
    )?;
    if !layout::needs_document_page_number_context(&selected_items, doc.get_pages().len()) {
        return Ok((
            (selected_items, selected_rects, selected_lines),
            page_thresholds,
            gid_encoded_pages,
            page_rotations,
        ));
    }

    let context_pages: HashSet<u32> = doc
        .get_pages()
        .keys()
        .copied()
        .filter(|page| !required_pages.contains(page))
        .collect();
    let (
        (context_items, context_rects, context_lines),
        context_thresholds,
        context_gid_pages,
        context_rotations,
    ) = extract_positioned_text_impl(
        doc,
        font_cmaps,
        Some(&context_pages),
        options,
        Some(required_pages),
        CoordinateFrame::UserSpace,
    )?;
    selected_items.extend(context_items);
    selected_rects.extend(context_rects);
    selected_lines.extend(context_lines);
    page_thresholds.extend(context_thresholds);
    gid_encoded_pages.extend(context_gid_pages);
    page_rotations.extend(context_rotations);
    Ok((
        (selected_items, selected_rects, selected_lines),
        page_thresholds,
        gid_encoded_pages,
        page_rotations,
    ))
}

/// Extract all pages for document-wide analysis while allowing malformed
/// unselected pages to be skipped. Any requested page still fails normally.
pub(crate) fn extract_positioned_text_for_document_analysis(
    doc: &Document,
    font_cmaps: &FontCMaps,
    required_pages: &HashSet<u32>,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    extract_positioned_text_impl(
        doc,
        font_cmaps,
        None,
        TextExtractionOptions::default(),
        Some(required_pages),
        CoordinateFrame::UserSpace,
    )
}

fn extract_positioned_text_impl(
    doc: &Document,
    font_cmaps: &FontCMaps,
    page_filter: Option<&HashSet<u32>>,
    options: TextExtractionOptions,
    required_pages: Option<&HashSet<u32>>,
    frame: CoordinateFrame,
) -> Result<(PageExtraction, PageThresholds, HashSet<u32>, PageRotations), PdfError> {
    let pages = doc.get_pages();
    let mut all_items = Vec::new();
    let mut all_rects = Vec::new();
    let mut all_lines = Vec::new();
    let mut page_thresholds: PageThresholds = HashMap::new();
    let mut gid_encoded_pages: HashSet<u32> = HashSet::new();
    // Embedded-font style flags are document-scoped: the same font program
    // is shared across pages, so parse it once, not once per page.
    let mut style_cache = FontStyleCache::new();
    // Pages whose coordinate frame was turned (see `PageRotation`): the
    // document-level annotation items appended below must follow.
    let mut page_rotations: PageRotations = HashMap::new();
    // Visible page box per extracted page, for the form-field shift below.
    let mut page_boxes: HashMap<u32, PageBox> = HashMap::new();

    // Build page ObjectId → page number map for form field extraction
    let page_id_to_num: HashMap<ObjectId, u32> =
        pages.iter().map(|(num, &id)| (id, *num)).collect();

    for (page_num, &page_id) in pages.iter() {
        if let Some(filter) = page_filter {
            if !filter.contains(page_num) {
                continue;
            }
        }
        let page_result = extract_page_text_items_with_options(
            doc,
            page_id,
            *page_num,
            font_cmaps,
            options,
            &mut style_cache,
            &mut FormWalkBudget::new(),
        );
        let ((mut items, mut rects, mut lines), has_gid_fonts, coords_rotated, _skipped_invisible) =
            match page_result {
                Ok(extraction) => extraction,
                Err(error)
                    if required_pages.is_some_and(|required| !required.contains(page_num)) =>
                {
                    debug!(
                        "page {}: skipping context-only extraction error: {}",
                        page_num, error
                    );
                    continue;
                }
                Err(error) => return Err(error),
            };
        if coords_rotated != geometry::PageRotation::Upright {
            page_rotations.insert(*page_num, coords_rotated);
        }
        // Clip to the visible page box: single-page extracts and imposed
        // spreads keep neighboring pages' content in the stream, positioned
        // outside the CropBox. Extracting it interleaves invisible text into
        // the page and poisons font statistics. On a turned page the box is
        // turned the same way, so the test runs in the items' own frame.
        let page_box = visible_page_box(doc, page_id);
        let mut clipped_box: Option<(f32, f32, f32, f32)> = None;
        let clip_box = page_box.map(|b| {
            let (mut x, mut y, mut w, mut h) = (b.x0, b.y0, b.x1 - b.x0, b.y1 - b.y0);
            coords_rotated.rotate_box(&mut x, &mut y, &mut w, &mut h);
            (x, y, x + w, y + h)
        });
        if let Some((bx0, by0, bx1, by1)) = clip_box {
            const TOL: f32 = 6.0;
            let outside = |it: &TextItem| {
                let cx = it.x + it.width / 2.0;
                !(cx >= bx0 - TOL && cx <= bx1 + TOL && it.y >= by0 - TOL && it.y <= by1 + TOL)
            };
            // Only clip when the off-page material reads as coherent text
            // (neighboring-page paragraphs). Curved/rotated display text
            // leaves short glyph fragments with artifact coordinates
            // outside the box, and those must stay.
            let off: Vec<&TextItem> = items.iter().filter(|it| outside(it)).collect();
            // Judge by character mass: paragraphs are dominated by long
            // word runs even when interleaved with short math fragments,
            // while glyph-confetti is short items through and through.
            let total_chars: usize = off.iter().map(|it| it.text.trim().chars().count()).sum();
            let wordy_chars: usize = off
                .iter()
                .map(|it| it.text.trim().chars().count())
                .filter(|&n| n >= 4)
                .sum();
            // Genuine neighboring-page content is cleanly separated from
            // on-page text. When an off-page item continues an on-page
            // line (same baseline, near-adjacent x), the coordinates are
            // artifacts of transforms we mis-model — don't clip those.
            let straddles = off.iter().any(|o| {
                items.iter().any(|i| {
                    !outside(i) && (i.y - o.y).abs() <= 2.0 && (o.x - (i.x + i.width)).abs() <= 10.0
                })
            });
            let coherent = off.len() >= 10 && wordy_chars * 2 >= total_chars.max(1) && !straddles;
            if bx1 - bx0 >= 72.0 && by1 - by0 >= 72.0 && coherent {
                let before = items.len();
                items.retain(|it| !outside(it));
                if items.len() < before {
                    debug!(
                        "page {}: clipped {} items outside page box ({:.0},{:.0})-({:.0},{:.0})",
                        page_num,
                        before - items.len(),
                        bx0,
                        by0,
                        bx1,
                        by1
                    );
                    // Only prune off-page geometry when off-page text
                    // existed — same neighboring-page content.
                    let overlaps = |x: f32, y: f32, w: f32, h: f32| {
                        let (x0, x1) = if w < 0.0 { (x + w, x) } else { (x, x + w) };
                        let (y0, y1) = if h < 0.0 { (y + h, y) } else { (y, y + h) };
                        x0 < bx1 + TOL && x1 > bx0 - TOL && y0 < by1 + TOL && y1 > by0 - TOL
                    };
                    rects.retain(|r| overlaps(r.x, r.y, r.width, r.height));
                    clipped_box = Some((bx0, by0, bx1, by1));
                    lines.retain(|l| {
                        overlaps(
                            l.x1.min(l.x2),
                            l.y1.min(l.y2),
                            (l.x2 - l.x1).abs(),
                            (l.y2 - l.y1).abs(),
                        )
                    });
                }
            }
        }
        if has_gid_fonts {
            gid_encoded_pages.insert(*page_num);
        }
        let threshold = crate::text_utils::fix_letterspaced_items(&mut items);
        if threshold > 0.10 {
            page_thresholds.insert(*page_num, threshold);
        }
        suppress_table_underlines(&mut items, &rects, &lines, *page_num);
        debug!(
            "page {}: {} text items, {} rects, {} lines{}",
            page_num,
            items.len(),
            rects.len(),
            lines.len(),
            if has_gid_fonts {
                " [gid-encoded fonts]"
            } else {
                ""
            }
        );
        if log::log_enabled!(log::Level::Trace) {
            for item in &items {
                log::trace!(
                    "  p={} x={:7.1} y={:7.1} w={:7.1} fs={:5.1} font={:6} {:?}",
                    page_num,
                    item.x,
                    item.y,
                    item.width,
                    item.font_size,
                    item.font,
                    trace_text_preview(&item.text, 80)
                );
            }
        }
        // Public position APIs report geometry relative to the visible page
        // box; the markdown pipeline stays in raw user space.
        let frame_box = page_box.unwrap_or(PageBox::LETTER);
        if frame == CoordinateFrame::VisiblePageBox {
            frame_box.translate_page(&mut items, &mut rects, &mut lines, coords_rotated);
        }
        page_boxes.insert(*page_num, frame_box);
        all_items.extend(items);
        all_rects.extend(rects);
        all_lines.extend(lines);

        // Extract hyperlinks from page annotations. A turned page turns its
        // annotation boxes too, so links stay on the text they cover and in
        // the regions that text is assigned to.
        let mut links = extract_page_links(doc, page_id, *page_num);
        for link in &mut links {
            coords_rotated.rotate_box(&mut link.x, &mut link.y, &mut link.width, &mut link.height);
        }
        // Annotations from the neighboring page are off-box too.
        if let Some((bx0, by0, bx1, by1)) = clipped_box {
            links.retain(|it| {
                let cx = it.x + it.width / 2.0;
                // Center-y, not it.y: link items carry an annotation rect,
                // so y is a box edge — unlike text items, where y is a
                // baseline and testing it directly is the natural semantics.
                let cy = it.y + it.height / 2.0;
                cx >= bx0 - 6.0 && cx <= bx1 + 6.0 && cy >= by0 - 6.0 && cy <= by1 + 6.0
            });
        }
        if frame == CoordinateFrame::VisiblePageBox {
            // The link rects were turned with the page above, so they take
            // the same turned shift as the page's items.
            frame_box.translate_items(&mut links, coords_rotated);
        }
        all_items.extend(links);
    }

    // Extract AcroForm field values. Widgets on a turned page turn with it,
    // like links, so positional consumers keep them on the text they cover;
    // in the visible-box frame they take the page's (turned) shift as well.
    let form_items: Vec<TextItem> = extract_form_fields(doc, &page_id_to_num)
        .into_iter()
        .filter(|item| page_filter.is_none_or(|filter| filter.contains(&item.page)))
        .map(|mut item| {
            let rotation = page_rotations
                .get(&item.page)
                .copied()
                .unwrap_or(geometry::PageRotation::Upright);
            rotation.rotate_box(&mut item.x, &mut item.y, &mut item.width, &mut item.height);
            if frame == CoordinateFrame::VisiblePageBox {
                let frame_box = page_boxes.get(&item.page).copied().unwrap_or_else(|| {
                    pages
                        .get(&item.page)
                        .and_then(|&id| visible_page_box(doc, id))
                        .unwrap_or(PageBox::LETTER)
                });
                frame_box.translate_items(std::slice::from_mut(&mut item), rotation);
            }
            item
        })
        .collect();
    all_items.extend(form_items);

    Ok((
        (all_items, all_rects, all_lines),
        page_thresholds,
        gid_encoded_pages,
        page_rotations,
    ))
}

fn suppress_table_underlines(
    items: &mut [TextItem],
    rects: &[PdfRect],
    lines: &[PdfLine],
    page: u32,
) {
    if !items
        .iter()
        .any(|item| item.is_underline || item.is_strikeout)
    {
        return;
    }

    let mut table_item_indices: HashSet<usize> = HashSet::new();
    // A detected "table" that swallows nearly every text item on the page
    // is a detection artifact (prose pages with boxed callouts or stacked
    // underline rules read as one giant grid), not a real table — letting
    // it through here erased every legitimate underline on the page
    // (text_dense__underline: rect detection claimed 52/52 items). Real
    // ruled tables share the page with headings, captions, and body text.
    let plausible = |table: &crate::tables::Table| {
        // Content sanity gate: prose pages with boxed callouts and stacked
        // underline rules can detect as a structurally rich "table" that
        // swallows every item on the page (text_dense__underline: a 4x8
        // grid claiming 52/52 items, one "cell" holding 806 chars of body
        // text) — suppressing there erased every legitimate underline on
        // the page. Real data-table cells are short values; a cell with
        // hundreds of characters means the grid captured flowing prose.
        let lens: Vec<usize> = table
            .cells
            .iter()
            .flatten()
            .filter(|cell| !cell.trim().is_empty())
            .map(|cell| cell.chars().count())
            .collect();
        if lens.is_empty() {
            return false;
        }
        let long = lens.iter().filter(|&&n| n > 100).count();
        (long as f32) < (lens.len() as f32) * 0.3
    };

    if !rects.is_empty() {
        let (rect_tables, _) = crate::tables::detect_tables_from_rects(items, rects, page);
        for table in rect_tables.iter().filter(|t| plausible(t)) {
            table_item_indices.extend(table.item_indices.iter().copied());
        }
    }

    if !lines.is_empty() {
        for table in crate::tables::detect_tables_from_lines(items, lines, page)
            .iter()
            .filter(|t| plausible(t))
        {
            table_item_indices.extend(table.item_indices.iter().copied());
        }
    }

    for index in table_item_indices {
        if let Some(item) = items.get_mut(index) {
            item.is_underline = false;
            item.is_strikeout = false;
        }
    }
}

// ---------------------------------------------------------------------------
// Shared helpers (used by submodules via `super::`)
// ---------------------------------------------------------------------------

/// Return true when this item should participate in text-layout
/// heuristics (column detection, table grid detection, line grouping).
///
/// Image XObjects emit a positional placeholder via
/// `extract_text_with_positions` (so layout-aware callers can crop +
/// caption figures), but their bboxes don't carry text glyphs and would
/// skew column/row clustering if they reached the heuristics. Hyperlinks
/// and form fields *do* participate — the existing logic treats them as
/// text-like and we keep that.
pub(crate) fn is_text_layout_item(item: &crate::types::TextItem) -> bool {
    !matches!(item.item_type, crate::types::ItemType::Image)
}

/// Map a (u, v) point in unit-square coordinates through the 6-element CTM
/// to page-space. CTM format is `[a, b, c, d, e, f]` per
/// [`multiply_matrices`].
fn apply_ctm_point(ctm: &[f32; 6], u: f32, v: f32) -> (f32, f32) {
    (
        u * ctm[0] + v * ctm[2] + ctm[4],
        u * ctm[1] + v * ctm[3] + ctm[5],
    )
}

/// Compute the page-space axis-aligned bounding box of an Image XObject
/// invoked under the given CTM.
///
/// Per the PDF spec, an image XObject is always rendered into a unit
/// square `(0,0)–(1,1)` in its local coordinate system, and the `Do`
/// operator applies the current CTM to position/scale/rotate that square
/// onto the page. For the common axis-aligned case (no rotation/shear),
/// the CTM reduces to `[w, 0, 0, h, x, y]` and the bbox is just
/// `(x, y, w, h)`. For rotated/sheared images we transform all four
/// corners and return their axis-aligned bbox so the caller always gets
/// an upright rectangle.
///
/// Coordinates are PDF user space (origin at bottom-left, y-up). Width
/// and height are non-negative.
pub(crate) fn image_bbox_from_ctm(ctm: &[f32; 6]) -> (f32, f32, f32, f32) {
    let corners = [
        apply_ctm_point(ctm, 0.0, 0.0),
        apply_ctm_point(ctm, 1.0, 0.0),
        apply_ctm_point(ctm, 1.0, 1.0),
        apply_ctm_point(ctm, 0.0, 1.0),
    ];
    let (mut x_min, mut x_max) = (corners[0].0, corners[0].0);
    let (mut y_min, mut y_max) = (corners[0].1, corners[0].1);
    for (cx, cy) in corners.iter().skip(1) {
        if *cx < x_min {
            x_min = *cx;
        }
        if *cx > x_max {
            x_max = *cx;
        }
        if *cy < y_min {
            y_min = *cy;
        }
        if *cy > y_max {
            y_max = *cy;
        }
    }
    (x_min, y_min, x_max - x_min, y_max - y_min)
}

/// Multiply two 2D transformation matrices
/// Matrix format: [a, b, c, d, e, f] representing:
/// | a  b  0 |
/// | c  d  0 |
/// | e  f  1 |
pub(crate) fn multiply_matrices(m1: &[f32; 6], m2: &[f32; 6]) -> [f32; 6] {
    [
        m1[0] * m2[0] + m1[1] * m2[2],
        m1[0] * m2[1] + m1[1] * m2[3],
        m1[2] * m2[0] + m1[3] * m2[2],
        m1[2] * m2[1] + m1[3] * m2[3],
        m1[4] * m2[0] + m1[5] * m2[2] + m2[4],
        m1[4] * m2[1] + m1[5] * m2[3] + m2[5],
    ]
}

/// Merge adjacent text items on the same line into single items.
///
/// Groups items by (page, Y-position) with a 5pt tolerance, sorts within each
/// group by X, then merges consecutive items that share a similar font size
/// and are close horizontally.
/// Cap item width for merge-gap computation to guard against Tw inflation.
///
/// When PDF word-spacing (Tw) is large (used for text justification), the
/// advance width of strings containing spaces extends far past the visible
/// glyph extent.  This inflated width collapses inter-column gaps, making
/// `merge_text_items` incorrectly merge items from different table columns.
///
/// Only applies to non-CJK items whose text contains spaces (where Tw
/// contributes) and whose average width-per-character is abnormally high.
/// Extent used to detect overlapping (backtracking) paint order: the merge
/// width for measured runs, the estimated box for width-less ones — an
/// estimate is still evidence of where a fragment ends, and taking it as zero
/// would let a tagged widthless ActualText line be x-sorted out of order.
fn order_extent(item: &TextItem) -> f32 {
    if item.advance_known {
        effective_merge_width(item)
    } else {
        item.width
    }
}

fn effective_merge_width(item: &TextItem) -> f32 {
    use crate::text_utils::is_cjk_char;

    // An estimated box (font without widths) is the best extent there is for
    // word-gap decisions — as it was when `effective_width` estimated it here;
    // the Tw cap below only makes sense for measured widths.
    if !item.advance_known {
        return item.width;
    }
    if item.width <= 0.0 || item.font_size <= 0.0 {
        return item.width;
    }
    // Tw only inflates strings that contain space characters.
    if !item.text.contains(' ') {
        return item.width;
    }
    // CJK characters are naturally ~1.0× font_size wide; skip the cap.
    if item.text.chars().any(is_cjk_char) {
        return item.width;
    }
    let char_count = item.text.chars().count();
    if char_count == 0 {
        return item.width;
    }
    let avg = item.width / char_count as f32;
    // Normal proportional text: ~0.5× font_size per char.
    // Monospace: ~0.6×.  Threshold at 0.85× catches Tw inflation.
    if avg > item.font_size * 0.85 {
        let capped = char_count as f32 * item.font_size * 0.6;
        capped.min(item.width)
    } else {
        item.width
    }
}

fn is_standalone_bullet_text(text: &str) -> bool {
    matches!(text.trim(), "•" | "○" | "●" | "◦")
}

fn first_text_char(text: &str) -> Option<char> {
    text.trim_start().chars().next()
}

fn is_short_alpha_fragment(text: &str) -> bool {
    let trimmed = text.trim();
    let char_count = trimmed.chars().count();
    (1..=4).contains(&char_count) && trimmed.chars().all(char::is_alphabetic)
}

fn has_phrase_continuation_shape(text: &str) -> bool {
    let trimmed = text.trim_start();
    trimmed
        .chars()
        .take(24)
        .any(|ch| ch.is_whitespace() || matches!(ch, '-'))
}

fn should_preserve_overlapping_stream_order(group: &[&TextItem]) -> bool {
    if group.len() < 3 {
        return false;
    }

    let Some(first) = group.iter().find(|item| !item.text.trim().is_empty()) else {
        return false;
    };
    if group.iter().all(|item| item.mcid.is_none()) {
        return false;
    }

    let mut nonempty_count = 0;
    let mut saw_backtrack = false;
    let mut nonspace_chars = 0;
    let mut math_symbol_chars = 0;
    let mut max_font_size = first.font_size;

    for item in group {
        if !item.text.trim().is_empty() {
            nonempty_count += 1;
        }
        if (item.font_size - first.font_size).abs() > first.font_size * 0.25 {
            return false;
        }
        max_font_size = max_font_size.max(item.font_size);
        for ch in item.text.chars().filter(|ch| !ch.is_whitespace()) {
            nonspace_chars += 1;
            if matches!(
                ch,
                '*' | 'ˆ' | '^' | '=' | '+' | '_' | '[' | ']' | '{' | '}' | '|' | '<' | '>'
            ) {
                math_symbol_chars += 1;
            }
        }
    }

    if nonempty_count < 2 {
        return false;
    }
    if nonspace_chars > 0 && math_symbol_chars * 4 > nonspace_chars {
        return false;
    }

    let mut sorted_by_x = group.to_vec();
    sorted_by_x.sort_by(|a, b| a.x.total_cmp(&b.x));
    let cluster_start = sorted_by_x[0].x;
    let mut cluster_end = cluster_start + order_extent(sorted_by_x[0]);
    for item in sorted_by_x.iter().skip(1) {
        let gap = item.x - cluster_end;
        if gap > max_font_size * 2.5 {
            return false;
        }
        cluster_end = cluster_end.max(item.x + order_extent(item));
    }
    if cluster_end - cluster_start > max_font_size * 36.0 {
        return false;
    }

    for index in 0..group.len() - 1 {
        let previous = group[index];
        let next = group[index + 1];
        let font_size = previous.font_size.max(next.font_size);
        let backtrack_threshold = font_size * 0.25;
        let previous_start = previous.x;
        let next_start = next.x;
        let next_end = next.x + order_extent(next);
        if next_start < previous_start - backtrack_threshold
            && next_end > previous_start + backtrack_threshold
        {
            let has_near_prefix = group[..=index].iter().rev().take(4).any(|item| {
                is_short_alpha_fragment(&item.text)
                    && item.x >= next_start - font_size * 0.5
                    && item.x <= next_start + font_size * 4.0
            });
            let starts_lowercase = first_text_char(&next.text).is_some_and(char::is_lowercase);
            let phrase_continuation = has_phrase_continuation_shape(&next.text);
            let has_near_bullet = group[..=index]
                .iter()
                .position(|item| {
                    is_standalone_bullet_text(&item.text) && next_start <= item.x + font_size * 3.0
                })
                .is_some_and(|bullet_index| {
                    if bullet_index >= index {
                        return false;
                    }
                    group[bullet_index + 1..=index]
                        .iter()
                        .rev()
                        .find(|item| !item.text.trim().is_empty())
                        .is_some_and(|item| {
                            item.text.trim().chars().count() <= 8
                                && has_phrase_continuation_shape(&next.text)
                        })
                });
            if (has_near_prefix && starts_lowercase && phrase_continuation) || has_near_bullet {
                saw_backtrack = true;
                break;
            }
        }
    }

    saw_backtrack
}

/// Detect a tracked (letter-spaced) run of single-glyph items and derive its
/// run-local space floor.
///
/// Display type set with tracking renders one glyph per show op; the merge
/// loop's fixed thresholds (0.08-0.13 em) then read every letter gap as a
/// word boundary and emit "H O W" instead of "HOW". Within such a run the
/// gaps carry the real signal: letter gaps cluster tightly just above the
/// fixed threshold, word gaps sit clearly higher. Returns (run_end_index,
/// space_floor) when the run starting at `start` is tracked — spaces are
/// then inserted only at gaps above the floor (infinity = single word).
/// Normal text (multi-char items, or single-char runs with sub-threshold
/// gaps) returns None and keeps the existing behavior.
/// Han/Kana scripts write without inter-word spaces. Hangul (Korean) DOES
/// space between words and deliberately stays out of this set — a Korean
/// tracked run keeps normal word-boundary handling.
pub(crate) fn is_spaceless_cjk(c: char) -> bool {
    matches!(c,
        '\u{3000}'..='\u{303F}'   // CJK Symbols and Punctuation
        | '\u{3040}'..='\u{309F}' // Hiragana
        | '\u{30A0}'..='\u{30FF}' // Katakana
        | '\u{4E00}'..='\u{9FFF}' // CJK Unified Ideographs
        | '\u{F900}'..='\u{FAFF}' // CJK Compatibility Ideographs
        | '\u{FF00}'..='\u{FFEF}' // Halfwidth and Fullwidth Forms
    )
}

fn tracked_run_space_floor(group: &[&TextItem], start: usize) -> Option<(usize, f32)> {
    const MIN_GAPS: usize = 4;
    let first = group[start];
    if first.text.trim().chars().count() != 1 {
        return None;
    }
    let fs = first.font_size;
    if fs <= 0.0 {
        return None;
    }

    // Walk the run under the SAME break conditions as the merge loop
    // (size band, style equality, mergeable gap) so indices stay aligned.
    let mut gaps: Vec<f32> = Vec::new();
    let mut end_x = first.x + effective_merge_width(first);
    let mut end = start;
    for (offset, next) in group[start + 1..].iter().enumerate() {
        if next.text.trim().chars().count() != 1 {
            break;
        }
        if (next.font_size - fs).abs() > fs * 0.20 {
            break;
        }
        if next.is_bold != first.is_bold
            || next.is_italic != first.is_italic
            || next.is_underline != first.is_underline
            || next.is_strikeout != first.is_strikeout
        {
            break;
        }
        let gap = next.x - end_x;
        if gap > fs * 0.5 || gap < -fs * 0.5 {
            break;
        }
        gaps.push(gap / fs);
        end_x = next.x + effective_merge_width(next);
        end = start + 1 + offset;
    }
    if gaps.len() < 2 {
        return None;
    }

    // Tracked signature: the run's TYPICAL gap clears the fixed space
    // threshold (0.08) — the merge loop would break almost every letter
    // pair into "words". Short runs (2-3 gaps: "H O W") demand a stricter
    // shape — clearly wide, uniform, ALL-CAPS — because a genuine spaced
    // sequence of single letters ("x y z" variables) has the same gap
    // count; display tracking is a caps convention.
    let mut sorted = gaps.clone();
    sorted.sort_by(|a, b| a.total_cmp(b));
    let median = sorted[sorted.len() / 2];
    // Typographic convention gate, both tiers: display tracking is an
    // all-caps convention, and Han/Kana never space between glyphs. Mixed-
    // or lowercase Latin runs keep their boundaries because geometry alone
    // cannot distinguish spaced singles ("A b c d e") from a tracked
    // title-case word ("B u f f a l o").
    let run_chars = || {
        group[start..=end]
            .iter()
            .flat_map(|it| it.text.trim().chars())
    };
    let spaceless_cjk = run_chars().all(|c| is_spaceless_cjk(c) || !c.is_alphanumeric())
        && run_chars().any(is_spaceless_cjk);
    let all_caps = run_chars().all(|c| c.is_uppercase() || is_cjk_char(c) || !c.is_alphabetic());
    if !(spaceless_cjk || all_caps) {
        return None;
    }

    if gaps.len() >= MIN_GAPS {
        if median <= 0.075 {
            return None;
        }
    } else {
        let uniform = sorted[sorted.len() - 1] <= sorted[0].max(0.01) * 1.4;
        if median < 0.09 || !uniform {
            return None;
        }
    }

    // Han/Kana: no inter-glyph spaces, period — a nonuniform gap
    // distribution (punctuation spacing, justification) must not
    // manufacture word boundaries.
    if spaceless_cjk {
        return Some((end, f32::INFINITY));
    }

    // Word gaps, if present, form a second mode above the letter-gap
    // cluster: split at the largest relative jump. Unimodal → one word.
    let mut best_jump = 1.0f32;
    let mut floor = f32::INFINITY;
    for pair in sorted.windows(2) {
        let (lo, hi) = (pair[0].max(0.01), pair[1].max(0.01));
        let jump = hi / lo;
        if jump > best_jump {
            best_jump = jump;
            floor = (lo + hi) / 2.0;
        }
    }
    if best_jump < 1.4 {
        floor = f32::INFINITY;
    }
    Some((end, floor * fs))
}

/// Fractional font-size band within which `merge_text_items` treats two runs as
/// the same size. Shared with `is_small_caps_continuation`, which exists only to
/// rescue junctions this band would otherwise break.
const MERGE_FONT_SIZE_BAND: f32 = 0.20;

/// Detect a small-caps continuation: typesetters render small caps as a
/// full-size capital immediately followed by shrunken capitals in the same
/// font (`(R) Tj` at 9.98pt, then `(OLANDO) Tj` at 6.74pt). Those runs are one
/// word, but the font-size band in `merge_text_items` would split them,
/// leaving "R" and "OLANDO" as separate items — which then read as separate
/// table columns, since column boundaries cluster on item start positions.
///
/// Gated tightly so it cannot absorb the other reasons a smaller run follows a
/// larger one:
///   - runs the size band already accepts — excluded by requiring the junction
///     to *cross* the band, so within-band pairs keep the normal word-spacing
///     logic instead of having their space suppressed
///   - superscripts / footnote markers — excluded by requiring an uppercase
///     *letter* on both sides, so digits never qualify
///   - drop caps — excluded because the body text that follows is mixed case
///   - adjacent table cells or separate words — excluded by requiring the runs
///     to be visually contiguous (essentially no gap)
fn is_small_caps_continuation(
    text_so_far: &str,
    first: &TextItem,
    next: &TextItem,
    gap: f32,
) -> bool {
    // Must shrink. Real small caps sit near 0.7-0.8 of the full cap height;
    // anything smaller is a superscript or a different run entirely.
    if first.font_size <= 0.0 || next.font_size >= first.font_size {
        return false;
    }
    // Only rescue junctions the size band would have broken. Within-band pairs
    // merge on their own, and suppressing their space would swallow real word
    // gaps between two similarly-sized uppercase words.
    if (next.font_size - first.font_size).abs() <= first.font_size * MERGE_FONT_SIZE_BAND {
        return false;
    }
    if next.font_size / first.font_size < 0.55 {
        return false;
    }
    // Visually contiguous: the capital and its small caps touch. A real word
    // space or a column gap disqualifies.
    if !(-first.font_size * 0.2..=first.font_size * 0.15).contains(&gap) {
        return false;
    }
    // The continuation must be all-uppercase letters (digits and lowercase
    // both disqualify), and must contain at least one letter.
    let mut saw_letter = false;
    for ch in next.text.chars() {
        if ch.is_alphabetic() {
            saw_letter = true;
            if !ch.is_uppercase() {
                return false;
            }
        } else if ch.is_numeric() {
            return false;
        }
    }
    if !saw_letter {
        return false;
    }
    // What we are continuing must itself end in a capital. Check the actual
    // trailing character rather than skipping back to the nearest letter: after
    // "ANGELA M. MAZZARELLI1" the run to continue is the footnote marker, not
    // the "I" before it.
    let trimmed = text_so_far.trim_end();
    if trimmed.chars().last().is_some_and(|c| c.is_numeric()) {
        // One legitimate exception: an ordinal suffix set as a smaller run,
        // e.g. "JULY 4" + "TH". Only the four English suffixes qualify —
        // anything else after a digit is a footnote marker or numeric suffix.
        return matches!(trimmed_suffix(next), "TH" | "ST" | "ND" | "RD");
    }
    trimmed
        .chars()
        .rev()
        .find(|c| c.is_alphabetic())
        .is_some_and(|c| c.is_uppercase())
}

/// The continuation run's text, trimmed — used to spot ordinal suffixes.
fn trimmed_suffix(next: &TextItem) -> &str {
    next.text.trim()
}

#[cfg(test)]
pub(crate) fn merge_text_items(items: Vec<TextItem>) -> Vec<TextItem> {
    merge_text_items_with_clips(items, &[], false)
}

/// The separators a number is written with: point, comma, colon, slash
/// and the Arabic decimal and thousands separators.
fn is_number_separator(c: char) -> bool {
    matches!(c, '.' | ',' | ':' | '/' | '\u{066B}' | '\u{066C}')
}

/// A fragment of a number: digits of any script, at least one, with the
/// separators that join them and nothing else.
fn numeric_fragment(text: &str) -> bool {
    let text = text.trim();
    text.chars().any(char::is_numeric)
        && text
            .chars()
            .all(|c| c.is_numeric() || is_number_separator(c))
}

/// A fragment of nothing but number separators: a comma or point shown
/// apart from its digits.
fn separator_fragment(text: &str) -> bool {
    let text = text.trim();
    !text.is_empty() && text.chars().all(is_number_separator)
}

/// Whether the junction of two neighbouring fragments lies inside a
/// number: both are number material and at least one holds a digit — a
/// separator shown apart from its digits belongs to the number beside it,
/// while two lone separators make no number.
fn inside_number(a: &str, b: &str) -> bool {
    let material = |text: &str| numeric_fragment(text) || separator_fragment(text);
    material(a) && material(b) && (numeric_fragment(a) || numeric_fragment(b))
}

/// Word-gap floor for a line of right-to-left text shown one glyph per
/// item, from its own gaps: the letter gaps of such a line cluster below
/// its word gaps. Declared advance widths are often off for these fonts,
/// so the fixed em fractions that serve word-by-word runs would put a space
/// after every narrow letter. The gaps are given and the floor returned in
/// em — of the smaller font beside each gap, so a word gap next to a
/// footnote mark or a run of a smaller font is measured by the glyphs it
/// separates. They are split into two classes where the variance between
/// them is largest (Otsu's threshold), and the floor sits between the
/// classes when the upper one is a space's worth apart from the lower —
/// glyphs of a second font with true widths, digits at zero gap beside
/// letters at a small one, form no such class. With one class of gaps the
/// floor is infinite when even the wide ones are mid-word gaps (under the
/// 0.13 em a junction inside a word may open to), so a line of one word
/// holds together; gaps of one class that are wider than that could as
/// well be the word gaps of one-letter words, and the fixed thresholds
/// decide them: `None`.
fn glyph_run_word_gap_floor(gaps: &[f32]) -> Option<f32> {
    if gaps.len() < 3 {
        return None;
    }
    let mut sorted: Vec<f32> = gaps.to_vec();
    sorted.sort_by(|a, b| a.total_cmp(b));
    let total: f32 = sorted.iter().sum();
    let n = sorted.len() as f32;
    let mut best: Option<(f32, f32, f32)> = None; // (between-class variance, low mean, high mean)
    let mut low_sum = 0.0f32;
    for (k, &value) in sorted.iter().enumerate().take(sorted.len() - 1) {
        low_sum += value;
        let low_n = (k + 1) as f32;
        let high_n = n - low_n;
        let low_mean = low_sum / low_n;
        let high_mean = (total - low_sum) / high_n;
        let variance = low_n * high_n * (high_mean - low_mean).powi(2);
        if best.is_none_or(|(v, _, _)| variance > v) {
            best = Some((variance, low_mean, high_mean));
        }
    }
    let upper_quartile = sorted[sorted.len() * 3 / 4];
    match best {
        Some((_, low_mean, high_mean)) if high_mean - low_mean >= 0.12 && high_mean >= 0.2 => {
            Some((low_mean + high_mean) / 2.0)
        }
        _ if upper_quartile <= 0.13 => Some(f32::INFINITY),
        _ => None,
    }
}

/// Bold and plain runs are kept apart whatever said they were bold: with
/// `PositionOptions::bold_from_weight` the weight class has already had its
/// say in `is_bold` (see `content_stream::read_bold_from_weight`), so runs
/// of different weight split only where the bold verdict changes.
/// `visual_rtl` says the page's right-to-left runs are stored in visual
/// order (see `text_utils::fix_visual_order_rtl`): the lines holding them
/// are then read back into logical order here, as they merge.
fn merge_text_items_with_clips(
    items: Vec<TextItem>,
    clips: &[Option<clip_boundaries::ClipRect>],
    visual_rtl: bool,
) -> Vec<TextItem> {
    if items.is_empty() {
        return items;
    }

    // References into `items` remain stable throughout grouping and sorting.
    // Keep clipping provenance private rather than changing the public item type.
    let clip_by_item: HashMap<*const TextItem, clip_boundaries::ClipRect> = items
        .iter()
        .zip(clips)
        .filter_map(|(item, clip)| clip.map(|rect| (item as *const TextItem, rect)))
        .collect();

    // Group items by (page, Y position) with 5pt tolerance
    let y_tolerance = 5.0;
    let mut line_groups: Vec<(u32, f32, Vec<&TextItem>)> = Vec::new();

    for item in &items {
        let found = line_groups
            .iter_mut()
            .find(|(pg, y, _)| *pg == item.page && (item.y - *y).abs() < y_tolerance);
        if let Some((_, _, group)) = found {
            group.push(item);
        } else {
            line_groups.push((item.page, item.y, vec![item]));
        }
    }

    // Each page's own direction: a line with right-to-left letters on a
    // right-to-left page reads right to left even when its Latin letters
    // outnumber them.
    let page_rtl: HashMap<u32, bool> = items
        .iter()
        .map(|item| item.page)
        .collect::<std::collections::HashSet<u32>>()
        .into_iter()
        .map(|page| {
            let rtl = is_rtl_text(items.iter().filter(|i| i.page == page).map(|i| &i.text));
            (page, rtl)
        })
        .collect();

    /// One line's fragments, in the order they are walked.
    struct LineGroup<'a> {
        page: u32,
        y: f32,
        group: Vec<&'a TextItem>,
        /// Each fragment's text as it reads: its own, or on a visual-order
        /// page the stretch of the line's logical text that is its.
        texts: Vec<Cow<'a, str>>,
        preserve_stream_order: bool,
        /// Holds right-to-left letters: walked in reading order, not along +x.
        bidi: bool,
        /// For a `bidi` line, each fragment's position in screen order.
        display_index: Vec<usize>,
        /// For a `bidi` line, the gap between each pair of screen
        /// neighbours, in points, by screen position.
        display_gaps: Vec<f32>,
        /// For a `bidi` line shown one glyph per fragment, the word-gap
        /// floor its own gaps give (`glyph_run_word_gap_floor`), in em of
        /// the smaller font at a junction.
        glyph_floor: Option<f32>,
    }
    let mut ordered_line_groups: Vec<LineGroup<'_>> = Vec::new();

    // Sort each group by X position (direction-aware), except for lines whose
    // content stream intentionally backtracks to overlay ActualText fragments.
    for (page, y, mut group) in line_groups {
        // A line with right-to-left letters, whichever direction dominates
        // it, is walked in reading order below.
        let bidi = group
            .iter()
            .any(|i| i.text.chars().any(crate::text_utils::is_rtl_char));
        let preserve_stream_order = !bidi && should_preserve_overlapping_stream_order(&group);
        let texts: Vec<Cow<'_, str>>;
        let mut display_index: Vec<usize> = Vec::new();
        let mut display_gaps: Vec<f32> = Vec::new();
        let mut glyph_floor: Option<f32> = None;
        if bidi {
            // Screen order first; the fragments are then taken in the reading
            // order the Unicode Bidirectional Algorithm gives the line, so an
            // embedded Latin phrase or number keeps its own order when the
            // concatenation below bakes the order in. On a visual-order page
            // the fragments' glyphs are the display line itself, and each
            // fragment gets its stretch of the logical text back.
            let rtl_base = crate::text_utils::rtl_line_base(
                &group,
                |i| *i,
                page_rtl.get(&page).copied().unwrap_or(false),
            );
            group.sort_by(|a, b| a.x.total_cmp(&b.x));
            // The gaps between screen neighbours, taken once here: two
            // glyphs at one x (a mark over its letter) sort either way, and
            // the reading order below must index the same sequence.
            display_gaps = group
                .windows(2)
                .map(|pair| pair[1].x - (pair[0].x + effective_merge_width(pair[0])))
                .collect();
            // Glyph-by-glyph positioned RTL text clusters into words by the
            // line's own gaps: adjacent glyphs abut, word gaps do not, with
            // the floor below where declared widths are off. Junctions
            // inside a number are never word gaps and say nothing about the
            // letters' gaps either (digits of another font keep true
            // widths), so they stay out of the sample. The same floor
            // separates the words for the bidi analysis and, below, for the
            // merge.
            let single_glyphs = group
                .iter()
                .filter(|i| i.text.trim().chars().count() == 1)
                .count();
            if group.len() >= 4 && single_glyphs * 10 >= group.len() * 7 {
                let gaps: Vec<f32> = group
                    .windows(2)
                    .zip(&display_gaps)
                    .filter(|(pair, _)| !inside_number(&pair[0].text, &pair[1].text))
                    .map(|(pair, gap)| gap / pair[0].font_size.min(pair[1].font_size).max(1.0))
                    .collect();
                glyph_floor = glyph_run_word_gap_floor(&gaps);
            }
            let order = crate::bidi::logical_line_order(
                &group,
                |i| i.text.as_str(),
                |i| (i.x, i.width),
                |i| i.font_size,
                |_| visual_rtl,
                glyph_floor,
                rtl_base,
            );
            let reordered: Vec<&TextItem> = order.iter().map(|&(index, _)| group[index]).collect();
            display_index = order.iter().map(|&(index, _)| index).collect();
            texts = order
                .into_iter()
                .map(|(index, logical)| {
                    if visual_rtl {
                        Cow::Owned(logical)
                    } else {
                        Cow::Borrowed(group[index].text.as_str())
                    }
                })
                .collect();
            group = reordered;
        } else {
            if !preserve_stream_order {
                group.sort_by(|a, b| a.x.total_cmp(&b.x));
            }
            texts = group
                .iter()
                .map(|i| Cow::Borrowed(i.text.as_str()))
                .collect();
        }
        ordered_line_groups.push(LineGroup {
            page,
            y,
            group,
            texts,
            preserve_stream_order,
            bidi,
            display_index,
            display_gaps,
            glyph_floor,
        });
    }

    // Sort groups by page then Y descending (top of page first)
    ordered_line_groups.sort_by(|a, b| a.page.cmp(&b.page).then_with(|| b.y.total_cmp(&a.y)));

    let mut merged = Vec::new();

    for line in &ordered_line_groups {
        let LineGroup {
            group,
            texts,
            preserve_stream_order,
            bidi,
            display_index,
            display_gaps,
            glyph_floor,
            ..
        } = line;
        // A line of right-to-left text is walked in reading order, which
        // runs leftwards through its RTL words and rightwards through an
        // embedded Latin phrase or number, but its word gaps are gaps between
        // neighbours on the page. The gap at a junction of the walk is the
        // gap between the two fragments when they are neighbours in screen
        // order; where the walk jumps into or out of an embedded run, it is
        // the gap between that run's near end and the fragment it turned
        // from — the wider of the two screen gaps that flank the jump, the
        // other being inside a run.
        let junction_gap = |from: usize, to: usize| -> f32 {
            let (a, b) = (display_index[from], display_index[to]);
            if a.abs_diff(b) == 1 {
                return display_gaps[a.min(b)];
            }
            let towards = |at: usize, other: usize| {
                if other > at {
                    display_gaps.get(at).copied()
                } else {
                    at.checked_sub(1).and_then(|k| display_gaps.get(k).copied())
                }
            };
            match (towards(a, b), towards(b, a)) {
                (Some(x), Some(y)) => x.max(y),
                (Some(x), None) | (None, Some(x)) => x,
                (None, None) => 0.0,
            }
        };
        let glyph_floor = *glyph_floor;
        let mut i = 0;
        while i < group.len() {
            let first = group[i];
            let mut text = texts[i].to_string();
            let mut legacy_symbol_rewrite = first.legacy_symbol_rewrite;
            let mut end_x = first.x + effective_merge_width(first);
            let mut box_right = first.x + first.width;
            let mut box_left = first.x;

            // Tracked display text: run-local space floor overrides the
            // fixed thresholds for this run's junctions (see helper).
            let tracked = if *preserve_stream_order || *bidi {
                None
            } else {
                tracked_run_space_floor(group, i)
            };

            let mut j = i + 1;
            while j < group.len() {
                let next = group[j];
                let next_text: &str = &texts[j];
                let gap = if *bidi {
                    junction_gap(j - 1, j)
                } else {
                    next.x - end_x
                };
                // A small-caps junction is mid-word: it both survives the
                // font-size band below and must never take a space.
                let small_caps_join = is_small_caps_continuation(&text, first, next, gap);
                // Must be similar font size, except for genuine small-caps
                // runs, where the shrunken capitals are the same word as the
                // full-size initial (see helper).
                if (next.font_size - first.font_size).abs() > first.font_size * MERGE_FONT_SIZE_BAND
                    && !small_caps_join
                {
                    break;
                }
                // Preserve the existing join behavior at non-bold style
                // boundaries, including italic fragments within formulas.
                if next.is_italic != first.is_italic
                    || next.is_underline != first.is_underline
                    || next.is_strikeout != first.is_strikeout
                {
                    break;
                }
                // Merging walks along +x, which is only the reading direction
                // of upright runs. A vertical stamp whose box bottom shares a
                // baseline with a body line must not be glued onto it, two
                // side-by-side vertical runs are separate lines, and the
                // fragments of an upside-down run read towards -x, so an
                // ascending walk would concatenate them reversed.
                if !first.is_upright() || !next.is_upright() {
                    break;
                }
                // A merged item carries one `advance_known`: never fold a
                // measured run and an estimated one into the same item.
                if next.advance_known != first.advance_known {
                    break;
                }
                let x_gap_max = if *preserve_stream_order && is_standalone_bullet_text(&text) {
                    first.font_size * 1.2
                } else {
                    first.font_size * 0.5
                };
                if gap > x_gap_max {
                    break;
                }
                if gap < -first.font_size * 0.5 && !preserve_stream_order {
                    break;
                }
                let previous = group[j - 1];
                if clip_boundaries::separated_runs(
                    previous,
                    clip_by_item.get(&(previous as *const TextItem)),
                    next,
                    clip_by_item.get(&(next as *const TextItem)),
                ) {
                    break;
                }
                // Vertically stacked DIGITS at different baselines — the
                // numerator over the denominator of a case fraction ("1"
                // over "3") — are not one number even though they share the
                // 5pt band and overlap in x. Letters keep merging: rotated
                // running headers and diagram labels stack letters too, and
                // splitting those only scatters fragments into body text.
                let digits = |t: &str| !t.is_empty() && t.chars().all(char::is_numeric);
                if !preserve_stream_order
                    && (next.y - first.y).abs() > first.font_size * 0.3
                    && gap < -effective_merge_width(next) * 0.5
                    && digits(text.trim())
                    && digits(next_text.trim())
                {
                    break;
                }
                // Insert space at word boundaries.
                // Base threshold 0.08; raised to 0.13 for lowercase→lowercase
                // junctions to accommodate Tc/Tw character-spacing adjustments
                // that shift advance widths relative to Td positioning.
                let threshold = {
                    let prev_last = text.trim_end().chars().last();
                    let next_first = next_text.trim_start().chars().next();
                    // Never insert space before joining punctuation
                    if next_first.is_some_and(|c| matches!(c, '.' | ',' | ';' | ')' | ']' | '}')) {
                        first.font_size * 0.25
                    } else if prev_last.is_some_and(|c| c.is_lowercase())
                        && next_first.is_some_and(|c| c.is_lowercase())
                    {
                        // Lowercase→lowercase: likely mid-word, use wider threshold
                        first.font_size * 0.13
                    } else if prev_last.is_some_and(crate::text_utils::is_rtl_char)
                        && next_first.is_some_and(crate::text_utils::is_rtl_char)
                    {
                        // Two pieces of one Hebrew or Arabic word, split where
                        // the producer kerned or rejoined a glyph run: as
                        // mid-word as a lowercase junction.
                        first.font_size * 0.13
                    } else {
                        first.font_size * 0.08
                    }
                };
                let needs_bullet_space = *preserve_stream_order
                    && is_standalone_bullet_text(&text)
                    && !next_text.trim().is_empty();
                let effective_threshold = match (tracked, glyph_floor) {
                    (Some((run_end, floor)), _) if j <= run_end => floor,
                    (_, Some(floor_em)) => {
                        floor_em * group[j - 1].font_size.min(next.font_size).max(1.0)
                    }
                    _ => threshold,
                };
                let bold_boundary = next.is_bold != first.is_bold;
                let explicit_bold_space = bold_boundary
                    && (text.ends_with(char::is_whitespace)
                        || next_text.starts_with(char::is_whitespace));
                // Numeric fragments have their own joining thresholds in
                // line assembly. Injecting a word space here would split a
                // number whose decimal point or digits use a bold font.
                let numeric_boundary = bold_boundary
                    && match (text.chars().last(), next_text.chars().next()) {
                        (Some(p), Some(c)) if p.is_ascii_digit() => {
                            c.is_ascii_digit() || matches!(c, '.' | ',' | '%')
                        }
                        (Some('.' | ','), Some(c)) if c.is_ascii_digit() => {
                            let prefix = &text[..text.len() - 1];
                            // A separate decimal glyph can start a fractional
                            // number even without a preceding integer run.
                            prefix.trim().is_empty()
                                || prefix.chars().last().is_some_and(|c| c.is_ascii_digit())
                        }
                        (Some('+' | '-'), Some(c)) => c.is_ascii_digit(),
                        _ => false,
                    };
                if !small_caps_join
                    && (needs_bullet_space || (gap > effective_threshold && !numeric_boundary))
                    && !explicit_bold_space
                    && !text.ends_with(char::is_whitespace)
                {
                    text.push(' ');
                }
                // Keep bold runs separate, but preserve the same word-space
                // decision as an unstyled merge. Otherwise the later line
                // assembler's wider joining threshold can glue words when
                // newly recovered font flags split a previously merged run.
                if bold_boundary {
                    break;
                }
                text.push_str(next_text);
                legacy_symbol_rewrite |= next.legacy_symbol_rewrite;
                box_right = box_right.max(next.x + next.width);
                box_left = box_left.min(next.x);
                let next_end = next.x + effective_merge_width(next);
                end_x = if *preserve_stream_order {
                    end_x.max(next_end)
                } else {
                    next_end
                };
                j += 1;
            }

            // Hebrew and Arabic presentation forms stand for letters; now
            // that the text reads in logical order, a ligature's letters
            // come out in reading order.
            let text = crate::bidi::normalize_presentation_forms(&text).into_owned();

            merged.push(TextItem {
                text,
                // An estimated run's item is the union of the estimated boxes
                // it merged, including any fragment that backtracked in x; so
                // is a run with right-to-left text, whose fragments were
                // walked in reading order rather than along +x.
                x: if first.advance_known && !*bidi {
                    first.x
                } else {
                    box_left
                },
                y: first.y,
                width: if first.advance_known && !*bidi {
                    end_x - first.x
                } else {
                    box_right - box_left
                },
                height: first.height,
                font: first.font.clone(),
                font_tag: first.font_tag.clone(),
                legacy_symbol_rewrite,
                font_size: first.font_size,
                page: first.page,
                is_bold: first.is_bold,
                is_italic: first.is_italic,
                font_weight: first.font_weight,
                bold_source: first.bold_source,
                fixed_pitch: first.fixed_pitch,
                is_underline: first.is_underline,
                is_strikeout: first.is_strikeout,
                rotation: first.rotation,
                advance_known: first.advance_known,
                item_type: first.item_type.clone(),
                mcid: first.mcid,
                baseline_shift: 0.0,
            });

            i = j;
        }
    }

    merged
}

/// Helper to get f32 from Object
pub(crate) fn get_number(obj: &Object) -> Option<f32> {
    match obj {
        Object::Integer(i) => Some(*i as f32),
        Object::Real(r) => Some(*r),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::text_utils::{is_cjk_char, is_rtl_char, is_rtl_text, sort_line_items};
    use crate::types::{ItemType, PdfLine, TextLine};
    use layout::{detect_columns, is_newspaper_layout, ColumnRegion};

    /// Glyph-per-item run at `fs`=12 with the given inter-glyph gap (pt).
    #[test]
    fn numeric_fragments_are_digits_of_any_script_with_their_separators() {
        assert!(numeric_fragment("12"));
        assert!(numeric_fragment(" 1,234.5 "));
        assert!(numeric_fragment("\u{0662}\u{0664}"));
        assert!(numeric_fragment("\u{0663}\u{066B}\u{0665}"));
        assert!(!numeric_fragment(""));
        assert!(!numeric_fragment("a1"));
        assert!(!numeric_fragment("\u{05D0}"));
        assert!(!numeric_fragment("-"));
        // A separator on its own is no number, but belongs to the number
        // beside it.
        assert!(!numeric_fragment(","));
        assert!(separator_fragment(","));
        assert!(inside_number("21", ","));
        assert!(inside_number(",", "847"));
        assert!(inside_number("1", "2"));
        assert!(!inside_number(".", "."));
        assert!(!inside_number("a", "1"));
        assert!(!inside_number("1", "\u{05D0}"));
    }

    #[test]
    fn glyph_run_word_gap_floor_splits_letter_gaps_from_word_gaps() {
        // Letter gaps under a tenth of an em and two word gaps of a third:
        // the floor sits between the classes.
        let gaps = [0.06, 0.08, 0.07, 0.34, 0.09, 0.06, 0.32, 0.08];
        let floor = glyph_run_word_gap_floor(&gaps).expect("two classes");
        assert!(floor > 0.09 && floor < 0.32, "{floor}");
    }

    #[test]
    fn glyph_run_word_gap_floor_holds_one_word_together() {
        // One class of gaps, all mid-word sized: the line is one word.
        let gaps = [0.06, 0.09, 0.11, 0.07, 0.10];
        assert_eq!(glyph_run_word_gap_floor(&gaps), Some(f32::INFINITY));
    }

    #[test]
    fn glyph_run_word_gap_floor_leaves_uniform_wide_gaps_to_the_thresholds() {
        // One class of gaps as wide as word spaces (one-letter words, or a
        // short run whose gaps do not tell): no floor of its own.
        let gaps = [0.24, 0.26, 0.25, 0.25];
        assert_eq!(glyph_run_word_gap_floor(&gaps), None);
        // Too few gaps to read a distribution from.
        assert_eq!(glyph_run_word_gap_floor(&[0.05, 0.3]), None);
    }

    fn glyph_run(chars: &str, start_x: f32, glyph_w: f32, gap: f32) -> Vec<TextItem> {
        let mut x = start_x;
        let mut out = Vec::new();
        for c in chars.chars() {
            out.push(make_merge_item(&c.to_string(), x, glyph_w));
            x += glyph_w + gap;
        }
        out
    }

    #[test]
    fn tracked_caps_run_collapses_to_word() {
        // Display tracking: every letter gap (0.19 em) clears the fixed
        // space threshold — without the run-local floor this reads "H O W".
        let items = glyph_run("HOW", 100.0, 10.0, 2.3);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "HOW");
    }

    #[test]
    fn tracked_run_keeps_word_gaps_bimodal() {
        // Letters at 0.19 em, word gaps at 0.42 em (below the 0.5 em item
        // break): the split must land between the modes. Needs >=4 gaps to
        // enter the bimodal tier — short runs use the strict uniform gate.
        let mut items = glyph_run("ITISOK", 100.0, 8.0, 2.3);
        for i in 2..6 {
            items[i].x += 2.8; // word gap at T|I
        }
        for i in 4..6 {
            items[i].x += 2.8; // word gap at S|O
        }
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "IT IS OK");
    }

    #[test]
    fn lowercase_spaced_singles_stay_words() {
        // "x y z" variables: same gap shape but lowercase — the short-run
        // caps requirement keeps genuine spaced singles apart.
        let items = glyph_run("xyz", 100.0, 6.0, 2.3);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "x y z");
    }

    #[test]
    fn kerned_singles_unaffected() {
        // Tiny kerning gaps never triggered spaces before and still don't.
        let items = glyph_run("WORD", 100.0, 8.0, 0.3);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "WORD");
    }

    #[test]
    fn long_lowercase_spaced_singles_keep_boundaries() {
        // Review: a 5+ single-letter lowercase list has the tracked gap
        // shape at any length — the convention gate must protect it in
        // the >=4-gap tier too.
        let items = glyph_run("abcde", 100.0, 6.0, 2.3);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "a b c d e");
    }

    #[test]
    fn han_run_with_nonuniform_gaps_never_gains_spaces() {
        // Review: a bimodal gap distribution (justification, punctuation
        // spacing) must not manufacture word boundaries in Han text.
        let mut items = glyph_run("北京时事快报", 100.0, 12.0, 1.4);
        for item in items.iter_mut().skip(3) {
            item.x += 3.0; // wide gap after the third glyph
        }
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "北京时事快报");
    }

    #[test]
    fn uppercase_leading_spaced_singles_keep_boundaries() {
        // "A b c d e" is indistinguishable from a title-case tracked word
        // without reliable tracking metadata, so preserve its boundaries.
        let items = glyph_run("Abcde", 100.0, 7.0, 2.3);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "A b c d e");
    }

    #[test]
    fn cjk_glyph_run_collapses_without_spaces() {
        // CJK sets one glyph per item with loose gaps; CJK uses no spaces,
        // and the non-alphabetic run passes the caps gate.
        let items = glyph_run("北京时事", 100.0, 12.0, 1.4);
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "北京时事");
    }

    fn make_merge_item(text: &str, x: f32, width: f32) -> TextItem {
        TextItem {
            text: text.into(),
            x,
            y: 700.0,
            width,
            height: 12.0,
            font: "F1".into(),
            font_tag: String::new(),
            legacy_symbol_rewrite: false,
            font_size: 12.0,
            page: 1,
            is_bold: false,
            is_italic: false,
            font_weight: None,
            bold_source: None,
            fixed_pitch: None,
            is_underline: false,
            is_strikeout: false,
            rotation: 0.0,
            advance_known: true,
            item_type: ItemType::Text,
            mcid: None,
            baseline_shift: 0.0,
        }
    }

    #[test]
    fn explicit_trailing_space_is_not_doubled_across_a_word_gap() {
        // "for " already carries its space run; the 4pt gap (0.33 em) that
        // run left clears the word threshold but must not add a second one.
        let items = vec![
            make_merge_item("for ", 100.0, 21.6),
            make_merge_item("the", 125.6, 21.6),
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "for the");
    }

    fn with_mcid(mut item: TextItem) -> TextItem {
        item.mcid = Some(1);
        item
    }

    fn make_line(x1: f32, y1: f32, x2: f32, y2: f32) -> PdfLine {
        PdfLine {
            x1,
            y1,
            x2,
            y2,
            page: 1,
        }
    }

    #[test]
    fn trace_text_preview_truncates_on_char_boundary() {
        let text = format!("{}{}tail", "a".repeat(79), '\u{FFFD}');
        let preview = trace_text_preview(&text, 80);

        assert_eq!(preview.chars().count(), 80);
        assert!(text.is_char_boundary(preview.len()));
        assert!(preview.ends_with('\u{FFFD}'));
    }

    #[test]
    fn merge_items_breaks_at_style_boundaries() {
        // A styled run adjacent to plain text must stay a separate item —
        // merging would erase the flags (italic) or stretch the span
        // (underline) before markdown emission sees them.
        let mut italic = make_merge_item("emphasis", 150.0, 40.0);
        italic.is_italic = true;
        let mut underlined = make_merge_item("term", 195.0, 20.0);
        underlined.is_underline = true;
        let items = vec![
            make_merge_item("plain lead", 100.0, 48.0),
            italic,
            underlined,
            make_merge_item("plain tail", 218.0, 45.0),
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 4);
        assert!(merged[1].is_italic && !merged[1].is_underline);
        assert!(merged[2].is_underline && !merged[2].is_italic);
        assert!(!merged[3].is_underline && !merged[3].is_italic);
    }

    #[test]
    fn merge_follows_the_bold_verdict_not_the_weight_class() {
        use crate::types::BoldSource;

        // A medium-weight label leading a light paragraph: neither is bold,
        // so the runs merge into one item whatever their weight classes,
        // and the item carries its first run's weight.
        let mut label = make_merge_item("Label:", 100.0, 36.0);
        label.font_weight = Some(500);
        let mut body = make_merge_item("body", 137.2, 24.0);
        body.font_weight = Some(300);
        let mut more = make_merge_item("text", 163.6, 24.0);
        more.font_weight = Some(300);
        let items = vec![label.clone(), body.clone(), more.clone()];
        let merged = merge_text_items_with_clips(items, &[], false);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "Label: body text");
        assert_eq!(merged[0].font_weight, Some(500));

        // Once the weight class has made the label bold (the option's pass,
        // `read_bold_from_weight`), the label stays its own item, and the
        // merge still decides the word space the way an unstyled merge
        // would, so the later line assembler does not glue "Label:" onto
        // "body".
        let mut items = vec![label, body, more];
        super::content_stream::read_bold_from_weight(&mut items, 500);
        let apart = merge_text_items_with_clips(items, &[], false);
        assert_eq!(apart.len(), 2);
        assert_eq!(apart[0].text, "Label: ");
        assert!(apart[0].is_bold);
        assert_eq!(apart[0].bold_source, Some(BoldSource::WeightClass));
        assert_eq!(apart[1].text, "body text");
        assert!(!apart[1].is_bold);
        assert_eq!(apart[1].bold_source, None);

        // Runs of different weight that agree on bold merge: a 700 face
        // beside a 400 face whose name says bold are one item, which keeps
        // the first run's weight class and bold source.
        let mut heavy = make_merge_item("Heavy", 100.0, 30.0);
        heavy.font_weight = Some(700);
        let mut named = make_merge_item("named", 132.0, 30.0);
        named.font_weight = Some(400);
        named.is_bold = true;
        named.bold_source = Some(BoldSource::FontName);
        let mut items = vec![heavy, named];
        super::content_stream::read_bold_from_weight(&mut items, 600);
        let merged = merge_text_items_with_clips(items, &[], false);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "Heavy named");
        assert_eq!(merged[0].font_weight, Some(700));
        assert_eq!(merged[0].bold_source, Some(BoldSource::WeightClass));

        // Runs that know no weight merge as before.
        let unknown = vec![
            make_merge_item("no", 100.0, 12.0),
            make_merge_item("weight", 113.2, 36.0),
        ];
        assert_eq!(merge_text_items_with_clips(unknown, &[], false).len(), 1);
    }

    #[test]
    fn read_bold_from_weight_credits_the_weight_class_after_name_and_flags() {
        use crate::types::BoldSource;

        let mut named = make_merge_item("named", 0.0, 10.0);
        named.font_weight = Some(700);
        named.is_bold = true;
        named.bold_source = Some(BoldSource::FontName);
        let mut painted = make_merge_item("painted", 20.0, 10.0);
        painted.font_weight = Some(650);
        painted.is_bold = true;
        painted.bold_source = Some(BoldSource::Painted);
        let mut light = make_merge_item("light", 40.0, 10.0);
        light.font_weight = Some(300);
        let unknown = make_merge_item("unknown", 60.0, 10.0);
        let mut items = vec![named, painted, light, unknown];
        super::content_stream::read_bold_from_weight(&mut items, 600);
        // The name outranks the weight class; the weight class outranks the
        // paint, since the face itself is heavy.
        assert_eq!(items[0].bold_source, Some(BoldSource::FontName));
        assert_eq!(items[1].bold_source, Some(BoldSource::WeightClass));
        assert!(!items[2].is_bold && items[2].bold_source.is_none());
        assert!(!items[3].is_bold && items[3].bold_source.is_none());

        // The threshold is inclusive and honoured as given.
        let mut items = vec![make_merge_item("x", 0.0, 10.0)];
        items[0].font_weight = Some(500);
        super::content_stream::read_bold_from_weight(&mut items, 500);
        assert!(items[0].is_bold);
        assert_eq!(items[0].bold_source, Some(BoldSource::WeightClass));
    }

    #[test]
    fn recovered_bold_preserves_word_spacing_at_style_boundary() {
        // A 0.1-em gap is a word boundary in merging, but the later line
        // assembler joins gaps below 0.15 em. Recovering bold must not lose
        // the space that the original all-plain merge would have emitted.
        let plain = vec![
            make_merge_item("KEY", 100.0, 24.0),
            make_merge_item("Body", 125.2, 24.0),
        ];
        let original = merge_text_items(plain.clone());
        let mut styled = plain;
        styled[0].is_bold = true;
        let recovered = merge_text_items(styled);
        assert_eq!(original[0].text, "KEY Body");
        assert_eq!(recovered.len(), 2);
        assert!(recovered[0].is_bold && !recovered[1].is_bold);
        assert_eq!(recovered[0].text, "KEY ");
        assert_eq!(recovered[1].text, "Body");
        assert_eq!(
            recovered
                .iter()
                .map(|item| item.text.as_str())
                .collect::<String>(),
            original[0].text
        );
        let line = TextLine {
            items: recovered,
            y: 100.0,
            page: 1,
            adaptive_threshold: 0.1,
        };
        assert_eq!(line.text(), "KEY Body");
        assert_eq!(
            line.text_with_formatting(true, false, false),
            "**KEY** Body"
        );
    }

    #[test]
    fn recovered_bold_keeps_zero_gap_word_fragments_joined() {
        let plain = vec![
            make_merge_item("un", 100.0, 12.0),
            make_merge_item("known", 112.0, 30.0),
        ];
        let original = merge_text_items(plain.clone());
        let mut styled = plain;
        styled[0].is_bold = true;
        let recovered = merge_text_items(styled);
        assert_eq!(original[0].text, "unknown");
        assert_eq!(recovered.len(), 2);
        assert!(recovered[0].is_bold && !recovered[1].is_bold);
        assert_eq!(
            recovered
                .iter()
                .map(|item| item.text.as_str())
                .collect::<String>(),
            original[0].text
        );
        let line = TextLine {
            items: recovered,
            y: 100.0,
            page: 1,
            adaptive_threshold: 0.1,
        };
        assert_eq!(line.text(), "unknown");
        assert_eq!(line.text_with_formatting(true, false, false), "**un**known");
    }

    #[test]
    fn bold_numeric_fragments_keep_line_assembly_spacing() {
        for (parts, gap, expected) in [
            (
                vec![("0", false), (".", true), ("86", false)],
                1.2,
                "0**.**86",
            ),
            (vec![("0.", true), ("86", false)], 1.2, "**0.**86"),
            (vec![(".", true), ("42", false)], 1.2, "**.**42"),
            (
                vec![("12 ", false), (".", true), ("55", false)],
                1.2,
                "12 **.**55",
            ),
            (
                vec![("12", false), (" .", true), ("55", false)],
                1.2,
                "12 **.**55",
            ),
            (vec![("1", false), ("23", true)], 1.2, "1**23**"),
            (vec![("12", true), ("%", false)], 1.2, "**12**%"),
            (vec![("+", true), ("12", false)], 1.2, "**+**12"),
            (
                vec![("1", false), (",", true), ("25", false)],
                1.2,
                "1**,**25",
            ),
            (vec![("Done.", true), ("2", false)], 1.2, "**Done.** 2"),
            (vec![("0. ", true), ("86", false)], 1.2, "**0.** 86"),
            (vec![("0.", true), ("86", false)], 4.8, "**0.** 86"),
            (vec![("KEY ", true), ("Body", false)], 1.2, "**KEY** Body"),
            (vec![("KEY", true), (" Body", false)], 1.2, "**KEY** Body"),
        ] {
            let mut x = 100.0;
            let items = parts
                .into_iter()
                .map(|(text, bold)| {
                    let width = text.len() as f32 * 6.0;
                    let mut item = make_merge_item(text, x, width);
                    item.is_bold = bold;
                    x += width + gap;
                    item
                })
                .collect();
            let line = TextLine {
                items: merge_text_items(items),
                y: 100.0,
                page: 1,
                adaptive_threshold: 0.1,
            };
            assert_eq!(line.text_with_formatting(true, false, false), expected);
            assert_eq!(line.text(), expected.replace("**", ""));
        }
    }

    #[test]
    fn non_bold_style_boundaries_keep_existing_spacing() {
        for style in 0..3 {
            let mut first = make_merge_item("KEY", 100.0, 24.0);
            match style {
                0 => first.is_italic = true,
                1 => first.is_underline = true,
                _ => first.is_strikeout = true,
            }
            let merged = merge_text_items(vec![first, make_merge_item("Body", 125.2, 24.0)]);
            assert_eq!(merged.len(), 2);
            assert_eq!(merged[0].text, "KEY");
            assert_eq!(merged[1].text, "Body");
        }
    }

    #[test]
    fn merge_items_no_space_before_period() {
        // Simulate Tc/Tw-adjusted width: "date" width is smaller than the gap
        // to "." due to negative Tc, but period should still join without space.
        let items = vec![
            make_merge_item("date", 227.25, 89.25), // end = 316.50
            make_merge_item(".", 318.00, 3.0),      // gap = 1.50 (0.125 × fs)
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "date.");
    }

    #[test]
    fn merge_items_lowercase_join_with_tc() {
        // Lowercase→lowercase junction: "deve" + "lopers" with Tc-affected gap
        // Gap of 0.12 × font_size should merge without space
        let items = vec![
            make_merge_item("deve", 100.0, 30.0),    // end = 130.0
            make_merge_item("lopers", 131.44, 40.0), // gap = 1.44 (0.12 × 12)
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "developers");
    }

    #[test]
    fn merge_items_space_at_word_boundary() {
        // Word boundary gap (> 0.13 × font_size) should insert space
        let items = vec![
            make_merge_item("hello", 100.0, 30.0),
            make_merge_item("world", 132.0, 30.0), // gap = 2.0 (0.167 × 12)
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "hello world");
    }

    #[test]
    fn merge_items_preserves_underline_from_later_fragment() {
        // Fragments with differing underline stay separate items — OR-merging
        // would stretch the eventual `<u>` span over the plain fragment.
        // Line-level text assembly still joins them without a space (tight
        // gap), so the rendered word is unchanged: `pre<u>fix</u>`.
        let mut items = vec![
            make_merge_item("pre", 100.0, 18.0),
            make_merge_item("fix", 119.0, 18.0),
        ];
        items[1].is_underline = true;

        let merged = merge_text_items(items);

        assert_eq!(merged.len(), 2);
        assert_eq!(merged[0].text, "pre");
        assert!(!merged[0].is_underline);
        assert_eq!(merged[1].text, "fix");
        assert!(merged[1].is_underline);
    }

    #[test]
    fn merge_items_preserves_stream_order_for_backtracking_heading() {
        // Some tagged PDFs emit first-letter ActualText fragments, then reset
        // the text matrix and draw the rest of the word from the line start.
        let items = vec![
            with_mcid(make_merge_item("F", 79.4, 4.5)),
            with_mcid(make_merge_item("r", 83.9, 3.3)),
            with_mcid(make_merge_item("om tables to data-", 79.4, 89.7)),
            with_mcid(make_merge_item("", 168.9, 33.9)),
            with_mcid(make_merge_item("analytics-", 168.9, 75.5)),
            with_mcid(make_merge_item("ready content", 210.5, 60.8)),
        ];

        let merged = merge_text_items(items);

        assert_eq!(merged.len(), 1);
        assert_eq!(
            merged[0].text,
            "From tables to data-analytics-ready content"
        );
    }

    #[test]
    fn merge_items_preserves_stream_order_for_reset_word_prefix() {
        let items = vec![
            with_mcid(make_merge_item("N", 68.0, 7.0)),
            with_mcid(make_merge_item("e", 75.1, 4.0)),
            with_mcid(make_merge_item("w fields created", 68.0, 82.0)),
        ];

        let merged = merge_text_items(items);

        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "New fields created");
    }

    #[test]
    fn merge_items_uses_x_order_for_untagged_backtracking_text() {
        let items = vec![
            make_merge_item("N", 68.0, 7.0),
            make_merge_item("e", 75.1, 4.0),
            make_merge_item("w fields created", 68.2, 82.0),
        ];

        let merged = merge_text_items(items);

        let texts: Vec<_> = merged.iter().map(|item| item.text.as_str()).collect();
        assert_eq!(texts, vec!["N", "w fields created", "e"]);
    }

    #[test]
    fn merge_items_preserves_bullet_stream_order_with_backtracking() {
        let items = vec![
            with_mcid(make_merge_item("•", 79.4, 5.0)),
            with_mcid(make_merge_item("The MS", 91.0, 32.6)),
            with_mcid(make_merge_item("A LoS project", 84.4, 70.0)),
        ];

        let merged = merge_text_items(items);

        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "• The MSA LoS project");
    }

    #[test]
    fn merge_items_keeps_normal_bullet_gap_limit_without_stream_order() {
        let items = vec![
            make_merge_item("•", 79.4, 5.0),
            make_merge_item("Distant item", 91.0, 60.0),
        ];

        let merged = merge_text_items(items);

        let texts: Vec<_> = merged.iter().map(|item| item.text.as_str()).collect();
        assert_eq!(texts, vec!["•", "Distant item"]);
    }

    #[test]
    fn suppress_table_underlines_clears_line_detected_table_items() {
        let mut items = vec![
            make_merge_item("H1", 125.0, 20.0),
            make_merge_item("H2", 225.0, 20.0),
            make_merge_item("A", 125.0, 20.0),
            make_merge_item("B", 225.0, 20.0),
        ];
        items[0].y = 490.0;
        items[1].y = 490.0;
        items[2].y = 470.0;
        items[3].y = 470.0;
        for item in &mut items {
            item.is_underline = true;
            item.is_strikeout = true;
        }
        let lines = vec![
            make_line(100.0, 500.0, 300.0, 500.0),
            make_line(100.0, 480.0, 300.0, 480.0),
            make_line(100.0, 460.0, 300.0, 460.0),
            make_line(100.0, 460.0, 100.0, 500.0),
            make_line(200.0, 460.0, 200.0, 500.0),
            make_line(300.0, 460.0, 300.0, 500.0),
        ];

        suppress_table_underlines(&mut items, &[], &lines, 1);

        assert!(items.iter().all(|item| !item.is_underline));
        assert!(items.iter().all(|item| !item.is_strikeout));
    }

    #[test]
    fn test_group_into_lines() {
        let items = vec![
            TextItem {
                text: "Hello".into(),
                x: 100.0,
                y: 700.0,
                width: 50.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "World".into(),
                x: 160.0,
                y: 700.0,
                width: 50.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "Next line".into(),
                x: 100.0,
                y: 680.0,
                width: 80.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].text(), "Hello World");
        assert_eq!(lines[1].text(), "Next line");
    }

    #[test]
    fn preserving_all_text_keeps_numeric_page_footer() {
        let mut page_number = make_merge_item("42", 100.0, 12.0);
        page_number.y = 50.0;

        assert!(group_into_lines(vec![page_number.clone()]).is_empty());

        let lines = group_into_lines_preserving_all_text(vec![page_number]);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "42");
    }

    #[test]
    fn inline_numeric_run_near_page_edge_is_not_removed() {
        let mut items = vec![
            make_merge_item("Total", 100.0, 30.0),
            make_merge_item("730", 136.0, 18.0),
            make_merge_item("seats", 160.0, 30.0),
        ];
        for item in &mut items {
            item.y = 780.0;
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Total 730 seats");
    }

    #[test]
    fn numeric_page_footer_separated_from_label_is_removed() {
        let mut page_number = make_merge_item("42", 25.0, 12.0);
        page_number.y = 50.0;
        let mut footer_label = make_merge_item("DOCUMENT FOOTER", 60.0, 100.0);
        footer_label.y = 50.0;

        let lines = group_into_lines(vec![page_number, footer_label]);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "DOCUMENT FOOTER");
    }

    #[test]
    fn decorative_marker_does_not_contextualize_numeric_page_footer() {
        let mut marker = make_merge_item("•", 19.0, 6.0);
        marker.y = 30.0;
        let mut page_number = make_merge_item("42", 37.0, 10.0);
        page_number.y = 30.0;
        let mut footer_label = make_merge_item("Company report footer", 68.0, 120.0);
        footer_label.y = 30.0;

        let lines = group_into_lines(vec![marker, page_number, footer_label]);

        assert!(lines.iter().all(|line| !line.text().contains("42")));
        assert!(lines
            .iter()
            .any(|line| line.text().contains("Company report footer")));
    }

    #[test]
    fn labeled_page_number_is_removed_in_a_short_document() {
        let mut label = make_merge_item("Page", 25.0, 28.0);
        label.y = 50.0;
        let mut page_number = make_merge_item("42", 57.0, 12.0);
        page_number.y = 50.0;

        let lines = group_into_lines(vec![label, page_number]);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Page");
    }

    #[test]
    fn labeled_page_number_with_running_header_suffix_is_removed() {
        let mut items = vec![
            make_merge_item("Page", 25.0, 28.0),
            make_merge_item("42", 57.0, 12.0),
            make_merge_item("of", 73.0, 12.0),
            make_merge_item("100", 89.0, 18.0),
            make_merge_item("Report header", 111.0, 78.0),
        ];
        for item in &mut items {
            item.y = 50.0;
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Report header");
    }

    #[test]
    fn page_of_total_expression_is_removed_without_leaving_fragments() {
        let mut items = vec![
            make_merge_item("Page", 482.0, 27.0),
            make_merge_item("1", 513.0, 6.0),
            make_merge_item("of", 523.0, 10.0),
            make_merge_item("15", 537.0, 12.0),
        ];
        for item in &mut items {
            item.y = 46.0;
        }

        let lines = group_into_lines(items);

        assert!(lines.is_empty());
    }

    #[test]
    fn document_folio_filter_survives_per_page_layout_splitting() {
        let mut items = Vec::new();
        for (page, value) in [(1, "42"), (2, "43"), (3, "44")] {
            let mut label = make_merge_item("Page", 25.0, 28.0);
            label.page = page;
            label.y = 50.0;
            let mut page_number = make_merge_item(value, 57.0, 12.0);
            page_number.page = page;
            page_number.y = 50.0;
            items.extend([label, page_number]);
        }

        let filtered = filter_markdown_page_numbers(items, 3);
        assert!(filtered
            .iter()
            .all(|item| !matches!(item.text.as_str(), "42" | "43" | "44")));
        let mut lines = Vec::new();
        for page in 1..=3 {
            let page_items = filtered
                .iter()
                .filter(|item| item.page == page)
                .cloned()
                .collect();
            lines.extend(
                group_prefiltered_items_into_lines_with_thresholds_and_charts(
                    page_items,
                    &HashMap::new(),
                    &HashSet::new(),
                    &HashMap::new(),
                ),
            );
        }

        assert_eq!(lines.len(), 3);
        assert!(lines.iter().all(|line| line.text() == "Page"));
    }

    #[test]
    fn numeric_only_page_edge_runs_do_not_contextualize_folios() {
        let mut page_number = make_merge_item("42", 25.0, 12.0);
        page_number.y = 50.0;
        let mut long_number = make_merge_item("12345", 43.0, 30.0);
        long_number.y = 50.0;

        let lines = group_into_lines(vec![page_number, long_number]);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "12345");
    }

    #[test]
    fn structured_and_dense_numeric_page_edge_runs_are_preserved() {
        let mut list_marker = make_merge_item("11)", 25.0, 18.0);
        list_marker.y = 50.0;
        let mut chapter = make_merge_item("13", 47.0, 12.0);
        chapter.y = 50.0;

        let mut isbn_prefix = make_merge_item("9", 25.0, 6.0);
        isbn_prefix.page = 2;
        isbn_prefix.y = 50.0;
        let mut isbn_mid = make_merge_item("780113", 35.0, 36.0);
        isbn_mid.page = 2;
        isbn_mid.y = 50.0;
        let mut isbn_end = make_merge_item("227426", 75.0, 36.0);
        isbn_end.page = 2;
        isbn_end.y = 50.0;

        let lines = group_into_lines(vec![list_marker, chapter, isbn_prefix, isbn_mid, isbn_end]);

        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].text(), "11) 13");
        assert_eq!(lines[1].text(), "9 780113 227426");
    }

    #[test]
    fn incrementing_numeric_body_column_is_not_treated_as_a_folio() {
        let mut items = Vec::new();
        for (page, value) in [(1, "13"), (2, "14"), (3, "15")] {
            let mut row_number = make_merge_item(value, 72.0, 12.0);
            row_number.page = page;
            row_number.y = 730.0;
            let mut name = make_merge_item("Person", 90.0, 42.0);
            name.page = page;
            name.y = 730.0;
            items.extend([row_number, name]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 3);
        assert_eq!(lines[0].text(), "13 Person");
        assert_eq!(lines[1].text(), "14 Person");
        assert_eq!(lines[2].text(), "15 Person");
    }

    #[test]
    fn advancing_number_in_repeated_deep_margin_footer_is_removed() {
        let mut items = Vec::new();
        for (page, value) in [(1, "2"), (2, "4"), (3, "6"), (4, "8")] {
            let mut page_number = make_merge_item(value, 25.0, 12.0);
            page_number.page = page;
            page_number.y = 30.0;
            let mut footer = make_merge_item("Company report footer", 41.0, 120.0);
            footer.page = page;
            footer.y = 30.0;
            items.extend([page_number, footer]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 4);
        assert!(lines
            .iter()
            .all(|line| line.text() == "Company report footer"));
    }

    #[test]
    fn repeated_substantive_page_number_prose_is_preserved() {
        let mut items = Vec::new();
        for (page, value) in [(1, "42"), (2, "43"), (3, "44"), (4, "45")] {
            let mut page_label = make_merge_item("Page", 25.0, 28.0);
            page_label.page = page;
            page_label.y = 30.0;
            let mut number = make_merge_item(value, 57.0, 12.0);
            number.page = page;
            number.y = 30.0;
            let mut explanation = make_merge_item("explains the result", 73.0, 108.0);
            explanation.page = page;
            explanation.y = 30.0;
            items.extend([page_label, number, explanation]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 4);
        for (line, value) in lines.iter().zip(["42", "43", "44", "45"]) {
            assert_eq!(line.text(), format!("Page {value} explains the result"));
        }
    }

    #[test]
    fn numeric_candidates_do_not_bridge_lexical_context() {
        let mut report = make_merge_item("Report", 25.0, 40.0);
        report.y = 30.0;
        let mut year = make_merge_item("2026", 69.0, 24.0);
        year.y = 30.0;
        let mut folio = make_merge_item("42", 97.0, 12.0);
        folio.y = 30.0;

        let lines = group_into_lines(vec![report, year, folio]);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Report 2026");
    }

    #[test]
    fn centered_folio_delimiters_are_removed_with_the_number() {
        let mut left = make_merge_item("-", 270.0, 6.0);
        left.y = 30.0;
        let mut number = make_merge_item("42", 280.0, 12.0);
        number.y = 30.0;
        let mut right = make_merge_item("-", 296.0, 6.0);
        right.y = 30.0;

        let lines = group_into_lines(vec![left, number, right]);

        assert!(lines.is_empty());
    }

    #[test]
    fn centered_delimiters_inside_substantive_text_are_preserved() {
        let mut items = vec![
            make_merge_item("Result", 240.0, 36.0),
            make_merge_item("-", 280.0, 6.0),
            make_merge_item("42", 290.0, 12.0),
            make_merge_item("-", 306.0, 6.0),
            make_merge_item("approved", 316.0, 48.0),
        ];
        for item in &mut items {
            item.y = 30.0;
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Result-42-approved");
    }

    #[test]
    fn changing_year_in_repeated_deep_margin_header_is_preserved() {
        let mut items = Vec::new();
        for (page, year) in [(1, "2020"), (2, "2021"), (3, "2022"), (4, "2023")] {
            let mut year = make_merge_item(year, 25.0, 24.0);
            year.page = page;
            year.y = 780.0;
            let mut header = make_merge_item("Annual report", 53.0, 78.0);
            header.page = page;
            header.y = 780.0;
            items.extend([year, header]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 4);
        assert_eq!(lines[0].text(), "2020 Annual report");
        assert_eq!(lines[3].text(), "2023 Annual report");
    }

    #[test]
    fn sparse_repeated_margin_numbers_do_not_meet_the_folio_evidence_floor() {
        let mut items = Vec::new();
        for page in 1..=4 {
            if page <= 2 {
                let value = if page == 1 { "2" } else { "4" };
                let mut number = make_merge_item(value, 25.0, 12.0);
                number.page = page;
                number.y = 30.0;
                let mut footer = make_merge_item("Company report footer", 41.0, 120.0);
                footer.page = page;
                footer.y = 30.0;
                items.extend([number, footer]);
            } else {
                let mut body = make_merge_item("Body text", 72.0, 54.0);
                body.page = page;
                body.y = 400.0;
                items.push(body);
            }
        }

        let lines = group_into_lines(items);

        assert!(lines
            .iter()
            .any(|line| line.text() == "2 Company report footer"));
        assert!(lines
            .iter()
            .any(|line| line.text() == "4 Company report footer"));
    }

    #[test]
    fn sparse_document_pages_count_toward_repeated_folio_coverage() {
        let mut items = Vec::new();
        for (page, value) in [(1, "1"), (10, "10"), (19, "19"), (28, "28")] {
            let mut number = make_merge_item(value, 25.0, 12.0);
            number.page = page;
            number.y = 30.0;
            let mut footer = make_merge_item("Company report footer", 41.0, 120.0);
            footer.page = page;
            footer.y = 30.0;
            items.extend([number, footer]);
        }

        let lines = group_into_lines(items);

        assert!(lines
            .iter()
            .any(|line| line.text() == "1 Company report footer"));
        assert!(lines
            .iter()
            .any(|line| line.text() == "28 Company report footer"));
    }

    #[test]
    fn trailing_blank_pages_count_toward_repeated_folio_coverage() {
        let mut items = Vec::new();
        for (page, value) in [(1, "1"), (2, "2"), (3, "3"), (4, "4")] {
            let mut number = make_merge_item(value, 25.0, 12.0);
            number.page = page;
            number.y = 30.0;
            let mut footer = make_merge_item("Company report footer", 41.0, 120.0);
            footer.page = page;
            footer.y = 30.0;
            items.extend([number, footer]);
        }

        let filtered = filter_markdown_page_numbers(items, 20);

        assert!(filtered.iter().any(|item| item.text == "1"));
        assert!(filtered.iter().any(|item| item.text == "4"));
    }

    #[test]
    fn prefiltered_contextual_number_survives_layout_partitioning() {
        let mut items = vec![
            make_merge_item("Total", 100.0, 30.0),
            make_merge_item("730", 136.0, 18.0),
            make_merge_item("seats", 160.0, 30.0),
        ];
        for item in &mut items {
            item.y = 780.0;
        }

        let filtered = filter_markdown_page_numbers(items, 1);
        let partitioned_number: Vec<TextItem> = filtered
            .into_iter()
            .filter(|item| item.text == "730")
            .collect();
        let lines = group_prefiltered_items_into_lines_with_thresholds_and_charts(
            partitioned_number,
            &HashMap::new(),
            &HashSet::new(),
            &HashMap::new(),
        );

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "730");
    }

    #[test]
    fn numeric_only_partition_does_not_define_columns() {
        let mut items = Vec::new();
        for row in 0..20 {
            let y = 90.0 - row as f32 * 4.0;
            let mut left = make_merge_item(&(row + 1).to_string(), 50.0, 20.0);
            left.y = y;
            let mut right = make_merge_item(&(row + 101).to_string(), 350.0, 20.0);
            right.y = y;
            items.extend([left, right]);
        }
        assert_eq!(detect_columns(&items, 1, false).len(), 2);

        let lines = group_prefiltered_items_into_lines_with_thresholds_and_charts(
            items,
            &HashMap::new(),
            &HashSet::new(),
            &HashMap::new(),
        );

        assert_eq!(lines.len(), 20);
        assert!(lines.iter().all(|line| line.items.len() == 2));
    }

    #[test]
    fn separated_content_is_not_treated_as_a_spread_folio_pair() {
        let mut value = make_merge_item("12", 100.0, 12.0);
        value.y = 30.0;
        let mut label = make_merge_item("Total", 116.0, 30.0);
        label.y = 30.0;
        let mut unrelated_number = make_merge_item("13", 300.0, 12.0);
        unrelated_number.y = 30.0;

        let lines = group_into_lines(vec![value, label, unrelated_number]);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "12 Total");
    }

    #[test]
    fn repeated_folio_uses_the_full_page_edge_band() {
        let mut items = Vec::new();
        for (page, value) in [(1, "2"), (2, "4"), (3, "6"), (4, "8")] {
            let mut page_number = make_merge_item(value, 25.0, 12.0);
            page_number.page = page;
            page_number.y = 80.0;
            let mut footer = make_merge_item("Company report footer", 41.0, 120.0);
            footer.page = page;
            footer.y = 80.0;
            items.extend([page_number, footer]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 4);
        assert!(lines
            .iter()
            .all(|line| line.text() == "Company report footer"));
    }

    #[test]
    fn contextual_folio_on_facing_page_spread_is_removed() {
        let mut marker = make_merge_item("•", 19.0, 6.0);
        marker.y = 30.0;
        let mut left_folio = make_merge_item("326", 35.0, 17.0);
        left_folio.y = 30.0;
        let mut footer = make_merge_item("Company report footer", 61.0, 120.0);
        footer.y = 30.0;
        let mut right_folio = make_merge_item("327", 1148.0, 17.0);
        right_folio.y = 30.0;

        let lines = group_into_lines(vec![marker, left_folio, footer, right_folio]);

        assert!(lines
            .iter()
            .all(|line| !line.text().contains("326") && !line.text().contains("327")));
        assert!(lines
            .iter()
            .any(|line| line.text().contains("Company report footer")));
    }

    #[test]
    fn contextual_folios_alternating_across_pages_are_removed() {
        let headers = [
            "Letter to shareholders",
            "Corporate governance report",
            "Business environment overview",
            "Consolidated financial statements",
        ];
        let mut items = Vec::new();
        for page in 1..=8 {
            let mut body = make_merge_item("Body text", 50.0, 500.0);
            body.page = page;
            body.y = 400.0;
            items.push(body);

            let mut folio = make_merge_item(&(page + 22).to_string(), 0.0, 14.0);
            folio.page = page;
            folio.y = 780.0;
            if page % 2 == 0 {
                folio.x = 50.0;
                items.push(folio);
            } else {
                let mut header = make_merge_item(headers[(page / 2) as usize], 350.0, 180.0);
                header.page = page;
                header.y = 780.0;
                folio.x = 536.0;
                items.extend([header, folio]);
            }
        }

        let filtered = filter_markdown_page_numbers(items, 8);

        assert!(filtered.iter().all(|item| {
            !matches!(
                item.text.as_str(),
                "23" | "24" | "25" | "26" | "27" | "28" | "29" | "30"
            )
        }));
        assert!(headers
            .iter()
            .all(|header| filtered.iter().any(|item| item.text == *header)));
    }

    #[test]
    fn one_isolated_neighbor_does_not_remove_contextual_number() {
        let mut body_one = make_merge_item("Body text", 50.0, 500.0);
        body_one.y = 400.0;
        let mut label = make_merge_item("Report", 450.0, 70.0);
        label.y = 780.0;
        let mut contextual = make_merge_item("1", 526.0, 7.0);
        contextual.y = 780.0;

        let mut body_two = body_one.clone();
        body_two.page = 2;
        let mut isolated = make_merge_item("2", 50.0, 7.0);
        isolated.page = 2;
        isolated.y = 780.0;

        let filtered =
            filter_markdown_page_numbers(vec![body_one, label, contextual, body_two, isolated], 2);

        assert!(filtered.iter().any(|item| item.text == "Report"));
        assert!(filtered.iter().any(|item| item.text == "1"));
        assert!(filtered.iter().all(|item| item.text != "2"));
    }

    #[test]
    fn narrow_content_span_does_not_establish_adjacent_page_edges() {
        let mut body_one = make_merge_item("Body text", 100.0, 120.0);
        body_one.y = 400.0;
        let mut label = make_merge_item("Report", 170.0, 60.0);
        label.y = 780.0;
        let mut contextual = make_merge_item("1", 235.0, 7.0);
        contextual.y = 780.0;

        let mut body_two = body_one.clone();
        body_two.page = 2;
        let mut isolated_two = make_merge_item("2", 100.0, 7.0);
        isolated_two.page = 2;
        isolated_two.y = 780.0;

        let mut body_four = body_one.clone();
        body_four.page = 4;
        let mut isolated_four = make_merge_item("4", 100.0, 7.0);
        isolated_four.page = 4;
        isolated_four.y = 780.0;

        let filtered = filter_markdown_page_numbers(
            vec![
                body_one,
                label,
                contextual,
                body_two,
                isolated_two,
                body_four,
                isolated_four,
            ],
            4,
        );

        assert!(filtered.iter().any(|item| item.text == "Report"));
        assert!(filtered.iter().any(|item| item.text == "1"));
    }

    #[test]
    fn same_edge_number_on_an_adjacent_page_is_not_folio_evidence() {
        let mut body_one = make_merge_item("Body text", 50.0, 500.0);
        body_one.y = 400.0;
        let mut isolated = make_merge_item("42", 50.0, 14.0);
        isolated.y = 780.0;

        let mut body_two = body_one.clone();
        body_two.page = 2;
        let mut contextual = make_merge_item("43", 50.0, 14.0);
        contextual.page = 2;
        contextual.y = 780.0;
        let mut label = make_merge_item("cases reviewed", 70.0, 90.0);
        label.page = 2;
        label.y = 780.0;

        let filtered =
            filter_markdown_page_numbers(vec![body_one, isolated, body_two, contextual, label], 2);

        assert!(filtered.iter().any(|item| item.text == "43"));
        assert!(filtered.iter().any(|item| item.text == "cases reviewed"));
    }

    #[test]
    fn constant_number_in_repeated_deep_margin_header_is_preserved() {
        let mut items = Vec::new();
        for page in 1..=4 {
            let mut year = make_merge_item("2026", 25.0, 24.0);
            year.page = page;
            year.y = 780.0;
            let mut header = make_merge_item("Annual report", 53.0, 78.0);
            header.page = page;
            header.y = 780.0;
            items.extend([year, header]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 4);
        assert!(lines.iter().all(|line| line.text() == "2026 Annual report"));
    }

    #[test]
    fn page_number_prefix_does_not_remove_substantive_text_during_layout() {
        let mut items = vec![
            make_merge_item("Page", 25.0, 28.0),
            make_merge_item("42", 57.0, 12.0),
            make_merge_item("explains", 73.0, 44.0),
            make_merge_item("the result", 121.0, 55.0),
        ];
        for item in &mut items {
            item.y = 50.0;
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Page 42 explains the result");
    }

    #[test]
    fn repeated_page_number_prefix_with_substantive_text_is_preserved_during_layout() {
        let mut items = Vec::new();
        for (page, value, chapter) in [(1, "42", "Chapter 1"), (2, "43", "Chapter 2")] {
            let mut label = make_merge_item("Page", 25.0, 28.0);
            label.page = page;
            label.y = 50.0;
            let mut page_number = make_merge_item(value, 57.0, 12.0);
            page_number.page = page;
            page_number.y = 50.0;
            let mut suffix = make_merge_item(chapter, 73.0, 58.0);
            suffix.page = page;
            suffix.y = 50.0;
            items.extend([label, page_number, suffix]);
        }

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 2);
        assert_eq!(lines[0].text(), "Page 42 Chapter 1");
        assert_eq!(lines[1].text(), "Page 43 Chapter 2");
    }

    #[test]
    fn page_number_phrase_in_the_page_body_is_preserved() {
        let items = vec![
            make_merge_item("Page", 25.0, 28.0),
            make_merge_item("42", 57.0, 12.0),
        ];

        let lines = group_into_lines(items);

        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Page 42");
    }

    #[test]
    fn short_numeric_context_near_page_edge_is_preserved() {
        let mut chapter = make_merge_item("Chapter", 100.0, 45.0);
        chapter.y = 760.0;
        let mut chapter_number = make_merge_item("1", 151.0, 6.0);
        chapter_number.y = 760.0;

        let chapter_lines = group_into_lines(vec![chapter, chapter_number]);
        assert_eq!(chapter_lines.len(), 1);
        assert_eq!(chapter_lines[0].text(), "Chapter 1");

        let mut year = make_merge_item("2026", 100.0, 24.0);
        year.y = 760.0;
        let mut report = make_merge_item("Report", 130.0, 36.0);
        report.y = 760.0;

        let report_lines = group_into_lines(vec![year, report]);
        assert_eq!(report_lines.len(), 1);
        assert_eq!(report_lines[0].text(), "2026 Report");

        let mut chapter = make_merge_item("Chapter", 100.0, 45.0);
        chapter.y = 760.0;
        let mut chapter_number = make_merge_item("1", 151.0, 6.0);
        chapter_number.y = 760.0;
        let mut edition_year = make_merge_item("2026", 163.0, 24.0);
        edition_year.y = 760.0;

        let chained_lines = group_into_lines(vec![chapter, chapter_number, edition_year]);
        assert_eq!(chained_lines.len(), 1);
        assert_eq!(chained_lines[0].text(), "Chapter 1 2026");
    }

    #[test]
    fn test_bold_italic_detection() {
        // Test bold detection
        assert!(is_bold_font("Arial-Bold"));
        assert!(is_bold_font("TimesNewRoman-Bold"));
        assert!(is_bold_font("Helvetica-BoldOblique"));
        assert!(is_bold_font("ABCDEF+ArialMT-Bold"));
        assert!(is_bold_font("NotoSans-Black"));
        assert!(is_bold_font("Roboto-SemiBold"));
        assert!(!is_bold_font("Arial"));
        assert!(!is_bold_font("TimesNewRoman-Italic"));

        // Test italic detection
        assert!(is_italic_font("Arial-Italic"));
        assert!(is_italic_font("TimesNewRoman-Italic"));
        assert!(is_italic_font("Helvetica-Oblique"));
        assert!(is_italic_font("ABCDEF+ArialMT-Italic"));
        assert!(is_italic_font("Helvetica-BoldOblique"));
        assert!(!is_italic_font("Arial"));
        assert!(!is_italic_font("TimesNewRoman-Bold"));

        // Test bold-italic detection
        assert!(is_bold_font("Arial-BoldItalic"));
        assert!(is_italic_font("Arial-BoldItalic"));
        assert!(is_bold_font("Helvetica-BoldOblique"));
        assert!(is_italic_font("Helvetica-BoldOblique"));
    }

    #[test]
    fn test_word_level_items_get_spaces() {
        // Simulate CID font per-word items touching with gap=0
        let items = vec![
            TextItem {
                text: "the".into(),
                x: 100.0,
                y: 500.0,
                width: 19.5,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "Prague".into(),
                x: 119.5,
                y: 500.0,
                width: 42.0,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "Rules".into(),
                x: 161.5,
                y: 500.0,
                width: 35.0,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "the Prague Rules");
    }

    #[test]
    fn test_single_char_items_still_join() {
        // Per-glyph positioning: single chars should join into words
        let items = vec![
            TextItem {
                text: "N".into(),
                x: 100.0,
                y: 500.0,
                width: 8.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "A".into(),
                x: 108.0,
                y: 500.0,
                width: 8.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "V".into(),
                x: 116.0,
                y: 500.0,
                width: 8.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "NAV");
    }

    #[test]
    fn test_per_glyph_word_boundaries() {
        // Per-character PDF rendering (e.g. SEC filings): each glyph is a
        // separate TextItem. Intra-word gaps are ≈ 0, word gaps ≈ 2.0 at
        // font_size 13.3 (ratio 0.15). Must detect word boundaries correctly.
        fn char_item(ch: &str, x: f32, width: f32) -> TextItem {
            TextItem {
                text: ch.into(),
                x,
                y: 719.3,
                width,
                height: 13.3,
                font: "F4".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 13.3,
                page: 1,
                is_bold: true,
                is_italic: false,
                font_weight: None,
                bold_source: Some(crate::types::BoldSource::FontName),
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            }
        }

        // "Item 2" — gap of 2.0 between 'm' and '2' at font_size 13.3
        let items = vec![
            char_item("I", 24.3, 3.1),
            char_item("t", 27.5, 2.7),
            char_item("e", 30.1, 3.5),
            char_item("m", 33.7, 6.7),
            char_item("2", 42.3, 4.0), // gap = 42.3 - 40.4 = 1.9
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "Item 2");
    }

    #[test]
    fn test_per_glyph_words_not_merged() {
        // Verify multiple words from per-character rendering get spaces between them
        fn char_item(ch: &str, x: f32, width: f32) -> TextItem {
            TextItem {
                text: ch.into(),
                x,
                y: 705.5,
                width,
                height: 13.3,
                font: "F5".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 13.3,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            }
        }

        // "of the" — three words, each with ~2px word gaps
        let items = vec![
            char_item("o", 100.0, 4.0),
            char_item("f", 104.0, 2.7),
            // word gap: 108.7 → 110.7 (gap = 4.0)
            char_item("t", 110.7, 2.7),
            char_item("h", 113.4, 4.4),
            char_item("e", 117.8, 3.5),
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "of the");
    }

    #[test]
    fn test_cjk_items_join_without_spaces() {
        // Japanese text items touching at gap=0 should join without spaces
        let items = vec![
            TextItem {
                text: "である".into(),
                x: 100.0,
                y: 500.0,
                width: 24.0,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "履行義務".into(),
                x: 124.0,
                y: 500.0,
                width: 32.0,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "を識別す".into(),
                x: 156.0,
                y: 500.0,
                width: 32.0,
                height: 12.0,
                font: "C2_0".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];

        let lines = group_into_lines(items);
        assert_eq!(lines.len(), 1);
        assert_eq!(lines[0].text(), "である履行義務を識別す");
    }

    fn make_item(text: &str, x: f32, y: f32, width: f32) -> TextItem {
        TextItem {
            text: text.into(),
            x,
            y,
            width,
            height: 12.0,
            font: "F1".into(),
            font_tag: String::new(),
            legacy_symbol_rewrite: false,
            font_size: 12.0,
            page: 1,
            is_bold: false,
            is_italic: false,
            font_weight: None,
            bold_source: None,
            fixed_pitch: None,
            is_underline: false,
            is_strikeout: false,
            rotation: 0.0,
            advance_known: true,
            item_type: ItemType::Text,
            mcid: None,
            baseline_shift: 0.0,
        }
    }

    #[test]
    fn test_detect_two_columns() {
        let mut items = Vec::new();
        // Left column at x=72, right column at x=350, gutter ~278-350
        for i in 0..30 {
            let y = 700.0 - (i as f32) * 14.0;
            items.push(make_item("Left text here", 72.0, y, 200.0));
            items.push(make_item("Right text here", 350.0, y, 200.0));
        }
        let cols = detect_columns(&items, 1, false);
        assert_eq!(cols.len(), 2, "Expected 2 columns, got {:?}", cols);
        assert!(cols[0].x_min < cols[1].x_min);
    }

    #[test]
    fn test_detect_three_columns() {
        let mut items = Vec::new();
        // Three columns at x=50, x=220, x=390
        for i in 0..30 {
            let y = 700.0 - (i as f32) * 14.0;
            items.push(make_item("Col one", 50.0, y, 140.0));
            items.push(make_item("Col two", 220.0, y, 140.0));
            items.push(make_item("Col three", 390.0, y, 140.0));
        }
        let cols = detect_columns(&items, 1, false);
        assert_eq!(cols.len(), 3, "Expected 3 columns, got {:?}", cols);
    }

    #[test]
    fn test_width_bleed_tolerance() {
        let mut items = Vec::new();
        // Two columns with a clear gutter
        for i in 0..30 {
            let y = 700.0 - (i as f32) * 14.0;
            items.push(make_item("Left text", 72.0, y, 200.0));
            items.push(make_item("Right text", 350.0, y, 200.0));
        }
        // Add a few items that bleed across the gutter
        for i in 0..3 {
            let y = 700.0 - (i as f32) * 14.0;
            items.push(make_item("wide", 72.0, y, 320.0));
        }
        let cols = detect_columns(&items, 1, false);
        assert!(
            cols.len() >= 2,
            "Width bleed should not prevent column detection, got {:?}",
            cols
        );
    }

    #[test]
    fn test_single_column_no_false_split() {
        let mut items = Vec::new();
        // Single column: items spanning full width
        for i in 0..30 {
            let y = 700.0 - (i as f32) * 14.0;
            items.push(make_item(
                "This is a full-width paragraph of text",
                72.0,
                y,
                468.0,
            ));
        }
        let cols = detect_columns(&items, 1, false);
        assert!(
            cols.len() <= 1,
            "Full-width text should not be split into columns, got {:?}",
            cols
        );
    }

    #[test]
    fn test_is_rtl_char() {
        // Hebrew alef
        assert!(is_rtl_char('\u{05D0}'));
        // Arabic alif
        assert!(is_rtl_char('\u{0627}'));
        // Latin 'A' is not RTL
        assert!(!is_rtl_char('A'));
        // CJK is not RTL
        assert!(!is_rtl_char('\u{4E00}'));
    }

    #[test]
    fn test_is_rtl_text() {
        // Majority Hebrew with digits → RTL
        assert!(is_rtl_text(["\u{05E9}\u{05DC}\u{05D5}\u{05DD} 123"].iter()));
        // Majority Latin → not RTL
        assert!(!is_rtl_text(["Hello world"].iter()));
        // Empty → not RTL
        assert!(!is_rtl_text(std::iter::empty::<&str>()));
    }

    #[test]
    fn test_is_rtl_text_weak_chars_do_not_vote() {
        // Arabic-Indic digits (U+0660-0669) are bidi class AN, not strong RTL:
        // a digits-only line must stay neutral, like ASCII-digit lines.
        assert!(!is_rtl_text(["\u{0661}\u{0662}\u{0663}"].iter()));
        // Extended Arabic-Indic digits (U+06F0-06F9) likewise
        assert!(!is_rtl_text(["\u{06F1}\u{06F2}\u{06F3}"].iter()));
        // Arabic decimal/thousands separators (U+066B/U+066C) with digits
        assert!(!is_rtl_text(
            ["\u{0661}\u{066B}\u{0662}\u{0663}\u{066C}\u{0664}"].iter()
        ));
        // Arabic letters alongside Arabic-Indic digits → still RTL
        assert!(is_rtl_text(
            ["\u{0645}\u{0631}\u{062D}\u{0628}\u{0627} \u{0661}\u{0662}"].iter()
        ));
        // Arabic letters with combining marks (NSM) → still RTL
        assert!(is_rtl_text(["\u{0645}\u{064E}\u{0631}\u{064D}"].iter()));
        // Combining marks alone are NSM, not strong RTL, even though they are
        // Other_Alphabetic: harakat-only and niqqud-only lines stay neutral
        assert!(!is_rtl_text(["\u{064E}\u{064F}\u{0650}\u{0651}"].iter()));
        assert!(!is_rtl_text(["\u{05B8}\u{05B4}\u{05BC}"].iter()));
        // Marks + Arabic-Indic digits (the full weak-only mix) → still neutral
        assert!(!is_rtl_text(["\u{0661}\u{064E}\u{0662}"].iter()));
    }

    #[test]
    fn test_rtl_line_sorting() {
        let mut items = vec![
            TextItem {
                text: "\u{05D0}".into(), // alef at x=100
                x: 100.0,
                y: 700.0,
                width: 10.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "\u{05D1}".into(), // bet at x=200 (rightmost)
                x: 200.0,
                y: 700.0,
                width: 10.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];
        sort_line_items(&mut items, false);
        // RTL: rightmost (higher X) comes first
        assert_eq!(items[0].x, 200.0);
        assert_eq!(items[1].x, 100.0);
    }

    #[test]
    fn test_ltr_unaffected() {
        let mut items = vec![
            TextItem {
                text: "Hello".into(),
                x: 100.0,
                y: 700.0,
                width: 50.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
            TextItem {
                text: "World".into(),
                x: 200.0,
                y: 700.0,
                width: 50.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page: 1,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            },
        ];
        sort_line_items(&mut items, false);
        // LTR: leftmost comes first
        assert_eq!(items[0].x, 100.0);
        assert_eq!(items[1].x, 200.0);
    }

    #[test]
    fn test_hangul_is_cjk() {
        // Hangul Jamo
        assert!(is_cjk_char('\u{1100}'));
        // Hangul Compatibility Jamo
        assert!(is_cjk_char('\u{3131}'));
        // Hangul Syllable '가'
        assert!(is_cjk_char('\u{AC00}'));
        // Latin is not CJK
        assert!(!is_cjk_char('A'));
    }

    #[test]
    fn test_newspaper_layout_detection() {
        // Two dense columns (>15 lines each) with matching Y positions → newspaper
        let make_line = |y: f32, x: f32, page: u32| TextLine {
            y,
            page,
            adaptive_threshold: 0.10,
            items: vec![TextItem {
                text: "text".into(),
                x,
                y,
                width: 100.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            }],
        };

        let col1: Vec<TextLine> = (0..20)
            .map(|i| make_line(700.0 - i as f32 * 14.0, 50.0, 1))
            .collect();
        let col2: Vec<TextLine> = (0..20)
            .map(|i| make_line(700.0 - i as f32 * 14.0, 350.0, 1))
            .collect();

        let cols = vec![
            ColumnRegion {
                x_min: 0.0,
                x_max: 300.0,
            },
            ColumnRegion {
                x_min: 300.0,
                x_max: 600.0,
            },
        ];
        assert!(is_newspaper_layout(&[col1, col2], &cols));
    }

    #[test]
    fn test_newspaper_layout_misaligned_baselines() {
        // Two dense balanced columns with non-aligned Y positions (e.g. government gazettes
        // where columns are independently typeset) → should still be newspaper
        let make_line = |y: f32, x: f32, page: u32| TextLine {
            y,
            page,
            adaptive_threshold: 0.10,
            items: vec![TextItem {
                text: "text".into(),
                x,
                y,
                width: 100.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            }],
        };

        // Col1 starts at Y=700, col2 starts at Y=685 (15pt offset — no Y-collision)
        let col1: Vec<TextLine> = (0..20)
            .map(|i| make_line(700.0 - i as f32 * 14.0, 50.0, 1))
            .collect();
        let col2: Vec<TextLine> = (0..20)
            .map(|i| make_line(685.0 - i as f32 * 14.0, 350.0, 1))
            .collect();

        let cols = vec![
            ColumnRegion {
                x_min: 0.0,
                x_max: 300.0,
            },
            ColumnRegion {
                x_min: 300.0,
                x_max: 600.0,
            },
        ];
        assert!(is_newspaper_layout(&[col1, col2], &cols));
    }

    #[test]
    fn test_tabular_layout_detection() {
        // Sparse columns (<15 lines) → tabular, not newspaper
        let make_line = |y: f32, x: f32, page: u32| TextLine {
            y,
            page,
            adaptive_threshold: 0.10,
            items: vec![TextItem {
                text: "text".into(),
                x,
                y,
                width: 100.0,
                height: 12.0,
                font: "F1".into(),
                font_tag: String::new(),
                legacy_symbol_rewrite: false,
                font_size: 12.0,
                page,
                is_bold: false,
                is_italic: false,
                font_weight: None,
                bold_source: None,
                fixed_pitch: None,
                is_underline: false,
                is_strikeout: false,
                rotation: 0.0,
                advance_known: true,
                item_type: ItemType::Text,
                mcid: None,
                baseline_shift: 0.0,
            }],
        };

        let col1: Vec<TextLine> = (0..5)
            .map(|i| make_line(700.0 - i as f32 * 14.0, 50.0, 1))
            .collect();
        let col2: Vec<TextLine> = (0..5)
            .map(|i| make_line(700.0 - i as f32 * 14.0, 350.0, 1))
            .collect();

        let cols = vec![
            ColumnRegion {
                x_min: 0.0,
                x_max: 300.0,
            },
            ColumnRegion {
                x_min: 300.0,
                x_max: 600.0,
            },
        ];
        assert!(!is_newspaper_layout(&[col1, col2], &cols));
    }

    fn make_item_fs(text: &str, x: f32, y: f32, width: f32, font_size: f32) -> TextItem {
        TextItem {
            text: text.into(),
            x,
            y,
            width,
            height: font_size,
            font: "F1".into(),
            font_tag: String::new(),
            legacy_symbol_rewrite: false,
            font_size,
            page: 1,
            is_bold: false,
            is_italic: false,
            font_weight: None,
            bold_source: None,
            fixed_pitch: None,
            is_underline: false,
            is_strikeout: false,
            rotation: 0.0,
            advance_known: true,
            item_type: ItemType::Text,
            mcid: None,
            baseline_shift: 0.0,
        }
    }

    #[test]
    fn stacked_fraction_glyphs_are_not_merged_into_one_run() {
        // "1" over "3" (a TeX case fraction): same x, baselines 8pt apart,
        // both inside the body line's 5pt band. They are two items; the
        // script detector then sees a superscript and a subscript.
        let items = vec![
            make_item_fs("about 3", 91.9, 511.3, 103.2, 10.0),
            make_item_fs("1", 196.3, 515.2, 3.7, 7.4),
            make_item_fs("3", 196.3, 507.3, 3.7, 7.4),
            make_item_fs("bits", 201.5, 511.3, 18.0, 10.0),
        ];
        let merged = merge_text_items(items);
        let texts: Vec<&str> = merged.iter().map(|i| i.text.as_str()).collect();
        assert!(texts.contains(&"1") && texts.contains(&"3"), "{texts:?}");
        // Side-by-side same-size raised symbol still joins its word.
        let items = vec![
            make_item_fs("Freon", 100.0, 500.0, 26.0, 10.0),
            make_item_fs("®", 126.0, 502.0, 6.0, 10.0),
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "Freon®");
        // Stacked LETTERS in the same band (a rotated label beside body
        // text) keep merging as before — only digit pairs are fractions.
        let items = vec![
            make_item_fs("x", 91.9, 511.3, 5.0, 10.0),
            make_item_fs("a", 96.9, 515.2, 3.7, 7.4),
            make_item_fs("r", 96.9, 507.3, 3.7, 7.4),
        ];
        let merged = merge_text_items(items);
        assert!(
            merged.iter().any(|i| i.text.contains("ar")),
            "{:?}",
            merged.iter().map(|i| i.text.as_str()).collect::<Vec<_>>()
        );
    }

    /// Small caps as typesetters emit them: a full-size capital at 9.98pt
    /// immediately followed by shrunken capitals at 6.74pt, touching.
    /// Modelled on `199AD3d.pdf` p.5 ("ROLANDO T. ACOSTA, P.J.").
    #[test]
    fn small_caps_run_merges_into_one_word() {
        let items = vec![
            make_item_fs("R", 144.36, 581.84, 7.20, 9.98),
            make_item_fs("OLANDO", 151.56, 581.84, 30.56, 6.74),
            make_item_fs("T. A", 185.45, 581.84, 17.58, 9.98),
            make_item_fs("COSTA", 203.94, 581.84, 23.15, 6.74),
            make_item_fs(", P.J.", 227.09, 581.84, 22.56, 9.98),
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1, "got {:?}", merged);
        assert_eq!(merged[0].text, "ROLANDO T. ACOSTA, P.J.");
    }

    /// The full two-column row: both names must merge independently and the
    /// 72pt column gap between them must survive as an item boundary.
    #[test]
    fn small_caps_merge_does_not_swallow_a_second_column() {
        let items = vec![
            // Column 1: "ROLANDO T. ACOSTA, P.J." ending at x=249.65
            make_item_fs("R", 144.36, 581.84, 7.20, 9.98),
            make_item_fs("OLANDO", 151.56, 581.84, 30.56, 6.74),
            make_item_fs("T. A", 185.45, 581.84, 17.58, 9.98),
            make_item_fs("COSTA", 203.94, 581.84, 23.15, 6.74),
            make_item_fs(", P.J.", 227.09, 581.84, 22.56, 9.98),
            // Column 2 starts at x=321.96 — a 72pt gap.
            make_item_fs("A", 321.96, 581.84, 7.20, 9.98),
            make_item_fs("NIL", 329.17, 581.84, 12.72, 6.74),
            make_item_fs("C. S", 345.04, 581.84, 19.59, 9.98),
            make_item_fs("INGH", 364.62, 581.84, 19.08, 6.74),
        ];
        let merged = merge_text_items(items);
        let texts: Vec<&str> = merged.iter().map(|i| i.text.as_str()).collect();
        assert_eq!(
            texts,
            vec!["ROLANDO T. ACOSTA, P.J.", "ANIL C. SINGH"],
            "column gap should keep the two names apart"
        );
    }

    #[test]
    fn small_caps_merge_keeps_word_space_between_same_size_capitals() {
        // Two uppercase words at sizes the merge band already accepts (9.98 and
        // 9.0, a 10% drop) separated by a real word gap. The small-caps path
        // must not claim this junction and swallow the space.
        let items = vec![
            make_item_fs("SEE", 100.0, 500.0, 18.0, 9.98),
            make_item_fs("ALSO", 119.2, 500.0, 24.0, 9.0),
        ];
        let merged = merge_text_items(items);
        assert_eq!(merged.len(), 1, "got {:?}", merged);
        assert_eq!(merged[0].text, "SEE ALSO");
    }

    #[test]
    fn trailing_digit_is_not_a_capital_awaiting_small_caps() {
        // "...MAZZARELLI1" ends in a footnote marker; the backward search for an
        // uppercase letter must not skip the digit and glue the next run.
        assert!(!is_small_caps_continuation(
            "ANGELA M. MAZZARELLI1",
            &make_item_fs("ANGELA", 100.0, 500.0, 40.0, 9.98),
            &make_item_fs("SHULMAN", 140.0, 500.0, 30.0, 6.74),
            0.0,
        ));
    }

    #[test]
    fn ordinal_suffix_after_a_digit_still_merges() {
        // "TUESDAY, JULY 4" + "TH" is one word in the source; the digit guard
        // must not block the four English ordinal suffixes.
        for suffix in ["TH", "ST", "ND", "RD"] {
            assert!(
                is_small_caps_continuation(
                    "TUESDAY, JULY 4",
                    &make_item_fs("JULY", 100.0, 500.0, 30.0, 12.0),
                    &make_item_fs(suffix, 130.0, 500.0, 8.0, 8.0),
                    0.0,
                ),
                "{suffix} should merge after a digit"
            );
        }
    }

    #[test]
    fn superscript_footnote_marker_is_not_a_small_caps_continuation() {
        // A digit must never qualify — otherwise footnote markers get glued on
        // without the superscript handling.
        assert!(!is_small_caps_continuation(
            "MAZZARELLI",
            &make_item_fs("MAZZARELLI", 100.0, 500.0, 50.0, 9.98),
            &make_item_fs("1", 150.0, 503.0, 3.0, 6.74),
            0.0,
        ));
    }

    #[test]
    fn drop_cap_is_not_a_small_caps_continuation() {
        // Mixed-case body text after a large initial is a drop cap, not small
        // caps.
        assert!(!is_small_caps_continuation(
            "T",
            &make_item_fs("T", 100.0, 500.0, 20.0, 30.0),
            &make_item_fs("he court held", 120.0, 500.0, 60.0, 10.0),
            0.0,
        ));
    }

    #[test]
    fn separate_word_is_not_a_small_caps_continuation() {
        // A real word space disqualifies even when both runs are uppercase.
        let first = make_item_fs("SEE", 100.0, 500.0, 20.0, 9.98);
        let next = make_item_fs("ALSO", 128.0, 500.0, 25.0, 6.74);
        assert!(!is_small_caps_continuation("SEE", &first, &next, 8.0));
    }

    #[test]
    fn lowercase_continuation_is_not_small_caps() {
        assert!(!is_small_caps_continuation(
            "SMALL",
            &make_item_fs("SMALL", 100.0, 500.0, 30.0, 9.98),
            &make_item_fs("caps", 130.0, 500.0, 20.0, 6.74),
            0.0,
        ));
    }

    #[test]
    fn too_small_a_ratio_is_not_small_caps() {
        // 0.4 ratio is a superscript/sub-run, outside the small-caps band.
        assert!(!is_small_caps_continuation(
            "A",
            &make_item_fs("A", 100.0, 500.0, 7.0, 10.0),
            &make_item_fs("BC", 107.0, 500.0, 8.0, 4.0),
            0.0,
        ));
    }

    #[test]
    fn vertical_run_never_merges_with_body_text_sharing_its_baseline() {
        // A 12pt margin stamp whose box bottom lands on a body line's
        // baseline, 2pt left of the body text: same y-group, tiny gap, same
        // font — every merge criterion but orientation says "join". The same
        // items set upright DO merge, so orientation is what blocks it.
        let mut stamp = make_merge_item("arXiv:2301.00001", 12.0, 12.0);
        stamp.height = 120.0;
        stamp.rotation = 90.0;
        let body = make_merge_item("Body text", 26.0, 54.0);

        let merged = merge_text_items(vec![stamp.clone(), body.clone()]);
        assert_eq!(merged.len(), 2, "{merged:?}");
        assert_eq!(merged[0].text, "arXiv:2301.00001");
        assert_eq!(merged[1].text, "Body text");

        stamp.height = 12.0;
        stamp.rotation = 0.0;
        stamp.width = 96.0;
        let body_after_upright_stamp = make_merge_item("Body text", 110.0, 54.0);
        let merged = merge_text_items(vec![stamp, body_after_upright_stamp]);
        assert_eq!(merged.len(), 1);
        assert_eq!(merged[0].text, "arXiv:2301.00001 Body text");
    }

    #[test]
    fn link_annotations_turn_with_a_rotated_page() {
        use crate::tounicode::FontCMaps;
        use lopdf::{dictionary, Object, Stream};

        // Two 90° runs make the page rotated; the link annotation covering
        // the first one (page box x 188..200, y 100..140) must land in the
        // same turned frame as the text: x = old y, y = -(old right edge).
        let mut doc = lopdf::Document::new();
        let widths: Vec<Object> = (0..=255).map(|_| 600.into()).collect();
        let font_id = doc.add_object(dictionary! {
            "Type" => "Font",
            "Subtype" => "Type1",
            "BaseFont" => "Helvetica",
            "FirstChar" => 0,
            "LastChar" => 255,
            "Widths" => Object::Array(widths),
        });
        let content_id = doc.add_object(Object::Stream(Stream::new(
            dictionary! {},
            b"BT /F1 12 Tf 0 1 -1 0 200 100 Tm (HELLO) Tj ET
BT /F1 12 Tf 0 1 -1 0 240 100 Tm (WORLD) Tj ET"
                .to_vec(),
        )));
        let link_id = doc.add_object(dictionary! {
            "Type" => "Annot",
            "Subtype" => "Link",
            "Rect" => vec![188.into(), 100.into(), 200.into(), 140.into()],
            "A" => dictionary! {
                "S" => "URI",
                "URI" => Object::string_literal("https://example.com/"),
            },
        });
        // An AcroForm text field drawn over the second run (page box
        // x 228..240, y 100..150) must turn the same way.
        let widget_id = doc.add_object(dictionary! {
            "Type" => "Annot",
            "Subtype" => "Widget",
            "FT" => "Tx",
            "T" => Object::string_literal("field"),
            "V" => Object::string_literal("value"),
            "Rect" => vec![228.into(), 100.into(), 240.into(), 150.into()],
        });
        let page_id = doc.add_object(dictionary! {
            "Type" => "Page",
            "Contents" => Object::Reference(content_id),
            "Annots" => vec![Object::Reference(link_id), Object::Reference(widget_id)],
            "Resources" => dictionary! {
                "Font" => dictionary! { "F1" => Object::Reference(font_id) },
            },
            "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()],
        });
        let pages_id = doc.add_object(dictionary! {
            "Type" => "Pages",
            "Count" => Object::Integer(1),
            "Kids" => vec![Object::Reference(page_id)],
        });
        let catalog_id = doc.add_object(dictionary! {
            "Type" => "Catalog",
            "Pages" => Object::Reference(pages_id),
            "AcroForm" => dictionary! {
                "Fields" => vec![Object::Reference(widget_id)],
            },
        });
        doc.trailer.set("Root", Object::Reference(catalog_id));

        let font_cmaps = FontCMaps::from_doc(&doc);
        let ((items, _, _), _, _, page_rotations) =
            extract_positioned_text_from_doc(&doc, &font_cmaps, None).unwrap();
        assert_eq!(page_rotations.get(&1), Some(&geometry::PageRotation::Ccw));
        let field = items
            .iter()
            .find(|i| matches!(i.item_type, ItemType::FormField))
            .expect("form field item");
        assert_eq!(
            (field.x, field.y, field.width, field.height),
            (100.0, -240.0, 50.0, 12.0)
        );
        let hello = items.iter().find(|i| i.text == "HELLO").unwrap();
        assert_eq!(hello.rotation, 0.0);
        assert!((hello.x - 100.0).abs() < 0.01 && (hello.y + 200.0).abs() < 0.01);
        let link = items
            .iter()
            .find(|i| matches!(i.item_type, ItemType::Link(_)))
            .expect("link item");
        assert_eq!(
            (link.x, link.y, link.width, link.height),
            (100.0, -200.0, 40.0, 12.0)
        );
        assert_eq!(link.rotation, 0.0);
    }

    #[test]
    fn upside_down_fragments_are_never_concatenated_reversed() {
        // A 180° run shown as two operators: "HELLO" is painted first, at
        // the right, and "WORLD" continues towards -x. Walking x ascending
        // would merge them as "WORLD HELLO"; they must stay separate.
        let mut hello = make_merge_item("HELLO", 310.0, 50.0);
        hello.rotation = 180.0;
        let mut world = make_merge_item("WORLD", 258.0, 50.0);
        world.rotation = 180.0;
        let merged = merge_text_items(vec![hello, world]);
        assert_eq!(merged.len(), 2, "{merged:?}");
        assert!(merged.iter().any(|i| i.text == "HELLO"));
        assert!(merged.iter().any(|i| i.text == "WORLD"));
    }

    #[test]
    fn measured_and_estimated_runs_never_merge() {
        // A width-less font's run (estimated box) next to a measured one on
        // the same baseline: the pair must stay two items, whichever comes
        // first, so `advance_known` keeps describing each item truthfully.
        let measured = make_merge_item("known", 100.0, 30.0);
        let mut estimated = make_merge_item("guess", 132.0, 30.0);
        estimated.advance_known = false;
        assert_eq!(
            merge_text_items(vec![measured.clone(), estimated.clone()]).len(),
            2
        );
        assert_eq!(merge_text_items(vec![estimated, measured]).len(), 2);
    }

    #[test]
    fn merged_estimated_runs_keep_the_union_of_their_boxes() {
        // Two width-less runs positioned at their estimated advance (half an
        // em per glyph at 12pt) walk like measured ones — gap 0, no space —
        // and the merged item is the union of the two estimated boxes.
        let mut first = make_merge_item("ab", 100.0, 12.0);
        first.advance_known = false;
        let mut second = make_merge_item("cdefg", 112.0, 30.0);
        second.advance_known = false;
        let merged = merge_text_items(vec![first, second]);
        assert_eq!(merged.len(), 1, "{merged:?}");
        assert_eq!(merged[0].text, "abcdefg");
        assert!(!merged[0].advance_known);
        assert!((merged[0].x - 100.0).abs() < 1e-3, "x = {}", merged[0].x);
        assert!(
            (merged[0].width - 42.0).abs() < 1e-3,
            "width = {}",
            merged[0].width
        );
    }

    #[test]
    fn estimated_fragments_that_backtrack_keep_the_union_box() {
        // Stream order "abc" (x 100), "de" (x 94, a backtrack), "fg" (x 118):
        // whichever order the merge walks, the estimated item spans from the
        // leftmost fragment to the rightmost box edge.
        let mut a = make_merge_item("abc", 100.0, 18.0);
        let mut b = make_merge_item("de", 94.0, 10.0);
        let mut c = make_merge_item("fg", 118.0, 12.0);
        for item in [&mut a, &mut b, &mut c] {
            item.advance_known = false;
            item.mcid = Some(1);
        }
        let merged = merge_text_items(vec![a, b, c]);
        assert_eq!(merged.len(), 1, "{merged:?}");
        assert!(!merged[0].advance_known);
        assert!((merged[0].x - 94.0).abs() < 1e-3, "x = {}", merged[0].x);
        assert!(
            (merged[0].width - 36.0).abs() < 1e-3,
            "width = {}",
            merged[0].width
        );
    }

    #[test]
    fn side_by_side_vertical_runs_stay_separate_lines() {
        // Two lines of a vertical stamp are adjacent em columns with the
        // same bottom: walking x would glue them into one "line".
        let mut first = make_merge_item("line one", 12.0, 12.0);
        first.height = 80.0;
        first.rotation = 90.0;
        let mut second = make_merge_item("line two", 24.0, 12.0);
        second.height = 80.0;
        second.rotation = 90.0;
        let merged = merge_text_items(vec![first, second]);
        assert_eq!(merged.len(), 2, "{merged:?}");
    }
}