rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
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
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
//! 단일 패스 조판 엔진 (TypesetEngine)
//!
//! 기존 3단계 파이프라인(height_measurer → pagination → layout)을 대체하는
//! 단일 패스 조판 엔진. 각 요소를 format() → fits() → place/split 순서로
//! 처리하여 측정과 배치를 하나의 흐름으로 통합한다.
//!
//! Phase 2: Break Token 기반 표 조판 구현.
//! Chromium LayoutNG의 Break Token 패턴, LibreOffice Writer의 Master/Follow Chain,
//! MS Word/OOXML의 cantSplit/tblHeader를 참고.

use crate::renderer::typeset::notes::footnotes::boundary::{
    native_hwp5_existing_footnote_reset_boundary, native_hwp5_first_footnote_overlap_break_line,
    native_hwp5_footnote_reset_fragments, NativeHwp5FootnoteFragmentSplit,
};
use crate::renderer::typeset::notes::footnotes::measure::{
    composed_footnote_content_height, queued_table_footnote_content_height,
};

use crate::document_core::queries::rendering::body_pile_stays_on_anchor_page;
use crate::model::control::Control;
use crate::model::footnote::{Footnote, FootnoteShape};
use crate::model::header_footer::HeaderFooterApply;
use crate::model::page::{ColumnDef, ColumnType, PageDef};
use crate::model::paragraph::{ColumnBreakType, LineSeg, Paragraph};
use crate::model::shape::CaptionDirection;
use crate::renderer::composer::{compose_paragraph, first_text_line, ComposedParagraph};
use crate::renderer::float_placement::{
    is_last_para_topbottom_float, is_page_bottom_fixed_float, is_para_topbottom_float,
    is_textless_coanchored_float_host, signed_hwpunit,
    stored_visible_anchor_band_host_line_advance_from_vpos, FloatLaneSet,
};
use crate::renderer::height_cursor::HeightCursor;
use crate::renderer::height_measurer::{stored_square_picture_has_adjacent_text, MeasuredTable};
use crate::renderer::layout::table_layout::native_terminal_child_host_line_spacing;
use crate::renderer::layout::{
    border_width_to_px, endnote_last_column_tail_overflows_frame,
    ENDNOTE_COLUMN_BOTTOM_BLEED_TOLERANCE_PX, ENDNOTE_LAST_COLUMN_SPLIT_BLEED_PX,
};
use crate::renderer::page_layout::PageLayoutInfo;
use crate::renderer::style_resolver::ResolvedStyleSet;
use crate::renderer::{
    format_number, hwpunit_to_px, NumberFormat as RenderNumberFormat, DEFAULT_DPI,
};

// [Task #836] 미주 paragraph의 가상 para_index = paragraphs.len() + endnote 내 순번.
// rendering.rs에서 paragraphs + endnote_paragraphs를 합쳐서 전달.
use self::controls::deferred::{DeferredTableControl, DeferredTableFlushPoint};
use self::paragraph::boundary::hwpx_explicit_page_break_tail_line;
use self::paragraph::line_queries::{
    composed_line_char_end, line_has_strict_tac_control, line_has_text_span, line_has_visible_text,
};
use self::paragraph::metrics::FormattedParagraph;
use self::paragraph::stored_lines::{
    next_boundary_reverts_spacing_trim, spacing_trim_restorable,
    stored_ladder_encodes_spacing_before,
};
use self::stored_table_frame::{
    table_declared_height_has_stored_cell_content_frame,
    table_declared_object_covers_cell_row_frames,
};
use super::pagination::{
    estimate_footnote_note_height, footnote_between_notes_margin_px,
    footnote_separator_overhead_px, ColumnContent, EndnoteDeferral, EndnoteParaSource, EndnoteRef,
    FootnoteFragment, FootnoteRef, FootnoteSource, HeaderFooterRef, PageContent, PageItem,
    PaginationResult,
};

/// [#5886] 미주 다단이 본문 하단 24px bleed 를 지나 **용지 밖**까지 그리는
/// 잔여만 단 전환한다. 용지 하단 여백(~30px)+bleed 보다 크고, CI 실측
/// 2022.hwpx 12쪽 잔여 초과(+69.7px, 수정 전 +198px)보다는 작다.
/// 80px 는 663번 문단(69.7px)을 놓쳐 알짜 풀이가 1193px 에 남았다.
const ENDNOTE_PAGE_OFFCANVAS_GUARD_PX: f64 = 56.0;

/// [#4654] 전면 크기 그림 낱장 배치는 문단의 비인라인 그림 중 엄격한 과반일 때만 쓴다.
///
/// 정확히 절반인 문단까지 낱장 정책을 적용하면 기존 pile 문서의 다수 그림 흐름을
/// 불필요하게 페이지 단위로 분리한다. 두 장 이상이라는 #1995의 하한은 유지한다.
/// 저장 줄 `next` 가 앞 저장 줄 `prev` 뒤에서 쪽 리셋(vpos <= 0, 앞 줄이 쪽에서 5000HU 넘게
/// 내려간 뒤 — #1920 임계)되었는가. 한/글이 그 줄을 다음 쪽 맨 위에 두었다는 저장 증거다.
/// 앞 줄이 내려간 깊이는 그 줄의 끝(vpos + lh)이다 — 쪽 첫머리의 큰 표 줄은 시작 vpos 가
/// 작아도 쪽을 채운다. 합성 줄은 증거가 아니다.
pub(crate) fn stored_line_restarts_page(
    prev: &crate::model::paragraph::LineSeg,
    next: &crate::model::paragraph::LineSeg,
) -> bool {
    (prev.tag | next.tag) & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && next.vertical_pos <= 0
        && prev.vertical_pos.saturating_add(prev.line_height) > 5000
}

fn has_majority_fullpage_images(fullpage_count: usize, noninline_picture_count: usize) -> bool {
    fullpage_count >= 2 && fullpage_count.saturating_mul(2) > noninline_picture_count
}

/// [#6511] #1995 낱장 배치는 본문 흐름에 참여하는 비-TAC 그림만 후보와 과반
/// 분모로 센다. 글뒤로/글앞으로(BehindText/InFrontOfText) 그림은 흐름 공간을
/// 소비하지 않아 한 쪽에 몇 장이든 공존할 수 있으므로(#703 표와 같은 불변식)
/// 전면 크기라도 스캔 이미지가 아니라 배경/워터마크다. 낱장 배치 후보로 세면
/// 배경 프레임을 깐 안내문이 강제 새 쪽을 얻고, 분모로만 남겨도 스캔 그림의
/// 과반을 희석해 정당한 낱장 배치를 억제한다 — 양쪽 모두에서 제외한다.
fn flow_noninline_picture(ctrl: &Control) -> Option<&crate::model::image::Picture> {
    match ctrl {
        Control::Picture(pic)
            if !pic.common.treat_as_char
                && !matches!(
                    pic.common.text_wrap,
                    crate::model::shape::TextWrap::BehindText
                        | crate::model::shape::TextWrap::InFrontOfText
                ) =>
        {
            Some(pic)
        }
        _ => None,
    }
}

use self::table::continuation::{
    BlockTableContinuationContext, BlockTableContinuationPreparedState,
    BlockTableContinuationSource, PendingTableFootnoteFragment, TableContinuationCursor,
    TableContinuationIteration,
};
pub(crate) use self::table::continuation::{ResumablePaginationStep, ResumableTablePaginationJob};
use self::table::scan::{BlockRowScanVars, BlockTableRowScan};

fn empty_paragraph_fallback_line_metrics(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    para_style: Option<&crate::renderer::style_resolver::ResolvedParaStyle>,
    hwp3_legacy_caps: bool,
) -> Option<(f64, f64)> {
    if let Some((height, leading, _)) =
        crate::renderer::reflow_float_host_line::neutral_anchor_metrics(
            para,
            styles,
            para_style,
            hwp3_legacy_caps,
            DEFAULT_DPI,
        )
    {
        return Some((height, leading));
    }
    // 글앞으로/글뒤로/어울림(비자리차지) 앵커 도형·그림만
    // 가진 빈 문단은 한글이 텍스트 관점의 빈 문단과 동일하게 완전한 em 줄박스를
    // 부여한다 (사용안내 실측: Square 그림 앵커 빈 문단 pi1/pi6 이 0~5.3px 로 붕괴
    // → 한글은 27.7px(base 1300 × 160%) 부여 — PrvImage 줄 좌표 대조). 자리차지
    // (TopAndBottom)는 흐름 소비 계약이 별도라 제외를 유지한다.
    let controls_flow_neutral = crate::renderer::empty_host_controls_are_flow_neutral(para);
    // char_count == 0 배제는 순수 빈 문단(컨트롤 없음)에만 유지한다 — 글앞/글뒤
    // 도형·그림 앵커 문단은 char_count 0 으로 저장되는 경우가 있고(사용안내 pi1/pi6
    // 실측 0px 붕괴), 한글은 이들에도 완전한 em 줄박스를 부여한다.
    if std::env::var("RHWP_DIAG_EMPTYP").is_ok() && !para.controls.is_empty() {
        eprintln!(
            "DIAG_EMPTYP text={:?} ctrls={} neutral={} segs={} cc={}",
            para.text.chars().take(6).collect::<String>(),
            para.controls.len(),
            controls_flow_neutral,
            para.line_segs.len(),
            para.char_count,
        );
    }
    if !para.text.trim().is_empty()
        || !(para.controls.is_empty() || controls_flow_neutral)
        || !para.line_segs.is_empty()
        || (para.char_count == 0 && para.controls.is_empty())
    {
        return None;
    }
    let char_shape_id =
        para.char_shape_id_at(0)
            .or_else(|| para.char_shapes.first().map(|cs| cs.char_shape_id))? as usize;
    let char_style = styles.char_styles.get(char_shape_id)?;
    let font_size = char_style.font_size;
    if font_size <= 0.0 {
        return None;
    }
    // [#2070 stage12] 폰트 크기 캡(10pt 이하, 비볼드 8pt 미만 제외)은 HWP3 변환본
    // 한정으로 유지한다 — 한글은 NO_LS 빈 문단을 크기와 무관하게 완전한 em 줄박스로
    // 재계산하지만(D-사다리 + 80168 실측), HWP3→HWP5 변환본은 종전 캡이 페이지 수
    // 게이트(sample16-hwp5 = 64)와 정합(캡 전면 제거 시 65 over-split).
    if hwp3_legacy_caps {
        let small_empty_para_max_font = hwpunit_to_px(1000, DEFAULT_DPI);
        if font_size > small_empty_para_max_font + 0.1 {
            return None;
        }
        let meaningful_empty_para_min_font = hwpunit_to_px(800, DEFAULT_DPI);
        if !char_style.bold && font_size < meaningful_empty_para_min_font - 0.1 {
            return None;
        }
    }
    let ls_val = para_style.map(|s| s.line_spacing).unwrap_or(160.0);
    let ls_type = para_style
        .map(|s| s.line_spacing_type)
        .unwrap_or(crate::model::style::LineSpacingType::Percent);
    Some(crate::renderer::corrected_line_metrics(
        0.0, 0.0, font_size, ls_type, ls_val,
    ))
}

fn raw_table_ctrl_height_px(table: &crate::model::table::Table, dpi: f64) -> Option<f64> {
    let range = crate::model::shape::common_obj_offsets::HEIGHT;
    if table.raw_ctrl_data.len() < range.end {
        return None;
    }
    let height = u32::from_le_bytes(table.raw_ctrl_data[range].try_into().ok()?);
    (height > 0).then(|| hwpunit_to_px(height as i32, dpi))
}

// ========================================================
// Break Token — 조판 분할 지점 (Chromium LayoutNG 참고)
// ========================================================

/// 표 조판의 분할 재개 정보.
/// 다음 페이지에서 이 토큰으로부터 이어서 조판한다.
#[derive(Debug, Clone)]
struct TableBreakToken {
    /// 재개할 시작 행 인덱스
    start_row: usize,
    /// 인트라-로우 분할 시 각 셀의 콘텐츠 오프셋
    cell_content_offsets: Option<Vec<f64>>,
}
crate::storage::clone_fields!(TableBreakToken, {start_row, cell_content_offsets});

/// RowBreak 표가 page boundary를 넘을 때 queue가 source order로 등록할 셀 각주.
///
/// `fragment_split`은 native HWP5 cell-footnote의 실제 stored vpos reset을 그대로
/// 옮긴 경우에만 채운다. 단순 capacity 부족은 일반 각주처럼 원자적으로 유지한다.
#[derive(Debug, Clone)]
struct TableCellFootnote {
    number: u16,
    cell_path: Vec<crate::renderer::pagination::TableFootnotePathEntry>,
    row: usize,
    /// Renderer가 실제 줄바꿈·trailing line-spacing까지 합산한 높이. RowBreak
    /// fragment queue는 이 값을 써야 URL 각주가 본문 위로 침범하지 않는다.
    content_height: f64,
    fragment_split: Option<NativeHwp5FootnoteFragmentSplit>,
}
crate::storage::clone_fields!(TableCellFootnote, {number, cell_path, row, content_height, fragment_split});

/// 배치 중인 본문 문단의 각주 한 개. `line` 은 참조 표시가 든 저장 줄이다.
///
/// 한/글은 각주를 참조 줄과 같은 쪽 아래에 두며, 참조 줄 뒤의 본문 줄은 그 각주
/// 영역 위에서 끝난다. 분할 판정은 이미 받은 줄의 각주를 다음 줄보다 먼저 예약한다.
#[derive(Debug, Clone)]
pub(in crate::renderer::typeset) struct OwnLineNote {
    pub para_index: usize,
    pub line: usize,
    pub control_index: usize,
    pub number: u16,
    pub content_height: f64,
    /// 각주 전체를 펼친 줄의 (줄 높이, 줄간격). 넘친 각주를 줄 단위로 나눌 때 쓴다.
    /// 구성 줄이 저장 줄과 일대일이 아니면 비워 둔다(통째로만 옮긴다).
    pub lines: Vec<(f64, f64)>,
    /// 저장 각주 줄 사다리가 가리키는 한/글의 쪽 나눔.
    pub stored_split: Option<NativeHwp5FootnoteFragmentSplit>,
}

// ========================================================
// FormattedTable — 표의 format() 결과
// ========================================================

/// 표의 조판 높이 정보 (format 단계 결과).
/// 기존 MeasuredTable + host_spacing을 통합하여 측정-배치 일원화.
#[derive(Debug)]
struct FormattedTable {
    /// 부모 프레임과 외부 자식의 공동 앵커 점유. 소스 행/컷 원장과 구분한다.
    external_flow: Option<crate::renderer::float_placement::ReflowExternalTableFlow>,
    /// 행별 높이 (px)
    row_heights: Vec<f64>,
    /// 행간 간격 (px)
    cell_spacing: f64,
    /// 머리행 수 (repeat_header && has_header_cells일 때 1)
    header_row_count: usize,
    /// 호스트 문단 spacing
    host_spacing: HostSpacing,
    /// 표 자체 높이 (host_spacing 미포함)
    effective_height: f64,
    /// 전체 높이 (host_spacing 포함)
    total_height: f64,
    /// 캡션 높이
    caption_height: f64,
    /// TAC 표 여부
    is_tac: bool,
    /// 누적 행 높이 (cell_spacing 포함)
    cumulative_heights: Vec<f64>,
    /// 표 쪽 나눔 설정
    page_break: crate::model::table::TablePageBreak,
    /// 셀별 측정 데이터 (인트라-로우 분할용)
    cells: Vec<crate::renderer::height_measurer::MeasuredCell>,
    /// 표 셀 내 각주 높이 합계 (가용 높이에서 차감)
    table_footnote_height: f64,
    /// 표 셀 내 각주 수 (separator/between-notes 예약 계산용)
    table_footnote_count: usize,
    /// 표 셀 각주의 source·순서·측정 높이.
    table_footnotes: Vec<TableCellFootnote>,
    /// #2439: 이 표 직후의 일반 문단은 trailing line advance까지 포함해 fit한다.
    /// native HWP의 단일 양수-offset 빈 호스트 RowBreak 표 증거가 있을 때만 true.
    strict_following_plain_text_fit: bool,
}

#[derive(Debug, Clone, Copy)]
struct VisibleFloatExclusion {
    /// 이 밴드를 만든 host 문단. 같은 문단의 co-anchored float 은 밴드를 서로
    /// 넘겨 짚으면 안 되므로(`#1510`) 소유자를 함께 싣는다.
    para_index: usize,
    /// visible host 문단의 자리차지 float 표가 후속 본문을 피하게 만드는 y 구간.
    top: f64,
    bottom: f64,
}
crate::storage::clone_copy!(VisibleFloatExclusion);

/// 다음 physical page의 본문 시작에 배치할 non-TAC Square picture control.
///
/// 그림은 float라 본문 높이를 소비하지 않지만, native HWP5는 anchor 문단이 page tail에
/// 있고 그림+caption이 각주 영역까지 닿으면 anchor의 남은 본문 줄은 현재 쪽에 유지한
/// 채 그림만 다음 쪽의 wrap band로 이월한다. `PageItem`을 현재 쪽에 즉시 넣으면 layout
/// 단계에서는 그 단의 anchor 좌표밖에 모르므로 본문/각주 위에 겹친다.
#[derive(Debug, Clone)]
struct DeferredSquarePictureControl {
    para_index: usize,
    control_index: usize,
    /// 그림이 다음 physical page를 소유할 때 같은 page에서 narrow line band를 써야 하는
    /// 연속 후속 본문 문단. 그림 PageItem만 이월하면 layout은 이 source contract를 알 수 없어
    /// 첫 문단 뒤의 본문을 전폭으로 그리고 Square 그림과 교차시킨다.
    wrap_target_para_indices: Vec<usize>,
    wrap_anchor: crate::renderer::pagination::WrapAnchorRef,
}
crate::storage::clone_fields!(DeferredSquarePictureControl, {para_index, control_index, wrap_target_para_indices, wrap_anchor});

/// 저장 정보 또는 확정한 계산 프레임으로 다음 쪽 상단 소유가 확인된 개체.
#[derive(Debug, Clone)]
enum DeferredStoredFrameKind {
    Picture,
    Table,
    AbsoluteShape,
}
impl crate::storage::CloneWithStorage for DeferredStoredFrameKind {
    fn clone_with_storage<S: crate::storage::Storage>(
        &self,
        storage: &S,
    ) -> Result<Self, S::Error> {
        match self {
            Self::Picture => Ok(Self::Picture),
            Self::Table => Ok(Self::Table),
            Self::AbsoluteShape => Ok(Self::AbsoluteShape),
        }
    }
}

#[derive(Debug, Clone)]
struct DeferredStoredFrameControl {
    /// 명시한 저장 쪽 소유. None이면 기존의 바로 다음 쪽 이월이다.
    target_page: Option<usize>,
    kind: DeferredStoredFrameKind,
    para_index: usize,
    control_index: usize,
    placement: crate::renderer::float_placement::ParagraphFloatPlacement,
    /// This original zero-origin body starts after the deferred object's page.
    following_body_para_index: Option<usize>,
}
crate::storage::clone_fields!(DeferredStoredFrameControl, {target_page, kind, para_index, control_index, placement, following_body_para_index});

/// 호스트 문단의 spacing (표 전/후)
#[derive(Debug, Clone, Copy)]
struct HostSpacing {
    /// 표 앞 spacing (spacing_before + outer_margin_top)
    before: f64,
    /// 표 뒤 spacing (spacing_after + outer_margin_bottom + host_line_spacing)
    after: f64,
    /// 단 상단에서 열 때의 `before` — 문단 앞 간격 없이 바깥 위 여백만. 앞 쪽에서 포맷한
    /// 표를 이월해 새 단 첫머리에 놓으면 이 값을 쓴다.
    column_top_before: f64,
    /// `after` 에 든 host 문단 줄간격(표-표 스택 간격, #1133).
    host_line_spacing: f64,
    /// spacing_after만 (마지막 fragment용 — Paginator와 동일)
    spacing_after_only: f64,
    /// 재조판한 흐름 개체의 마지막 조각 뒤에서 닫을 아래 바깥여백.
    terminal_outer_bottom_flow: f64,
    /// 페이지 적합 판정용 after — 빈 호스트 자리차지 표의 outer_margin_bottom 은
    /// 흐름 전진에만 계상하고 fit 에서 제외한다 (#2195 stage58: 86712 구분선 간격
    /// 한글 괘선 실측 vs hwpspec 178쪽 핀(#1086) 동시 충족).
    after_for_fit: f64,
}
crate::storage::clone_copy!(HostSpacing);

/// 단일 패스 조판 엔진
pub struct TypesetEngine {
    dpi: f64,
    section_column_spacing_hu: std::cell::Cell<Option<i32>>,
    /// [#2403] 현재 조판 입력의 레이아웃 호환 프로파일 — typeset 진입 시 set.
    /// (HWPX 저장 시멘틱·HWP3 변환본 판단 등 소스분기의 단일 질의 표면.)
    profile: std::cell::Cell<crate::model::provenance::LayoutCompatibilityProfile>,
    /// [#5854] 현재 구역의 저장 LINE_SEG 사다리가 통짜 합성값인지 — 구역 진입 시 set.
    /// 참이면 줄 metrics 를 저장값이 아니라 글꼴·문단 스타일에서 다시 뽑는다.
    uniform_filler_ladder: std::cell::Cell<bool>,
    /// [#6175] 현재 구역의 용지/쪽 기준 어울림 개체 흐름 증거 — 구역 진입 시 set.
    /// 폭과 세로 band가 모두 맞을 때만 저장 행 admission이 균일한 좁은 행을
    /// 문단 자신의 테두리 inset과 구분한다.
    float_carve_evidence:
        std::cell::RefCell<Vec<crate::renderer::float_placement::FloatCarveEvidence>>,
    /// [#7840] 본문 흐름이 지금 구성하는 문단 바로 뒤 문단의 첫 저장 줄 vpos.
    /// 흐름 진입에서만 set 하고 구성 직후 비운다 — 다른 구성 경로는 None 을 본다.
    format_next_stored_vpos: std::cell::Cell<Option<i32>>,
    render_normalization:
        std::sync::Arc<crate::renderer::render_normalization::RenderNormalizationOverlay>,
    /// 같은 상태 세대에서 반복된 미주 단 측정 결과.
    endnote_measure_memo: std::cell::RefCell<notes::endnotes::measure_memo::EndnoteMeasureMemo>,
}

/// 조판 중 현재 페이지/단 상태
/// [#3236] 1행 1열 RowBreak 표의 선언 높이 신뢰(#1891) 상한 배율. 측정이 선언의
/// 이 배율을 넘으면 폰트 대체 팽창이 아니라 셀 내용이 진짜로 큰 것이므로 특례를
/// 적용하지 않고 인트라-로우 분할 경로에 맡긴다.
const SINGLE_ROW_DECLARED_TRUST_MAX_RATIO: f64 = 1.5;
/// [Task #2085] 표 분할 첫 조각에 남길 최소 상단 높이 / RowBreak 말미 빈 행 허용 오버플로.
const MIN_TOP_KEEP_PX: f64 = 25.0;

/// Row-internal splits normally keep the established content-only orphan threshold.  The narrow
/// native-HWP #2439 contract instead compares the painted fragment, including visible cell
/// padding, because that is the height that actually remains on the page.
#[inline]
fn row_split_meets_min_top_keep(
    content_height: f64,
    painted_height: f64,
    use_painted_height: bool,
) -> bool {
    let keep_height = if use_painted_height {
        painted_height
    } else {
        content_height
    };
    keep_height >= MIN_TOP_KEEP_PX
}

/// [#6035] 행의 셀 문단 저장 사다리에 **비전진(동일 vpos) 연속 seg 쌍**이 있는지 —
/// 저장 시점 한글이 이 행을 쪽 경계에서 줄 단위로 나눈 흔적이다 (2804253 r70:
/// 0/1560/1560, horz 동일이라 좌우분할 아님). 같은 vpos 의 세 의미(좌우분할·쪽
/// 리셋·중복) 중 좌우분할은 `column_start`/폭이 갈리므로 세로 신호만 잡는다.
fn row_has_stored_same_vpos_split_signal(table: &crate::model::table::Table, row: usize) -> bool {
    table
        .cells
        .iter()
        .filter(|cell| cell.row as usize == row)
        .any(|cell| {
            cell.paragraphs.iter().any(|paragraph| {
                paragraph.line_segs.windows(2).any(|pair| {
                    pair.iter().all(|seg| {
                        seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                    }) && pair[0].vertical_pos > 0
                        && pair[1].vertical_pos == pair[0].vertical_pos
                        && pair[1].column_start == pair[0].column_start
                        && pair[1].segment_width == pair[0].segment_width
                })
            })
        })
}

/// [#6860] 셀의 첫 한 줄 뒤에서 다음 문단이 같은 0으로 재개하고, 그 다음
/// 문단부터 정상 전진하는 저장 경계. 모든 문단을 0으로 저장한 입력이나
/// 개체/빈 문단, 서로 다른 열의 줄은 쪽 경계 증거로 사용하지 않는다.
fn row_has_stored_cross_paragraph_zero_reset(
    table: &crate::model::table::Table,
    row: usize,
) -> bool {
    use crate::model::paragraph::LineSeg;

    table
        .cells
        .iter()
        .filter(|cell| cell.row as usize == row)
        .any(|cell| {
            let Some(paragraphs) = cell.paragraphs.get(..3) else {
                return false;
            };
            if paragraphs
                .iter()
                .any(|para| !para.controls.is_empty() || para.text.trim().is_empty())
            {
                return false;
            }
            let [first] = paragraphs[0].line_segs.as_slice() else {
                return false;
            };
            let [second] = paragraphs[1].line_segs.as_slice() else {
                return false;
            };
            let Some(third) = paragraphs[2].line_segs.first() else {
                return false;
            };
            [first, second, third].iter().all(|seg| {
                seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                    && seg.line_height > 0
                    && seg.column_start == first.column_start
                    && seg.segment_width == first.segment_width
            }) && first.vertical_pos == 0
                && second.vertical_pos == 0
                && third.vertical_pos > 0
                && i64::from(third.vertical_pos)
                    == i64::from(second.line_height) + i64::from(second.line_spacing.max(0))
        })
}

/// Native HWP로 저장·재파싱한 뒤에도 남는 "1열 셀을 1×2로 분할"한 표 구조.
///
/// [`crate::model::table::Table::split_cell_into`]는 기존 1열의 다른 셀을 새 2열
/// 전체 span으로 확장하고, 분할 대상 행에는 원문 셀과 템플릿에서 만든 빈 셀을
/// 나란히 둔다. `dirty_flag`는 저장 경계를 넘지 못하므로 이 구조만 #4138의
/// continuation strict-cut 근거로 쓴다. 병합 제목행과 일반 2열 데이터행이 섞인
/// 흔한 표(#2097)는 현재 행의 두 셀이 모두 본문을 가지므로 제외된다.
pub(crate) fn is_reparsed_single_column_cell_split_row(
    table: &crate::model::table::Table,
    row: usize,
) -> bool {
    if table.col_count != 2 || row >= table.row_count as usize {
        return false;
    }

    let mut row_cells = table
        .cells
        .iter()
        .filter(|cell| cell.row as usize == row)
        .collect::<Vec<_>>();
    row_cells.sort_by_key(|cell| cell.col);
    let matching_padding = row_cells.len() == 2
        && row_cells[0].padding.left == row_cells[1].padding.left
        && row_cells[0].padding.right == row_cells[1].padding.right
        && row_cells[0].padding.top == row_cells[1].padding.top
        && row_cells[0].padding.bottom == row_cells[1].padding.bottom;
    if row_cells.len() != 2
        || row_cells[0].col != 0
        || row_cells[1].col != 1
        || row_cells
            .iter()
            .any(|cell| cell.col_span != 1 || cell.row_span != 1)
        || row_cells[0].width.abs_diff(row_cells[1].width) > 1
        || row_cells[0].height != row_cells[1].height
        || row_cells[0].border_fill_id != row_cells[1].border_fill_id
        || !matching_padding
    {
        return false;
    }

    let cell_has_content = |cell: &&crate::model::table::Cell| {
        cell.paragraphs
            .iter()
            .any(|para| !para.text.is_empty() || !para.controls.is_empty())
    };
    let cell_is_template_empty = |cell: &&crate::model::table::Cell| {
        cell.paragraphs.len() == 1
            && cell.paragraphs[0].text.is_empty()
            && cell.paragraphs[0].controls.is_empty()
            && !cell.paragraphs[0].has_para_text
            && cell.paragraphs[0].char_count <= 1
    };
    let content_cells = row_cells
        .iter()
        .filter(|cell| cell_has_content(cell))
        .copied()
        .collect::<Vec<_>>();
    let template_cells = row_cells
        .iter()
        .filter(|cell| cell_is_template_empty(cell))
        .copied()
        .collect::<Vec<_>>();
    if content_cells.len() != 1 || template_cells.len() != 1 {
        return false;
    }

    let content_cell = content_cells[0];
    let template_cell = template_cells[0];
    if content_cell.col != 0 || template_cell.col != 1 {
        return false;
    }
    let Some(source_para) = content_cell.paragraphs.first() else {
        return false;
    };
    let template_para = &template_cell.paragraphs[0];

    // `new_from_template`는 문단 header를 그대로 복제하되 instanceId
    // (`raw_header_extra[6..10]`)만 0으로 만든다. 이 차이는 native HWP
    // 저장·재파싱 뒤에도 남는다. 단순 `has_para_text=false`는 자연 작성 빈
    // 셀에도 가능하므로, 나머지 raw header와 셀/문단 서식이 실제 clone인 경우만
    // split provenance로 인정한다.
    let zeroed_instance_clone = source_para.raw_header_extra.len() >= 10
        && source_para.raw_header_extra.len() == template_para.raw_header_extra.len()
        && source_para.raw_header_extra[6..10]
            .iter()
            .any(|byte| *byte != 0)
        && template_para.raw_header_extra[6..10]
            .iter()
            .all(|byte| *byte == 0)
        && source_para.raw_header_extra[..6] == template_para.raw_header_extra[..6]
        && source_para.raw_header_extra[10..] == template_para.raw_header_extra[10..];
    let cloned_first_char_shape = template_para.char_shapes.len()
        == source_para.char_shapes.len().min(1)
        && template_para
            .char_shapes
            .iter()
            .zip(source_para.char_shapes.iter())
            .all(|(template, source)| {
                template.start_pos == source.start_pos
                    && template.char_shape_id == source.char_shape_id
            });
    let cloned_first_line = template_para.line_segs.len() == 1
        && source_para
            .line_segs
            .first()
            .zip(template_para.line_segs.first())
            .is_some_and(|(source, template)| {
                source.text_start == template.text_start
                    && source.vertical_pos == template.vertical_pos
                    && source.line_height == template.line_height
                    && source.text_height == template.text_height
                    && source.baseline_distance == template.baseline_distance
                    && source.line_spacing == template.line_spacing
                    && source.column_start == template.column_start
                    && source.segment_width == template.segment_width
                    && source.tag == template.tag
            });
    if !zeroed_instance_clone
        || content_cell.raw_list_extra != template_cell.raw_list_extra
        || content_cell.list_header_width_ref != template_cell.list_header_width_ref
        || content_cell.text_direction != template_cell.text_direction
        || content_cell.vertical_align != template_cell.vertical_align
        || content_cell.apply_inner_margin != template_cell.apply_inner_margin
        || content_cell.is_header != template_cell.is_header
        || source_para.para_shape_id != template_para.para_shape_id
        || source_para.style_id != template_para.style_id
        || !cloned_first_char_shape
        || !cloned_first_line
    {
        return false;
    }

    let mut other_cells = table
        .cells
        .iter()
        .filter(|cell| cell.row as usize != row)
        .peekable();
    other_cells.peek().is_some()
        && other_cells.all(|cell| cell.col == 0 && cell.col_span == table.col_count)
}

/// Flow spacing repeated around a proven non-TAC RowBreak table fragment.
///
/// The first fragment keeps the formatted host-before value (paragraph spacing + outer top),
/// while a continuation repeats only the table's outer top.  Every fragment reserves the outer
/// bottom.  `repeat_outer_margin` is the narrow native-HWP evidence gate; applying this to every
/// RowBreak table is disproven by the #2097 COM page pins. `vertical_offset` remains a
/// first-fragment-only concern at the call site. `repeat_cellbreak_outer_margin` is the [#5922]
/// native-HWP CellBreak contract: the same reopen for proven empty-host TopAndBottom CellBreak
/// fragments (거대 표의 저장 ladder 는 표 높이를 접어 #2439 증거를 요구할 수 없다).
fn partial_rowbreak_fragment_spacing_px(
    table: &crate::model::table::Table,
    first_fragment_host_before: f64,
    is_continuation: bool,
    repeat_outer_margin: bool,
    repeat_cellbreak_outer_margin: bool,
    dpi: f64,
) -> (f64, f64) {
    let repeats_outer_margin = !table.common.treat_as_char
        && is_para_topbottom_float(&table.common)
        && match table.layout_page_break() {
            crate::model::table::TablePageBreak::RowBreak => repeat_outer_margin,
            crate::model::table::TablePageBreak::CellBreak => repeat_cellbreak_outer_margin,
            crate::model::table::TablePageBreak::None => false,
        };
    let before = if is_continuation {
        if repeats_outer_margin {
            hwpunit_to_px(table.outer_margin_top as i32, dpi)
        } else {
            0.0
        }
    } else {
        first_fragment_host_before
    };
    let bottom = if repeats_outer_margin {
        hwpunit_to_px(table.outer_margin_bottom as i32, dpi)
    } else {
        0.0
    };
    (before, bottom)
}

/// [#8149] 글 없는 host 의 문단 기준 자리차지 표가 쪽 바닥에서 나뉘면 한/글은 첫 조각
/// 아래에 그 표의 바깥 아래 여백과 (아래 캡션이면) 캡션 자리를 남긴다 — 한/글 2020 저장·
/// Print 합성 `samples/issue8149/gen_rowfit.py` 16사례: 캡션 없음·여백 0 은 본문 끝까지,
/// 여백 1984HU 는 여백만, 아래 캡션은 `여백 + 캡션 간격 + 캡션 줄` 을 남긴다. 첫 행이
/// 들어가는지 보는 이월 판정과 첫 조각 행 예산이 같은 값을 쓴다 — 한글문서파일형식 32쪽
/// 표 199 는 제목 행 19.5px 만 남은 22px 에 들어가 보였지만 이 예약 50.5px 를 넣으면 들지
/// 않아 한/글처럼 표 전체가 33쪽으로 넘어간다. 조각마다 반복하는 바깥 아래 여백
/// (`fragment_outer_bottom`)이 이미 있거나 원본 글 프레임이 첫 조각을 정하면 쓰지 않는다.
fn empty_host_float_first_fragment_reserve_px(
    para: &Paragraph,
    table: &crate::model::table::Table,
    fragment_outer_bottom: f64,
    has_source_text_first_frame: bool,
    caption_overhead: f64,
    caption_is_top: bool,
    dpi: f64,
) -> f64 {
    if fragment_outer_bottom > 0.0
        || has_source_text_first_frame
        || !is_para_topbottom_float(&table.common)
        || signed_hwpunit(table.common.vertical_offset) != 0
        || para_has_non_whitespace_text(para)
    {
        return 0.0;
    }
    hwpunit_to_px(table.outer_margin_bottom as i32, dpi).max(0.0)
        + if caption_is_top {
            0.0
        } else {
            caption_overhead
        }
}

/// [Task #853] ColumnDef 의 "디자인 spacing"(px): 1단이면 `간격`, 다단이면 0.
fn column_def_design_spacing_px(cd: &ColumnDef, dpi: f64) -> f64 {
    if cd.column_count.max(1) <= 1 {
        hwpunit_to_px(cd.spacing as i32, dpi)
    } else {
        0.0
    }
}

/// [#5918] 현재 단이 block-table continuation 꼬리 조각(들)과 빈 필러 문단만
/// 담고 있는지 — 저장 vpos 리셋의 이중 쪽 경계 판정용. 꼬리 조각이 저장 경계와
/// 같은 물리 쪽 경계를 이미 열어 놨다면 리셋의 advance는 중복이므로 호출부에서
/// 건너뜀.
///
/// 추가로 꼬리 조각이 쪽의 **소수 부분**(30% 이하)만 차지할 때 한정한다.
/// 드레인이 새로 연 쪽에 조각이 작게 남을 때는 그 쪽이 저장 사다리상 다음
/// 경계(리셋 문단)의 내용을 흡수할 예약 쪽이지만(sample1-repro pi=608:
/// 78px / pi=750: 220px), 조각 자체가 쪽을 대부분 채웠다면 그 쪽은 저장
/// 사다리에서 이미 소진된 독립 경계라 리셋은 별도의 다음 쪽을 가리킨다
/// (task2097/75544 pi=316: 909px·pi=525: 826px, hwpx_sample2 pi=138:
/// 1042px — 한글 COM/PDF 정답지가 전부 존중을 요구한다).
fn page_holds_only_fresh_table_continuation(st: &TypesetState, paragraphs: &[Paragraph]) -> bool {
    const FRESH_CONTINUATION_PAGE_MAX_FILL_RATIO: f64 = 0.30;
    if st.current_items.is_empty() {
        return false;
    }
    if st.current_height > st.available_height() * FRESH_CONTINUATION_PAGE_MAX_FILL_RATIO {
        return false;
    }
    let mut has_continuation = false;
    for item in &st.current_items {
        match item {
            PageItem::PartialTable {
                is_continuation, ..
            } if *is_continuation => has_continuation = true,
            PageItem::FullParagraph { para_index }
            | PageItem::PartialParagraph { para_index, .. } => {
                let empty_only = paragraphs
                    .get(*para_index)
                    .is_some_and(|p| p.text.trim().is_empty() && p.controls.is_empty());
                if !empty_only {
                    return false;
                }
            }
            _ => return false,
        }
    }
    has_continuation
}

fn para_has_visible_text(para: &Paragraph) -> bool {
    para.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}')
}

fn para_has_non_whitespace_text(para: &Paragraph) -> bool {
    para.text
        .chars()
        .any(|c| c > '\u{001F}' && c != '\u{FFFC}' && !c.is_whitespace())
        || crate::renderer::is_unstored_whitespace_object_host(para)
}

fn take_strict_plain_text_fit_after_empty_host_float_once(
    pending: &mut bool,
    para: &Paragraph,
) -> bool {
    if !*pending || !para_has_non_whitespace_text(para) || !para.controls.is_empty() {
        return false;
    }
    *pending = false;
    true
}

fn paragraph_page_end_fit_height(
    total_height: f64,
    height_for_fit: f64,
    require_full_advance: bool,
) -> f64 {
    if require_full_advance {
        total_height.max(height_for_fit)
    } else {
        height_for_fit
    }
}

fn para_line_spacing_px(para: &Paragraph, dpi: f64) -> f64 {
    para.line_segs
        .last()
        .filter(|seg| seg.line_spacing > 0)
        .map(|seg| hwpunit_to_px(seg.line_spacing, dpi))
        .unwrap_or(0.0)
}

fn has_following_non_positive_visible_float(para: &Paragraph, control_index: usize) -> bool {
    para.controls
        .iter()
        .skip(control_index + 1)
        .any(|ctrl| match ctrl {
            Control::Table(table) => {
                is_para_topbottom_float(&table.common)
                    && signed_hwpunit(table.common.vertical_offset) <= 0
            }
            _ => false,
        })
}

fn para_is_non_tac_overlay_table_anchor(para: &Paragraph) -> bool {
    !para_has_non_whitespace_text(para)
        && para.controls.iter().any(|ctrl| {
            matches!(
                ctrl,
                Control::Table(table)
                    if !table.common.treat_as_char
                        && matches!(
                            table.common.text_wrap,
                            crate::model::shape::TextWrap::InFrontOfText
                                | crate::model::shape::TextWrap::BehindText
                        )
            )
        })
}

fn para_is_empty_topbottom_table_anchor(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para
            .controls
            .iter()
            .any(|ctrl| matches!(ctrl, Control::Table(t) if is_para_topbottom_float(&t.common)))
}

/// native HWP5의 그림 표 뒤에 붙은 빈 문단 중, 저장 vpos가 표의 실제 paint span 안에
/// 들어가는 것은 본문 줄이 아니라 그림 위치를 유지하는 guide line이다.
///
/// 이 fixture의 p182 `그림 67`은 빈 host 2×1 RowBreak 표 뒤에 같은 PS의 빈 line 다섯
/// 개를 남긴다. 표는 이미 선언 높이만큼 흐름을 소비했으므로 guide line까지 다시
/// advance하면 다음 두 본문 문단이 p183으로 밀린다. 일반 빈 줄은 의도된 간격일 수
/// 있으므로, native HWP5·empty host·positive offset·2×1 figure table·동일 PS·표 span
/// 내부라는 저장 계약이 모두 있을 때만 숨긴다.
fn native_hwp5_figure_table_overlay_guide_empty(
    para_idx: usize,
    para: &Paragraph,
    paragraphs: &[Paragraph],
) -> bool {
    if para.controls.is_empty()
        && !para_has_visible_text(para)
        && para.column_type == ColumnBreakType::None
    {
        let Some(guide_vpos) = para
            .line_segs
            .iter()
            .find(|seg| !is_synthetic_line_seg(seg))
            .map(|seg| seg.vertical_pos)
        else {
            return false;
        };
        let Some((_, host)) = (0..para_idx).rev().find_map(|idx| {
            let candidate = paragraphs.get(idx)?;
            (!candidate.controls.is_empty() || para_has_visible_text(candidate))
                .then_some((idx, candidate))
        }) else {
            return false;
        };
        if host.para_shape_id != para.para_shape_id || para_has_visible_text(host) {
            return false;
        }
        let Some((anchor_vpos, table)) = host
            .line_segs
            .iter()
            .find(|seg| !is_synthetic_line_seg(seg))
            .map(|seg| seg.vertical_pos)
            .and_then(|anchor_vpos| {
                host.controls.iter().find_map(|control| match control {
                    Control::Table(table)
                        if !table.common.treat_as_char
                            && is_para_topbottom_float(&table.common)
                            && matches!(
                                table.layout_page_break(),
                                crate::model::table::TablePageBreak::RowBreak
                            )
                            && table.row_count == 2
                            && table.col_count == 1
                            && table.cells.len() == 2
                            && signed_hwpunit(table.common.vertical_offset) > 0
                            && table.cells.first().is_some_and(|cell| {
                                cell.paragraphs.iter().any(|cell_para| {
                                    cell_para.controls.iter().any(|control| {
                                        matches!(control, Control::Picture(_) | Control::Shape(_))
                                    })
                                })
                            }) =>
                    {
                        Some((anchor_vpos, table))
                    }
                    _ => None,
                })
            })
        else {
            return false;
        };
        let table_bottom = anchor_vpos
            .saturating_add(signed_hwpunit(table.common.vertical_offset).max(0))
            .saturating_add(table.common.height.min(i32::MAX as u32) as i32);
        return guide_vpos >= anchor_vpos && guide_vpos < table_bottom;
    }
    false
}

/// [Task #1863] 텍스트 없이 TAC 표만 담은 문단 — 시각적으로 단독 표 줄.
/// 빈 앵커 TopAndBottom 표 뒤에 이런 문단이 오면 표-표 스택이므로 앵커의
/// host_line_spacing 이 표 사이 시각 간격이다 (#1133 과 동일 본질).
fn para_is_empty_tac_table_anchor(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para
            .controls
            .iter()
            .any(|ctrl| matches!(ctrl, Control::Table(t) if t.common.treat_as_char))
}

fn para_has_visible_text_or_equation(para: &Paragraph) -> bool {
    para_has_visible_text(para)
        || para
            .controls
            .iter()
            .any(|c| matches!(c, Control::Equation(eq) if eq.common.treat_as_char))
}

fn para_has_visible_text_and_treat_as_char_equation(para: &Paragraph) -> bool {
    para_has_visible_text(para)
        && para
            .controls
            .iter()
            .any(|c| matches!(c, Control::Equation(eq) if eq.common.treat_as_char))
}

/// HWPX가 자동으로 만드는 미주 제목은 자동번호 컨트롤과 짧은 답 표식만 가진다.
/// 리터럴 문항명이 남은 HWP5 제목과 구별해, 단 하단에서 제목만 고립시키지 않는다.
fn para_is_short_auto_endnote_marker(para: &Paragraph) -> bool {
    para.text
        .chars()
        .filter(|c| *c > '\u{001F}' && *c != '\u{FFFC}' && !c.is_whitespace())
        .count()
        <= 1
        && para.controls.iter().any(|control| {
            matches!(
                control,
                Control::AutoNumber(number)
                    if number.number_type == crate::model::control::AutoNumberType::Endnote
            )
        })
}

fn is_treat_as_char_equation_control(ctrl: Option<&Control>) -> bool {
    matches!(ctrl, Some(Control::Equation(eq)) if eq.common.treat_as_char)
}

fn para_is_treat_as_char_picture_only(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para.controls.iter().any(|ctrl| match ctrl {
            Control::Picture(pic) => pic.common.treat_as_char,
            Control::Shape(shape) => shape.common().treat_as_char,
            _ => false,
        })
}

/// 문단의 가시 payload가 글자처럼 취급하는 그림/도형으로만 이뤄졌는가.
///
/// `para_is_treat_as_char_picture_only`는 기존 조판 경로를 위해 TAC 그림이 **하나라도** 있는
/// 텍스트 없는 문단을 가리킨다. 단일 단 저장 vpos-reset을 강제 분리하는 경우에는 표·수식처럼
/// 다른 컨트롤이 섞이면 안 되므로 더 좁은 판정이 필요하다.
fn para_has_only_treat_as_char_picture_or_shape(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && !para.controls.is_empty()
        && para.controls.iter().all(|ctrl| match ctrl {
            Control::Picture(pic) => pic.common.treat_as_char,
            Control::Shape(shape) => shape.common().treat_as_char,
            _ => false,
        })
}

fn para_has_treat_as_char_picture_or_shape(para: &Paragraph) -> bool {
    para.controls.iter().any(|ctrl| match ctrl {
        Control::Picture(pic) => pic.common.treat_as_char,
        Control::Shape(shape) => shape.common().treat_as_char,
        _ => false,
    })
}

/// 저장 HWP5 표 앞줄이 빈 앵커가 아니라 TAC 그림·도형이 소유한 줄인지 확인한다.
fn hwp5_tac_prefix_has_owned_object_line(para: &Paragraph, table_line: usize) -> bool {
    para.controls.iter().enumerate().any(|(index, control)| {
        let is_tac_object = match control {
            Control::Picture(picture) => picture.common.treat_as_char,
            Control::Shape(shape) => shape.common().treat_as_char,
            _ => false,
        };
        is_tac_object
            && crate::renderer::layout::control_line_seg_index(para, index)
                .is_some_and(|line| line < table_line)
    })
}

fn non_tac_picture_or_shape_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
    match ctrl {
        Control::Picture(pic) if !pic.common.treat_as_char => Some(&pic.common),
        Control::Shape(shape) if !shape.common().treat_as_char => Some(shape.common()),
        _ => None,
    }
}

fn para_has_non_tac_picture_or_shape(para: &Paragraph) -> bool {
    para.controls
        .iter()
        .any(|ctrl| non_tac_picture_or_shape_common(ctrl).is_some())
}

fn paper_overlay_object_bottom_abs_px(para: &Paragraph, dpi: f64) -> Option<f64> {
    if !crate::renderer::layout::para_is_floating_overlay_anchor(para) {
        return None;
    }

    let mut max_bottom: Option<f64> = None;
    for ctrl in &para.controls {
        let common = match ctrl {
            Control::Shape(shape) if !shape.common().treat_as_char => shape.common(),
            Control::Picture(pic) if !pic.common.treat_as_char => &pic.common,
            Control::Table(table) if !table.common.treat_as_char => &table.common,
            _ => continue,
        };
        if !matches!(common.vert_rel_to, crate::model::shape::VertRelTo::Paper) {
            continue;
        }

        let top_hu = signed_hwpunit(common.vertical_offset);
        let bottom_hu = top_hu
            .saturating_add(common.height as i32)
            .saturating_add(common.margin.bottom as i32);
        let bottom_px = hwpunit_to_px(bottom_hu, dpi);
        max_bottom = Some(max_bottom.map_or(bottom_px, |prev| prev.max(bottom_px)));
    }

    max_bottom
}

fn para_is_columndef_only_separator(para: &Paragraph) -> bool {
    para.text.trim().is_empty()
        && !para.controls.is_empty()
        && para
            .controls
            .iter()
            .all(|c| matches!(c, Control::ColumnDef(_)))
}

fn para_is_paper_page_square_empty_table_anchor(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para.controls.iter().any(|ctrl| {
            matches!(ctrl, Control::Table(table)
            if !table.common.treat_as_char
                && matches!(
                    table.common.text_wrap,
                    crate::model::shape::TextWrap::Square
                )
                && matches!(
                    table.common.vert_rel_to,
                    crate::model::shape::VertRelTo::Paper
                        | crate::model::shape::VertRelTo::Page
                ))
        })
}

fn para_is_pre_paper_page_square_table_scaffold(para_idx: usize, paragraphs: &[Paragraph]) -> bool {
    let Some(para) = paragraphs.get(para_idx) else {
        return false;
    };
    if para_has_visible_text(para)
        || !matches!(
            para.column_type,
            ColumnBreakType::Page | ColumnBreakType::Section
        )
        || !para.controls.iter().all(|ctrl| {
            matches!(
                ctrl,
                Control::SectionDef(_) | Control::ColumnDef(_) | Control::Bookmark(_)
            )
        })
    {
        return false;
    }

    let Some(next) = paragraphs
        .get(para_idx + 1)
        .filter(|next| para_is_paper_page_square_empty_table_anchor(next))
    else {
        return false;
    };
    // 원본 저장 사다리가 이 빈 문단을 지나며 앞으로 나아갔다면 한/글은 이 문단에 줄을
    // 줬다(표 앞 빈 줄도 본문 흐름을 차지한다). 그 경우는 스캐폴드로 감추지 않는다.
    // 합성 줄은 이 증거로 쓰지 않는다.
    !matches!(
        (para.line_segs.last(), next.line_segs.first()),
        (Some(own), Some(following))
            if own.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                && following.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                && following.vertical_pos > own.vertical_pos
    )
}

fn para_is_post_paper_page_square_table_scaffold(
    para_idx: usize,
    paragraphs: &[Paragraph],
) -> bool {
    let Some(para) = paragraphs.get(para_idx) else {
        return false;
    };
    if para_has_visible_text(para) {
        return false;
    }
    let empty_no_control_para =
        para.column_type == ColumnBreakType::None && para.controls.is_empty();
    let columndef_only_separator =
        para.column_type == ColumnBreakType::Column && para_is_columndef_only_separator(para);
    if !empty_no_control_para && !columndef_only_separator {
        return false;
    }

    paragraphs
        .get(para_idx.saturating_sub(1))
        .is_some_and(para_is_paper_page_square_empty_table_anchor)
        && paragraphs
            .get(para_idx + 1)
            .is_some_and(para_has_visible_text)
}

fn columndef_separator_between_floating_overlays(
    para_idx: usize,
    paragraphs: &[Paragraph],
) -> bool {
    let prev_overlay = (0..para_idx).rev().find_map(|idx| {
        let para = paragraphs.get(idx)?;
        if para.text.trim().is_empty()
            && (para.controls.is_empty() || para_is_columndef_only_separator(para))
        {
            return None;
        }
        Some(crate::renderer::layout::para_is_floating_overlay_anchor(
            para,
        ))
    });
    let next_overlay = paragraphs.iter().skip(para_idx + 1).find_map(|para| {
        if para.text.trim().is_empty()
            && (para.controls.is_empty() || para_is_columndef_only_separator(para))
        {
            return None;
        }
        Some(crate::renderer::layout::para_is_floating_overlay_anchor(
            para,
        ))
    });

    prev_overlay == Some(true) && next_overlay == Some(true)
}

fn non_tac_picture_or_shape_block_height_px(para: &Paragraph, dpi: f64) -> Option<f64> {
    let mut max_height = 0.0f64;
    let mut found = false;
    for ctrl in &para.controls {
        let Some(common) = non_tac_picture_or_shape_common(ctrl) else {
            continue;
        };
        let block_height_hu =
            common.height as i32 + common.margin.top as i32 + common.margin.bottom as i32;
        max_height = max_height.max(hwpunit_to_px(block_height_hu.max(1), dpi));
        found = true;
    }
    found.then_some(max_height)
}

fn non_tac_picture_or_shape_content_height_px(para: &Paragraph, dpi: f64) -> Option<f64> {
    let mut max_height = 0.0f64;
    let mut found = false;
    for ctrl in &para.controls {
        let Some(common) = non_tac_picture_or_shape_common(ctrl) else {
            continue;
        };
        max_height = max_height.max(hwpunit_to_px((common.height as i32).max(1), dpi));
        found = true;
    }
    found.then_some(max_height)
}

fn non_tac_square_picture_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
    let common = match ctrl {
        Control::Picture(pic) => Some(&pic.common),
        Control::Shape(shape) => {
            if let crate::model::shape::ShapeObject::Picture(pic) = shape.as_ref() {
                Some(&pic.common)
            } else {
                None
            }
        }
        _ => None,
    }?;
    (!common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square))
        .then_some(common)
}

/// [#6175] 비-TAC 어울림(Square) 개체의 공통 속성 — 그림뿐 아니라 묶음(GroupShape)
/// 등 모든 개체 종류를 받는다. 묶음 그림도 한컴에서는 같은 배제 밴드를 만든다.
fn non_tac_square_float_common(ctrl: &Control) -> Option<&crate::model::shape::CommonObjAttr> {
    let common = match ctrl {
        Control::Picture(pic) => Some(&pic.common),
        Control::Shape(shape) => Some(shape.common()),
        _ => None,
    }?;
    (!common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square))
        .then_some(common)
}

/// [#6175] 어울림 개체의 **자기 기하**만으로 유도되는 우측 밴드의 좌측 레인 폭.
///
/// 호스트 문단의 첫 줄이 전폭이면(그림이 그 줄보다 아래에서 시작하는 형상) 기존
/// arming 은 밴드를 못 만든다. 그러나 개체가 단 우단까지 닿는 문단/단 기준 개체라면
/// 옆으로 흐를 레인은 개체 자신의 `horizontal_offset` 이 그대로 규정한다 — 한컴이
/// 뒤따르는 문단의 `segment_width` 로 저장하는 값과 같은 수다(156518601 1쪽:
/// horzOffset 29138 = 저장 사다리 4줄 전부의 horzsize).
fn square_float_left_lane_width(para: &Paragraph, col_w_hu: i32) -> Option<i32> {
    use crate::model::shape::HorzRelTo;
    let mut floats = para.controls.iter().filter_map(non_tac_square_float_common);
    let common = floats.next()?;
    if floats.next().is_some() {
        return None;
    }
    if !matches!(common.horz_rel_to, HorzRelTo::Para | HorzRelTo::Column) {
        return None;
    }
    let lane = common.horizontal_offset as i32;
    let right_edge = lane
        .saturating_add(common.width as i32)
        .saturating_add(common.margin.right as i32);
    // 개체가 단 우단까지 닿아야 좌측 레인 하나로 정의된다. 가운데 놓인 개체는
    // 좌·우 두 레인을 만들므로 이 유도가 성립하지 않는다.
    (lane > 0 && lane < col_w_hu && right_edge >= col_w_hu - 200).then_some(lane)
}

/// NO_LS 문단의 Square 그림들을 페이지 공간 배제
/// 사각형으로 수집한다. 반환 튜플 = (x0, x1, flow_top, flow_bottom) — x 는 페이지 px,
/// y 는 단 공통 flow 좌표(px, 문단 상단 = flow_y 기준). Square 그림은 가로 오프셋으로
/// 앵커 단 밖(다른 단 위)에 놓일 수 있으므로 단이 아니라 페이지 공간으로 기억한다.
fn synth_square_wrap_rects(
    para: &Paragraph,
    anchor_col_x: f64,
    flow_y: f64,
    dpi: f64,
) -> Vec<(f64, f64, f64, f64)> {
    para.controls
        .iter()
        .filter_map(non_tac_square_picture_common)
        .filter_map(|cm| {
            let w = crate::renderer::hwpunit_to_px(cm.width as i32, dpi);
            let h = crate::renderer::hwpunit_to_px(cm.height as i32, dpi);
            if w < 8.0 || h < 8.0 {
                return None;
            }
            let ml = crate::renderer::hwpunit_to_px(cm.margin.left as i32, dpi);
            let mr = crate::renderer::hwpunit_to_px(cm.margin.right as i32, dpi);
            let mb = crate::renderer::hwpunit_to_px(cm.margin.bottom as i32, dpi);
            let x0 = anchor_col_x
                + crate::renderer::hwpunit_to_px(signed_hwpunit(cm.horizontal_offset), dpi)
                - ml;
            let x1 = x0 + ml + w + mr;
            let top = flow_y
                + crate::renderer::hwpunit_to_px(signed_hwpunit(cm.vertical_offset).max(0), dpi);
            let bottom = top + h + mb;
            Some((x0, x1, top, bottom))
        })
        .collect()
}

/// [#7665] 로컬로 다시 색인한 미주 측정 문단 중 **미주의 첫 문단**(번호 장식을 받는 새 문항
/// 제목)인 로컬 번호. 렌더 `LayoutEngine::endnote_note_first_paras` 와 같은 소유 경계
/// (`note_para_index == 0`)를 `HeightCursor` 측정 시뮬에도 싣는다.
fn endnote_first_local_paras(
    body_len: usize,
    endnote_sources: &[EndnoteParaSource],
    local_indices: &[(usize, usize)],
) -> std::sync::Arc<std::collections::HashSet<usize>> {
    std::sync::Arc::new(
        local_indices
            .iter()
            .filter(|(global, _)| {
                global
                    .checked_sub(body_len)
                    .and_then(|local| endnote_sources.get(local))
                    .is_some_and(|src| src.note_para_index == 0)
            })
            .map(|(_, local)| *local)
            .collect(),
    )
}

fn paragraph_by_global_index<'a>(
    body_paragraphs: &'a [Paragraph],
    endnote_paragraphs: &'a [Paragraph],
    para_index: usize,
) -> Option<&'a Paragraph> {
    if para_index < body_paragraphs.len() {
        body_paragraphs.get(para_index)
    } else {
        endnote_paragraphs.get(para_index - body_paragraphs.len())
    }
}

fn page_item_para_index(item: &PageItem) -> Option<usize> {
    match item {
        PageItem::FullParagraph { para_index }
        | PageItem::PartialParagraph { para_index, .. }
        | PageItem::Table { para_index, .. }
        | PageItem::PartialTable { para_index, .. }
        | PageItem::Shape { para_index, .. } => Some(*para_index),
        PageItem::EndnoteSeparator { .. } => None,
    }
}

pub(super) fn page_item_vpos_base(item: &PageItem, paragraphs: &[Paragraph]) -> Option<i32> {
    match item {
        PageItem::PartialParagraph {
            para_index,
            start_line,
            ..
        } => paragraphs
            .get(*para_index)
            .and_then(|para| para.line_segs.get(*start_line))
            .map(|seg| seg.vertical_pos),
        PageItem::FullParagraph { para_index }
        | PageItem::Table { para_index, .. }
        | PageItem::PartialTable { para_index, .. }
        | PageItem::Shape { para_index, .. } => paragraphs
            .get(*para_index)
            .and_then(|para| para.line_segs.first())
            .map(|seg| seg.vertical_pos),
        PageItem::EndnoteSeparator { .. } => None,
    }
}

fn square_picture_wrap_anchor_for_para(
    st: &TypesetState,
    body_paragraphs: &[Paragraph],
    para: &Paragraph,
    page_def: &PageDef,
) -> Option<crate::renderer::pagination::WrapAnchorRef> {
    if st.wrap_around_cs < 0 {
        return None;
    }

    let para_cs = para.line_segs.first().map(|s| s.column_start).unwrap_or(0);
    let para_sw = para
        .line_segs
        .first()
        .map(|s| s.segment_width as i32)
        .unwrap_or(0);
    let is_empty_para = para
        .text
        .chars()
        .all(|ch| ch.is_whitespace() || ch == '\r' || ch == '\n')
        && para.controls.is_empty();
    let any_seg_matches = para.line_segs.iter().any(|s| {
        s.column_start == st.wrap_around_cs && s.segment_width as i32 == st.wrap_around_sw
    });
    let body_w =
        (page_def.width as i32) - (page_def.margin_left as i32) - (page_def.margin_right as i32);
    let sw0_match = st.wrap_around_sw == 0 && is_empty_para && para_sw > 0 && para_sw < body_w / 2;

    let anchor_para = paragraph_by_global_index(
        body_paragraphs,
        &st.endnote_paragraphs,
        st.wrap_around_table_para,
    )?;
    let anchor_image_match = if st.wrap_around_cs == 0 {
        let body_left = page_def.margin_left as i32;
        let expected_cs_hu = anchor_para
            .controls
            .iter()
            .find_map(|ctrl| {
                non_tac_square_picture_common(ctrl).map(|common| {
                    common.horizontal_offset as i32
                        + common.width as i32
                        + 2 * common.margin.right as i32
                        - body_left
                })
            })
            .unwrap_or(0);
        expected_cs_hu > 0
            && (para_cs - expected_cs_hu).abs() < 200
            && para_sw > 0
            && para_cs + para_sw <= body_w + 200
    } else {
        false
    };
    let cs_only_match = st.wrap_around_any_seg && para_cs == st.wrap_around_cs && para_sw > 0;
    let matched = (para_cs == st.wrap_around_cs && para_sw == st.wrap_around_sw)
        || (any_seg_matches && (is_empty_para || st.wrap_around_any_seg))
        || sw0_match
        || anchor_image_match
        || cs_only_match;
    if !matched {
        return None;
    }

    anchor_para
        .controls
        .iter()
        .find_map(non_tac_square_picture_common)?;
    Some(crate::renderer::pagination::WrapAnchorRef {
        anchor_para_index: st.wrap_around_table_para,
        anchor_cs: st.wrap_around_cs,
        anchor_sw: st.wrap_around_sw,
        band_y_range: None,
    })
}

fn maybe_register_square_picture_wrap_anchor(
    st: &mut TypesetState,
    body_paragraphs: &[Paragraph],
    para: &Paragraph,
    para_index: usize,
    page_def: &PageDef,
) {
    if st.wrap_around_cs < 0 {
        return;
    }
    if let Some(anchor) = square_picture_wrap_anchor_for_para(st, body_paragraphs, para, page_def) {
        st.register_following_wrap_anchor(para_index, anchor);
    } else {
        st.finish_stored_wrap_matching();
        st.close_square_band();
    }
}

fn activate_square_picture_wrap_for_para(
    st: &mut TypesetState,
    para_index: usize,
    para: &Paragraph,
) {
    if !para
        .controls
        .iter()
        .any(|ctrl| non_tac_square_picture_common(ctrl).is_some())
    {
        return;
    }

    let anchor_cs = para.line_segs.first().map(|s| s.column_start).unwrap_or(0);
    let anchor_sw = para
        .line_segs
        .first()
        .map(|s| s.segment_width as i32)
        .unwrap_or(0);
    if anchor_cs > 0 || anchor_sw > 0 {
        st.arm_control_wrap(anchor_cs, anchor_sw, para_index, true);
    }
}

fn line_has_strict_equation_tac_control(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> bool {
    let Some(line) = comp.lines.get(line_idx) else {
        return false;
    };
    let start = line.char_start;
    let end = composed_line_char_end(comp, line_idx);
    end > start
        && comp.tac_controls.iter().any(|(pos, _, ci)| {
            *pos >= start && *pos < end && is_treat_as_char_equation_control(para.controls.get(*ci))
        })
}

fn line_is_leading_empty_equation_tac_guide(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> bool {
    let Some(line) = comp.lines.get(line_idx) else {
        return false;
    };
    let Some(next) = comp.lines.get(line_idx + 1) else {
        return false;
    };
    line.runs.is_empty()
        && line.char_start == next.char_start
        && !line_has_strict_tac_control(comp, line_idx)
        && line_has_strict_equation_tac_control(para, comp, line_idx + 1)
}

fn equation_only_tac_line_assignment(
    para: &Paragraph,
    comp: &ComposedParagraph,
) -> Option<Vec<usize>> {
    match equation_only_tac_line_assignment_with_storage(para, comp, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn equation_only_tac_line_assignment_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    comp: &ComposedParagraph,
    storage: &S,
) -> Result<Option<Vec<usize>>, S::Error> {
    let n_lines = comp.lines.len();
    if n_lines <= 1 || comp.tac_controls.is_empty() {
        return Ok(None);
    }
    if !comp.lines.iter().all(|line| line.runs.is_empty()) {
        return Ok(None);
    }
    let degenerate = comp
        .lines
        .windows(2)
        .any(|w| w[1].char_start <= w[0].char_start);
    if !degenerate {
        return Ok(None);
    }

    let mut assign = storage.filled(comp.tac_controls.len(), n_lines - 1)?;
    let mut line_idx = 0usize;
    let mut tac_idx = 0usize;
    while tac_idx < comp.tac_controls.len() {
        let pos = comp.tac_controls[tac_idx].0;
        while line_idx < n_lines && comp.lines[line_idx].char_start < pos {
            line_idx += 1;
        }

        let tac_start = tac_idx;
        while tac_idx < comp.tac_controls.len() && comp.tac_controls[tac_idx].0 == pos {
            tac_idx += 1;
        }
        let tac_count = tac_idx - tac_start;

        let line_start = line_idx;
        while line_idx < n_lines && comp.lines[line_idx].char_start == pos {
            line_idx += 1;
        }
        let line_candidates: Vec<usize> = storage.collect(line_start..line_idx)?;
        let filtered_candidates: Vec<usize> = storage.collect(
            line_candidates
                .iter()
                .copied()
                .filter(|idx| !line_is_leading_empty_equation_tac_guide(para, comp, *idx)),
        )?;
        let line_targets = if tac_count > 1 && line_candidates.len() >= tac_count {
            // 같은 char_start에 여러 TAC 수식이 있고 저장 LINE_SEG도 같은 수만큼 있으면
            // 선행 빈 guide 줄도 한컴의 물리 수식 줄로 보존한다.
            &line_candidates
        } else if filtered_candidates.is_empty() {
            &line_candidates
        } else {
            &filtered_candidates
        };

        for offset in 0..tac_count {
            assign[tac_start + offset] = if line_targets.is_empty() {
                line_start.min(n_lines - 1)
            } else {
                line_targets[offset.min(line_targets.len() - 1)]
            };
        }
    }

    Ok(Some(assign))
}

fn tac_control_indices_for_line(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> Vec<usize> {
    match tac_control_indices_for_line_with_storage(
        para,
        comp,
        line_idx,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn tac_control_indices_for_line_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    storage: &S,
) -> Result<Vec<usize>, S::Error> {
    let Some(line) = comp.lines.get(line_idx) else {
        return Ok(Vec::new());
    };
    if comp.tac_controls.is_empty() {
        return Ok(Vec::new());
    }

    if let Some(assign) =
        crate::renderer::composer::composed_tac_line_assignment_with_storage(para, comp, storage)?
    {
        return storage.collect(
            assign
                .into_iter()
                .filter_map(|(ci, owner)| (owner == line_idx).then_some(ci)),
        );
    }

    if let Some(assign) = equation_only_tac_line_assignment_with_storage(para, comp, storage)? {
        return storage.collect(comp.tac_controls.iter().enumerate().filter_map(
            |(idx, (_, _, ci))| (assign.get(idx).copied() == Some(line_idx)).then_some(*ci),
        ));
    }

    if line.runs.is_empty() {
        let start = line.char_start;
        let end = comp
            .lines
            .get(line_idx + 1)
            .map(|next| next.char_start)
            .unwrap_or(usize::MAX);
        return storage.collect(
            comp.tac_controls
                .iter()
                .filter_map(|(pos, _, ci)| (*pos >= start && *pos < end).then_some(*ci)),
        );
    }

    let next_start = comp.lines.get(line_idx + 1).map(|next| next.char_start);
    let mut hits = Vec::new();
    let mut run_start = line.char_start;
    for (run_idx, run) in line.runs.iter().enumerate() {
        let run_len = run.text.chars().count();
        let run_end = run_start + run_len;
        let next_line_starts_at_run_end = next_start.is_some_and(|start| start == run_end);
        let allow_end_tac = run_idx == line.runs.len() - 1 && !next_line_starts_at_run_end;
        for (pos, _, ci) in &comp.tac_controls {
            if *pos >= run_start && (*pos < run_end || (allow_end_tac && *pos == run_end)) {
                storage.push(&mut hits, *ci)?;
            }
        }
        run_start = run_end;
    }
    Ok(hits)
}

fn line_has_tac_equation_control(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> bool {
    tac_control_indices_for_line(para, comp, line_idx)
        .iter()
        .any(|ci| is_treat_as_char_equation_control(para.controls.get(*ci)))
}

fn line_leading_tac_equation_count(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> usize {
    let Some(line_start) = comp.lines.get(line_idx).map(|line| line.char_start) else {
        return 0;
    };
    let line_controls = tac_control_indices_for_line(para, comp, line_idx);
    comp.tac_controls
        .iter()
        .filter(|(pos, _, ci)| {
            *pos == line_start
                && line_controls.contains(ci)
                && is_treat_as_char_equation_control(para.controls.get(*ci))
        })
        .count()
}

fn line_is_equation_tac_text_run_only(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> bool {
    if line_has_visible_text(comp, line_idx) {
        return false;
    }

    let line_controls = tac_control_indices_for_line(para, comp, line_idx);
    !line_controls.is_empty()
        && line_controls
            .iter()
            .all(|ci| is_treat_as_char_equation_control(para.controls.get(*ci)))
}

fn line_has_visible_text_or_tac_equation(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
) -> bool {
    line_has_visible_text(comp, line_idx) || line_has_tac_equation_control(para, comp, line_idx)
}

fn line_has_tac_control(para: &Paragraph, comp: &ComposedParagraph, line_idx: usize) -> bool {
    match line_has_tac_control_with_storage(para, comp, line_idx, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn line_has_tac_control_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    storage: &S,
) -> Result<bool, S::Error> {
    Ok(!tac_control_indices_for_line_with_storage(para, comp, line_idx, storage)?.is_empty())
}

fn line_tac_picture_or_shape_height(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    dpi: f64,
) -> Option<f64> {
    match line_tac_picture_or_shape_height_with_storage(
        para,
        comp,
        line_idx,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn line_tac_picture_or_shape_height_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    dpi: f64,
    storage: &S,
) -> Result<Option<f64>, S::Error> {
    Ok(
        tac_control_indices_for_line_with_storage(para, comp, line_idx, storage)?
            .iter()
            .find_map(|ci| {
                para.controls
                    .get(*ci)
                    .and_then(|ctrl| crate::renderer::tac_object_flow_height_px(ctrl, dpi))
            }),
    )
}

fn text_line_is_picture_lead_in(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    raw_lh: f64,
    max_fs: f64,
    dpi: f64,
) -> bool {
    match text_line_is_picture_lead_in_with_storage(
        para,
        comp,
        line_idx,
        raw_lh,
        max_fs,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn text_line_is_picture_lead_in_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    comp: &ComposedParagraph,
    line_idx: usize,
    raw_lh: f64,
    max_fs: f64,
    dpi: f64,
    storage: &S,
) -> Result<bool, S::Error> {
    if max_fs <= 0.0 || raw_lh <= max_fs * 2.0 {
        return Ok(false);
    }
    let Some(line) = comp.lines.get(line_idx) else {
        return Ok(false);
    };
    if line.runs.iter().all(|run| run.text.trim().is_empty())
        || line_tac_picture_or_shape_height_with_storage(para, comp, line_idx, dpi, storage)?
            .is_some()
    {
        return Ok(false);
    }
    let Some(next) = comp.lines.get(line_idx + 1) else {
        return Ok(false);
    };
    if !next.runs.iter().all(|run| run.text.trim().is_empty()) {
        return Ok(false);
    }
    Ok(
        line_tac_picture_or_shape_height_with_storage(para, comp, line_idx + 1, dpi, storage)?
            .map(|height| (raw_lh - height).abs() <= 8.0)
            .unwrap_or(false),
    )
}

/// 큰 inline `TopAndBottom` 그림 바로 앞 native HWP5 본문 문단의 physical-page
/// reset을 찾는다.
///
/// HWP5는 그림을 위한 다음 physical page의 본문 tail을 같은 paragraph의 LINE_SEG에
/// 보관할 수 있다. 일반 text reset은 다단 coordinate drift 또는 저장 시점의 잔재일 수
/// 있으므로 전역 page break 신호가 아니다. 다만 현재 쪽 하단의 visible text가 `vpos=0`
/// 으로 reset되고, 즉시 다음 문단이 page-top 부근에서 시작하는 큰 inline
/// TopAndBottom 그림 하나인 경우는 PDF의 본문-그림 owner 경계를 직접 표현한다.
///
/// 이 경로는 그림 앞 text tail만 PartialParagraph로 나누고 그림 자체는 다음 loop에서
/// normal flow로 배치한다. 따라서 Square/비-TAC float, 표, 각주, 작은 inline object 및
/// successor가 없는 일반 reset에는 적용하지 않는다.
fn native_hwp5_text_reset_before_large_tac_topbottom_picture_break_line(
    st: &TypesetState,
    para: &Paragraph,
    fmt: &FormattedParagraph,
    paragraphs: &[Paragraph],
    para_idx: usize,
    dpi: f64,
) -> Option<usize> {
    // [#5128] HWP5-origin HWPX 도 원본 HWP5 와 같은 저장 pagination 을 쓴다.
    // hwp5_stored_pagination_layout() 만 보면 스펙 문서 문단 84 앞 TAC 그림 분할이
    // 빠져 69→68 이 된다.
    if !st.profile.hwp5_stored_pagination_layout()
        || st.col_count != 1
        || st.current_footnote_height > 0.0
        || st.current_items.is_empty()
        || st.current_height < st.layout.body_area.height * 0.60
        || !para.controls.is_empty()
        || !para_has_visible_text(para)
        || fmt.line_heights.len() < 2
        || para.line_segs.len() < fmt.line_heights.len()
    {
        return None;
    }

    let next_para = paragraphs.get(para_idx + 1)?;
    if next_para.controls.len() != 1
        || next_para.line_segs.len() != 1
        || para_has_visible_text(next_para)
        || !para_controls_only_tac_topbottom_objects(next_para)
    {
        return None;
    }
    let next_line = next_para.line_segs.first()?;
    if is_synthetic_line_seg(next_line)
        || !(0..=8_000).contains(&next_line.vertical_pos)
        || hwpunit_to_px(next_line.line_height, dpi) < st.layout.body_area.height * 0.15
    {
        return None;
    }

    para.line_segs[..fmt.line_heights.len()]
        .windows(2)
        .enumerate()
        .find_map(|(prev_idx, pair)| {
            let (prev, next) = (&pair[0], &pair[1]);
            if is_synthetic_line_seg(prev)
                || is_synthetic_line_seg(next)
                || prev.vertical_pos <= 0
                || next.vertical_pos != 0
            {
                return None;
            }
            (hwpunit_to_px(prev.vertical_pos.saturating_add(prev.line_height), dpi)
                >= st.layout.body_area.height * 0.70)
                .then_some(prev_idx + 1)
        })
}

/// native HWP5/HWPX의 2행 그림+caption RowBreak 표인지 판별한다.
///
/// 그림을 첫 행에, caption을 둘째 행에 저장한 표는 현재 페이지의 기존 각주 위에
/// 실제로 들어가도 일반 다행 표와 같은 clean-defer gate를 타기 쉽다. 일반 요구사항
/// 표와 rowspan 표의 이월 계약은 건드리지 않기 위해, 이 구조만 별도 near-fit 보정의
/// 후보로 식별한다.
fn is_two_row_picture_caption_rowbreak_table(table: &crate::model::table::Table) -> bool {
    if table.row_count != 2
        || table.col_count != 1
        || table.cells.len() != 2
        || table
            .cells
            .iter()
            .any(|cell| cell.col != 0 || cell.row > 1 || cell.row_span != 1 || cell.col_span != 1)
    {
        return false;
    }

    let has_picture = table.cells.iter().any(|cell| {
        cell.row == 0
            && cell.paragraphs.iter().any(|para| {
                para.controls
                    .iter()
                    .any(|control| matches!(control, Control::Picture(_)))
            })
    });
    let has_caption_text = table
        .cells
        .iter()
        .any(|cell| cell.row == 1 && cell.paragraphs.iter().any(para_has_visible_text));
    has_picture && has_caption_text
}

/// 빈 host의 저장 좌표를 그대로 쓸 수 있는 단일 그림 표인지 판별한다.
///
/// `TopAndBottom` 자체는 일반 CellBreak/RowBreak 데이터 표에도 사용된다. 선언 높이만
/// 예약하면 그 표의 실제 행·셀 조각을 건너뛰므로, raw page anchor 특례는 non-TAC 그림만
/// 담은 1×1 RowBreak 표로만 제한한다.
fn is_single_noninline_picture_table(table: &crate::model::table::Table) -> bool {
    if table.common.treat_as_char
        || table.row_count != 1
        || table.col_count != 1
        || table.cells.len() != 1
        || !matches!(
            table.layout_page_break(),
            crate::model::table::TablePageBreak::RowBreak
        )
    {
        return false;
    }

    let Some(cell) = table.cells.first() else {
        return false;
    };
    cell.row == 0
        && cell.col == 0
        && cell.row_span == 1
        && cell.col_span == 1
        && cell.paragraphs.len() == 1
        && cell.paragraphs.first().is_some_and(|cell_para| {
            cell_para.text.trim().is_empty()
                && cell_para.controls.len() == 1
                && matches!(
                    cell_para.controls.first(),
                    Some(Control::Picture(picture)) if !picture.common.treat_as_char
                )
        })
}

/// 일반 RowBreak 데이터 표가 raw page anchor 특례를 타지 않도록, 저장 좌표를
/// 신뢰할 수 있는 그림 표 구조만 통과시킨다.
///
/// 1×1 비-TAC 그림 표와 그림·caption을 행으로 분리한 2×1 표는 한컴이 empty host의
/// `LINE_SEG`에 물리 페이지 좌표를 남기는 형상이다. 후자의 내부 그림은 TAC여도
/// 표 자체가 비-TAC float이므로 허용한다. 그림이 아닌 단순 1×1 표는 별도의 선언
/// 높이 신뢰 판정을 통과한 native HWP5에서만 raw anchor를 허용한다.
// [#7203] `stored_ladder_leaves_object_room` 은 `renderer::stored_float_anchor` 가
// 정본이다 — 조판과 렌더가 같은 판정·같은 원점을 쓴다.
use crate::renderer::stored_float_anchor::{
    stored_ladder_leaves_object_room, stored_single_topbottom_top_px,
};

fn is_stored_anchor_picture_table(table: &crate::model::table::Table) -> bool {
    !table.common.treat_as_char
        && matches!(
            table.layout_page_break(),
            crate::model::table::TablePageBreak::RowBreak
        )
        && (is_single_noninline_picture_table(table)
            || is_two_row_picture_caption_rowbreak_table(table))
}

/// 1×1 RowBreak 표의 실측 높이가 선언 객체 높이와 같은 범위인지 판별한다.
///
/// 그림 표가 아니더라도 이 형상은 한컴이 empty host의 raw vpos에 직접 배치할 수
/// 있다. 단, 실제 셀 내용이 선언 높이보다 크게 팽창한 표는 이 경로에서 행 fragment가
/// 사라지므로, 선언 높이의 1.5배 이내일 때만 허용한다.
fn is_single_rowbreak_table_with_trustworthy_declared_height(
    table: &crate::model::table::Table,
    effective_height: f64,
    dpi: f64,
) -> bool {
    if table.common.treat_as_char
        || table.row_count != 1
        || table.col_count != 1
        || table.cells.len() != 1
        || !matches!(
            table.layout_page_break(),
            crate::model::table::TablePageBreak::RowBreak
        )
    {
        return false;
    }

    let Some(cell) = table.cells.first() else {
        return false;
    };
    if cell.row != 0 || cell.col != 0 || cell.row_span != 1 || cell.col_span != 1 {
        return false;
    }

    let declared_height = hwpunit_to_px(table.common.height as i32, dpi).max(0.0);
    declared_height > 0.0
        && effective_height <= declared_height * SINGLE_ROW_DECLARED_TRUST_MAX_RATIO
}

/// RowBreak 표의 특정 행 셀 안에 저장된 vpos reset이 있는지 판별한다.
///
/// 표 행 경계가 아니라 셀 내부 줄에서 `양수 vpos → 0 이하`로 되감긴 경우는 해당
/// cell tail이 다음 물리 페이지에서 이어진다는 저장 frame 신호다. HWP와 HWPX의
/// 원본 `lineSeg` 모두에 같은 방식으로 적용된다.
fn rowbreak_row_has_internal_saved_vpos_reset(
    table: &crate::model::table::Table,
    row: usize,
) -> bool {
    table
        .cells
        .iter()
        .filter(|cell| cell.row as usize == row)
        .any(cell_has_internal_saved_vpos_reset)
}

/// 셀 안의 저장 줄 사이에서 `양수 vpos → 0 이하` 되감김이 있는지 판별한다.
fn cell_has_internal_saved_vpos_reset(cell: &crate::model::table::Cell) -> bool {
    // 저장된 물리 page reset은 cell paragraph 경계에서 시작할 수도 있다. 각
    // paragraph 안의 `windows(2)`만 보면 `<OPTN>` 다음 `간 특수 검사`처럼
    // p[n]의 마지막 LINE_SEG → p[n+1]의 첫 LINE_SEG reset을 놓친다.
    let mut previous_vpos = None;
    for para in &cell.paragraphs {
        for seg in para
            .line_segs
            .iter()
            .filter(|seg| !is_synthetic_line_seg(seg))
        {
            if previous_vpos.is_some_and(|previous| previous > 0 && seg.vertical_pos <= 0) {
                return true;
            }
            previous_vpos = Some(seg.vertical_pos);
        }
    }
    false
}

/// [#7288] «쪽 경계에서» 값 0 «나누지 않음» 의 **원자 규칙**을 이 표에 걸 수 있는가.
///
/// 값의 뜻은 한/글 정본 실측으로 고정했다. 한/글 13.0 이 같은 원문을 두 형식으로 저장한
/// 쌍둥이(`samples/2025 행정업무운영 편람(최종).hwp` / `.hwpx`)에서 표별 분포가 양쪽
/// 일치해(45 / 4 / 274) HWP5 `HWPTAG_TABLE` bit 0~1 의 `0/1/2` 가 HWPX
/// `pageBreak="NONE"/"TABLE"/"CELL"` 에 대응하는 것이 실측으로 잠긴다. rhwp 의 enum
/// 이름(`CellBreak`=1 · `RowBreak`=2)은 이 뜻과 반대로 읽히니 이름으로 판단하지 않는다.
///
/// 한/글은 이 표를 쪽 경계에서 나누지 않고 통째로 다음 쪽에 놓는다 — 저장소 정본
/// `pdf/text_footnote_tail_overpagination-2024.pdf` 62·63쪽이 7x7 `NONE` 표 둘을 각각
/// 한 쪽에 통째로 담고, 정본 51문서 교차 확인에서 `NONE` 표 21건 중 쪽을 넘긴 사례는 0건이다.
///
/// 다만 **양수 세로 오프셋의 가시-host 자리차지 float** 은 제외한다. 그 갈래는 흐름을
/// 전진시키지 않고 배제 영역에만 밴드를 남기며(`signed_vertical_offset > 0`), 뒤 본문의
/// y 는 저장 사다리에서 온다. 두 좌표계가 아직 화해되지 않아(#7198 축) 표만 옮기면 글 위에
/// 표가 그려진다 — 1490000 149쪽 실측 겹침 134 -> 156. 오프셋 0 float 과 `treat_as_char`
/// 표는 흐름이 밴드를 실제로 소비하므로 해당 없다.
pub(in crate::renderer) fn none_table_is_atomic_here(table: &crate::model::table::Table) -> bool {
    matches!(
        table.layout_page_break(),
        crate::model::table::TablePageBreak::None
    ) && !(!table.common.treat_as_char
        && is_para_topbottom_float(&table.common)
        && signed_hwpunit(table.common.vertical_offset) > 0)
}

/// [#7288] «쪽 경계에서» 값 1 «셀 단위로 나눔» 의 **행 원자 규칙**을 이 표에 걸 수 있는가.
///
/// 값의 뜻과 enum 이름의 함정은 위 [`none_table_is_atomic_here`] 의 설명과 같다
/// (`CellBreak`=1 · `RowBreak`=2 로 이름이 뜻과 반대로 읽힌다).
///
/// 한/글은 값 1 표를 **행 경계에서만** 끊는다 — 행 안까지 자르지 않는다. 저장소 정본
/// `pdf/2025 행정업무운영 편람(최종)-hwp-2020.pdf` 158→159쪽은 40행 2열 값 1 표에서
/// 마지막 행이 괘선까지 닫히고 바닥에 빈 공간을 남긴 뒤 다음 쪽이 새 행으로 시작한다.
/// `pdf/issue6132/156482639_startup_ir_contest-2020.pdf` 5→6쪽도 항목 7 을 끝내고 6쪽을
/// 새 행(`8 안산 (주)오토노미아`)으로 시작한다.
///
/// 문단 기준 오프셋은 개체의 원점을 정하며 행 경계 분할 정책을 바꾸지 않는다.
/// 저장된 내부 쪽 재시작과 새 쪽에도 들어가지 않는 행의 불가피한 분할은
/// 소비 지점에서 실제 프레임·행 예산으로 별도 확인한다.
///
/// 조회만 한다 — 상태를 쓰지 않는다. 소비자는 `table/block/prepare.rs` 의 이월 게이트와
/// `table/scan/runner/row_step.rs` 의 행 내부 컷 게이트다.
pub(in crate::renderer) fn cell_unit_row_is_atomic_here(
    table: &crate::model::table::Table,
) -> bool {
    matches!(
        table.layout_page_break(),
        crate::model::table::TablePageBreak::CellBreak
    )
}

/// RowBreak 표 셀 안에 저장된 vpos reset이 있는지 판별한다.
fn rowbreak_table_has_internal_saved_vpos_reset(table: &crate::model::table::Table) -> bool {
    // [#7639] 행마다 전체 셀을 다시 거르지 않고 셀을 한 번만 훑는다(행×셀 → 셀).
    let row_count = table.row_count as usize;
    table
        .cells
        .iter()
        .any(|cell| (cell.row as usize) < row_count && cell_has_internal_saved_vpos_reset(cell))
}

pub(crate) fn missing_lineseg_trailing_line_break(
    para: &Paragraph,
    line_count: usize,
    current_height: f64,
    available: f64,
    trailing_line_spacing: f64,
    source_uses_inline_field_reset: bool,
    hwp3_converted_missing_lineseg: bool,
) -> Option<usize> {
    crate::renderer::pagination::missing_lineseg_fragment_boundary(
        para,
        line_count,
        current_height,
        available,
        trailing_line_spacing,
        source_uses_inline_field_reset,
        hwp3_converted_missing_lineseg,
    )
}

fn is_synthetic_line_seg(ls: &LineSeg) -> bool {
    ls.tag & 0x80000000 != 0
}

/// [#6409] HWPX 가 글자처럼 취급 표를 쪽높이급 **한 줄**로 저장했으면, leftover
/// 에 행 분할로 끼우지 않고 다음 쪽 상단에서 시작한다.
///
/// 원본 XML 의 vertpos=0 은 typeset 전에 누적 vpos 로 덮인다(3249937 신고서
/// 표 0 → 524475). 남는 신호는 단일 LINE_SEG 높이(vertsize=69344 ≈ 본문 92%).
/// 붙임4 표도 한 줄이지만 잔여에 통째로 들어가(762px < leftover) 그대로 둔다.
fn hwpx_stored_tac_table_starts_at_page_top(
    para: &Paragraph,
    table: &crate::model::table::Table,
    current_items_empty: bool,
    current_height: f64,
    body_available: f64,
    dpi: f64,
) -> bool {
    if current_items_empty || current_height < 1.0 || !table.common.treat_as_char {
        return false;
    }
    let segs: Vec<&LineSeg> = para
        .line_segs
        .iter()
        .filter(|seg| !is_synthetic_line_seg(seg))
        .collect();
    let Some(seg) = segs.first() else {
        return false;
    };
    if segs.len() != 1 {
        return false;
    }
    let stored_h = hwpunit_to_px(seg.line_height, dpi);
    stored_h >= body_available * 0.5 && current_height + stored_h > body_available
}

/// [#5941 축 B] `#5921` 완화를 걸어도 되는 쪽인가 — **지금 쪽이 사실상 비어 있는가**.
///
/// 리셋을 지켰을 때 거의 빈 쪽이 남는 형상에서는 한/글도 쪼개지 않는다. 반대로 쪽이 이미
/// 차 있으면 저장 리셋이 이긴다(아래 `native_near_top_reset` 결합부 주석 참조).
const NEAR_TOP_RESET_EMPTY_PAGE_FILL_RATIO: f64 = 0.10;

fn near_top_reset_page_is_barely_started(current_height: f64, available_height: f64) -> bool {
    available_height > 0.0
        && current_height <= available_height * NEAR_TOP_RESET_EMPTY_PAGE_FILL_RATIO
}

/// [#5921] stored near-top 리셋이 이번 쪽 잔여를 넘는가.
///
/// `native_near_top_reset` 은 저장 vpos≈sb 만 보고 쪽을 가른다. 잔여에
/// 문단(sb+저장 줄 높이)이 들어가면 한글은 같은 쪽에 붙인다
/// (`neartop_reset_sb2500.hwpx`: 잔여 80px > 필요 63px, 한글 2020 1쪽).
/// 과적 케이스(148753276 pi46, used 942>933.6)는 잔여가 없어 리셋이 유지된다.
fn native_near_top_reset_exceeds_remaining(
    para: &Paragraph,
    para_sb_hu: i32,
    current_height: f64,
    available_height: f64,
    dpi: f64,
) -> bool {
    let remaining = (available_height - current_height).max(0.0);
    let real_lines: Vec<&LineSeg> = para
        .line_segs
        .iter()
        .filter(|ls| !is_synthetic_line_seg(ls))
        .collect();
    if real_lines.is_empty() {
        return true;
    }
    let sb_px = hwpunit_to_px(para_sb_hu.max(0), dpi);
    let lines_px: f64 = real_lines
        .iter()
        .map(|ls| hwpunit_to_px(ls.line_height.max(0), dpi))
        .sum();
    sb_px + lines_px > remaining + 0.5
}

/// 어울림(비 `treat_as_char`) 개체를 문단이 품고 있는가.
///
/// 어울림 밴드 옆으로 흐르는 줄은 앞 문단과 같은 세로 위치를 정당하게 다시 쓰므로,
/// 저장된 vpos 충돌을 쪽 경계로 읽으면 안 되는 예외다.
fn para_has_floating_object(para: &Paragraph) -> bool {
    para.controls.iter().any(|c| {
        matches!(
            c,
            Control::Shape(_) | Control::Table(_) | Control::Picture(_) | Control::Equation(_)
        ) && !c.is_treat_as_char_object()
    })
}

/// 앞뒤 문단이 **둘 다** 단 맨 위(stored vpos 0)를 주장하는가 (#5907).
///
/// Task #321 의 단일 단 트리거는 직전 문단의 마지막 줄이 쪽 하단부에 있을 때
/// (`pv > 5000`) 만 저장 리셋을 인정한다. 그런데 한/글은 쪽 하나에 짧은 문단
/// 하나만 올린 뒤 쪽을 넘기기도 하고, 그때 직전 문단의 vpos 는 0 이라 트리거가
/// 침묵한다 — 세 문단이 각각 한 쪽씩 차지하는 `samples/p122.hwp` 가 그 예다.
///
/// 이 규칙은 본문 텍스트의 일반적인 0-vpos 연속에는 적용하지 않는다. `p122`처럼
/// 양쪽 텍스트는 비어 있지만 구역/글자처럼 개체 컨트롤을 단독으로 가진 문단이 다시
/// 0 에서 시작하면, 그 컨트롤 앵커는 앞 쪽의 흐름과 같은 단에 함께 놓일 수 없다.
/// 넘침이 사유가 아니어서 rhwp 자체 흐름으로는 재현되지 않으므로 저장값을 그대로
/// 신뢰한다.
///
/// 오탐을 막기 위해 두 문단이 같은 단 기하(`column_start`/`segment_width`)를 쓰고,
/// 어울림 개체가 없으며, 양쪽 LINE_SEG 가 합성본이 아닌 경우로만 좁힌다.
fn stored_vpos_top_collision(prev: &Paragraph, curr: &Paragraph) -> bool {
    if para_has_floating_object(prev) || para_has_floating_object(curr) {
        return false;
    }
    // 일반 본문/생성 HWPX는 모든 문단의 LINE_SEG vpos를 0으로 저장할 수 있다. 그
    // 경우까지 쪽 경계로 읽으면 매 문단마다 새 쪽이 생긴다. p122의 증거는 양쪽 모두
    // 텍스트 없이 실제 컨트롤/빈 앵커를 단독으로 둔 경우이므로, 그 좁은 경우만
    // 인정한다. 컨트롤도 없는 trailing 빈 문단(#1663) 역시 저장 0이 남아 있을 뿐 쪽
    // 경계가 아니다.
    if para_has_visible_text(prev) || para_has_visible_text(curr) || prev.controls.is_empty() {
        return false;
    }
    let real = |ls: &&LineSeg| !is_synthetic_line_seg(ls);
    let (Some(prev_first), Some(prev_last), Some(curr_first)) = (
        prev.line_segs.iter().find(real),
        prev.line_segs.iter().rev().find(real),
        curr.line_segs.iter().find(real),
    ) else {
        return false;
    };

    // 저장된 조판에서 온 실제 줄 세그먼트여야 한다. 프로그램으로 만든 문단
    // (`LineSeg::default()` + line_height 만 채운 합성 IR)은 vpos·tag·segment_width 가
    // 모두 0 이라 "전부 단 맨 위" 로 보이므로, 그런 IR 에는 이 규칙을 적용하지 않는다.
    let parsed_seg = |ls: &LineSeg| {
        ls.tag & LineSeg::TAG_FIRST_SEGMENT != 0 && ls.segment_width > 0 && ls.line_height > 0
    };
    if !parsed_seg(prev_first) || !parsed_seg(prev_last) || !parsed_seg(curr_first) {
        return false;
    }

    // [#6087] 앞 문단의 저장 **전진이 0**(줄간격 0%: lh + ls ≤ 0)이면 쪽을
    // 점유하지 않으므로, 그 직후의 vpos=0 은 "다시 맨 위 주장"이 아니라 같은
    // 자리다 — 충돌 아님. 30307: pi=0(구역/단 정의, lh 1300 + ls −1300) 직후
    // pi=1 을 충돌로 읽어 완전한 빈 1쪽을 만들었다(한글 13쪽 vs 14쪽). p122
    // 증거(전진 1600/22838 문단들의 연쇄 단독 쪽)는 전진 > 0 이라 불변.
    if prev_last.line_height.saturating_add(prev_last.line_spacing) <= 0 {
        return false;
    }

    // 앞 문단이 통째로 단 맨 위 한 줄에 있었고(첫 줄·마지막 줄 모두 vpos 0),
    // 0 보다 아래에서 끝났는데 다음 문단이 다시 맨 위를 주장한다.
    prev_first.vertical_pos == 0
        && prev_last.vertical_pos == 0
        && curr_first.vertical_pos == 0
        && prev_last.column_start == curr_first.column_start
        && prev_last.segment_width == curr_first.segment_width
}

/// [#6342] 쪽을 거의 채운 TAC 자리차지 표 뒤의 짧은 붙임 두 줄은 잔여 칸에
/// 한 줄만 끼워 넣지 않고 다음 쪽으로 함께 넘긴다.
///
/// `36385445` 결재문서: 4×1 단 기준 TAC 표 899.5px / 본문 952.5px 뒤에 붙임
/// 28.8+28.8px 가 온다. 한글은 둘 다 2쪽에 둔다. 첫 줄만 잔여 53px 에 넣으면
/// used=964.3 으로 넘친다. 모든 원본 HWPX TAC 표에 열면 #3931 편람 쪽수와
/// #6044 상자 간격이 깨지므로, 4×1 단 기준·40px 미만 두 줄만 연다.
fn original_hwpx_tac_filled_page_keeps_short_trail(
    original_hwpx: bool,
    table: &crate::model::table::Table,
    table_height_px: f64,
    body_height_px: f64,
    remaining_px: f64,
    current_h: f64,
    next_h: f64,
) -> bool {
    use crate::model::shape::{HorzRelTo, TextWrap};
    original_hwpx
        && table.common.treat_as_char
        && matches!(table.common.text_wrap, TextWrap::TopAndBottom)
        && matches!(table.common.horz_rel_to, HorzRelTo::Column)
        && table.row_count == 4
        && table.col_count == 1
        && body_height_px > 0.0
        && table_height_px >= body_height_px * 0.90
        && current_h > 0.0
        && next_h > 0.0
        && current_h < 40.0
        && next_h < 40.0
        && remaining_px + 0.5 >= current_h
        && remaining_px + 0.5 < current_h + next_h
}

/// Returns only the measured-row slack that remains below a saved native
/// RowBreak first-fragment flow frame. Both bounds are absolute page flow
/// coordinates; host-before spacing and paint-only vertical insets are not
/// part of the stored flow frame.
fn saved_rowbreak_first_fragment_flow_overflow_allowance(
    declared_height: u32,
    outer_table_owns_row_geometry: bool,
    source_flow_bottom: f64,
    fragment_flow_bottom: f64,
) -> f64 {
    const SOURCE_FRAME_EPSILON_PX: f64 = 0.5;
    if declared_height == 0
        || declared_height > i32::MAX as u32
        || !outer_table_owns_row_geometry
        || !source_flow_bottom.is_finite()
        || !fragment_flow_bottom.is_finite()
        || source_flow_bottom <= 0.0
        || fragment_flow_bottom <= 0.0
        || source_flow_bottom > fragment_flow_bottom + SOURCE_FRAME_EPSILON_PX
    {
        return 0.0;
    }

    (fragment_flow_bottom - source_flow_bottom).max(0.0)
}

/// [#6123] 저장 프레임 바닥이 **저장 행 경계**와 같다고 볼 수 있는 허용치.
/// 저장 높이는 HWPUNIT→px 변환에서 행마다 반올림 오차를 남기므로 행 수에
/// 비례하는 몫을 더해 쓴다(호출부).
const SAVED_FRAME_ROW_END_STORED_TOLERANCE_PX: f64 = 1.0;

/// 저장된 첫 RowBreak 조각 높이에 가장 가까운 행 경계를 찾는다.
///
/// 저장 프레임의 남은 물리 공간은 글꼴 측정 drift를 흡수할 수 있지만, 다음 행까지
/// 허용하는 일반 여유값은 아니다. 동률이면 앞 경계를 택해 다음 행을 앞당겨
/// 소유하지 않는다.
fn nearest_saved_rowbreak_frame_row_end(
    frame_height: f64,
    row_heights: &[f64],
    stored_row_heights: &[f64],
    cell_spacing: f64,
) -> Option<usize> {
    if !frame_height.is_finite() || frame_height <= 0.0 {
        return None;
    }

    let mut bottom = 0.0;
    let mut nearest: Option<(usize, f64, f64)> = None;
    for (row, height) in row_heights.iter().enumerate() {
        if row > 0 {
            bottom += cell_spacing;
        }
        bottom += height;
        let distance = (bottom - frame_height).abs();
        if nearest.is_none_or(|(_, best, _)| distance < best) {
            nearest = Some((row + 1, distance, bottom));
        }
    }
    let (end_row, _, row_bottom) = nearest?;

    // [#6123] 프레임이 그 행 경계를 **닿지 못하면** 그 행을 소유하지 않는다.
    //
    // 최근접 스냅에는 거리 제한이 없어, 프레임 바닥이 어떤 행 한복판에 떨어져도
    // 그 행의 끝으로 끌려갔다 — 3112461 7쪽은 프레임 388.0px 이 행 1(측정
    // 36.0~573.1)의 65% 지점인데 행 끝(573.1)으로 스냅돼 그 행을 통째로 앞
    // 쪽에 얹었고, 표가 본문 하단을 174px 넘겼다. 한글은 그 행을 줄 단위로
    // 가른다.
    //
    // 프레임이 경계를 **넘어서는**(frame ≥ 누적) 경우는 종전 그대로다 — 21298295
    // 별표 5 는 프레임이 행 13 경계를 22.6px 지나며, 그 초과는 다음 행의 측정↔
    // 저장 drift 다. 반대로 **모자라는** 쪽은 그 행을 다 담지 못했다는 뜻이므로,
    // 흡수 가능한 drift(관련 행들의 |측정 − 저장| 합 + 행별 px 변환 반올림)
    // 안에서만 허용한다. 저장 높이를 못 읽는 행은 그 행의 측정 높이가 곧 상한이
    // 되어 종전 스냅이 그대로 남는다.
    let shortfall = row_bottom - frame_height;
    if shortfall <= 0.0 {
        return Some(end_row);
    }
    // 모자란 몫이 **조각이 될 수 없는 크기**(`MIN_TOP_KEEP_PX`)면 그 잔여를 다음
    // 쪽으로 옮길 수 없으므로 행을 통째로 두는 것이 맞다 — 1790387 PrEP 보고서는
    // 프레임이 행 3 경계에 16.8px 못 미친다. 그보다 크게 모자라면 흡수 가능한
    // drift(관련 행들의 |측정 − 저장| 합 + 행별 px 변환 반올림) 안에서만 허용한다.
    // 저장 높이를 못 읽는 행은 그 행의 측정 높이가 곧 상한이 되어 종전 스냅이
    // 그대로 남는다.
    let drift_budget: f64 = row_heights
        .iter()
        .take(end_row)
        .enumerate()
        .map(|(row, measured)| {
            let stored = stored_row_heights.get(row).copied().unwrap_or(0.0);
            if stored > 0.0 && stored.is_finite() {
                (measured - stored).abs()
            } else {
                *measured
            }
        })
        .sum::<f64>()
        + SAVED_FRAME_ROW_END_STORED_TOLERANCE_PX * end_row as f64;
    (shortfall <= drift_budget.max(MIN_TOP_KEEP_PX)).then_some(end_row)
}

/// Visible host text that is structurally a numbered table caption.
///
/// A positive table offset alone does not make the host a caption: ordinary
/// section headings such as `1. 편성기준` can share that geometry (#2097).
/// Restrict the native pre-emit path to the explicit `표 N`/`Table N` form
/// observed in Hancom's visible-host captions (policy tables 26--28).
fn visible_host_is_numbered_table_caption(para: &Paragraph) -> bool {
    let has_table_number_control = para.controls.iter().any(|control| {
        matches!(
            control,
            Control::AutoNumber(number)
                if number.number_type == crate::model::control::AutoNumberType::Table
        ) || matches!(
            control,
            Control::NewNumber(number)
                if number.number_type == crate::model::control::AutoNumberType::Table
        )
    });
    if has_table_number_control {
        return true;
    }

    let text = para.text.trim_start();
    let suffix = if let Some(rest) = text.strip_prefix('표') {
        rest
    } else if text
        .get(.."Table".len())
        .is_some_and(|prefix| prefix.eq_ignore_ascii_case("Table"))
    {
        &text["Table".len()..]
    } else {
        return false;
    };

    suffix
        .trim_start()
        .chars()
        .next()
        .is_some_and(char::is_numeric)
}

/// Native HWP5 can encode a table title as visible text in the table's host
/// paragraph instead of as `Table::caption`.  When the stored host line fits
/// wholly inside the table's positive paragraph-relative offset, Hancom paints
/// that line in the offset lane before the first RowBreak fragment.  Deferring
/// every visible host until the terminal fragment moves such titles to the
/// following page (policy report table 27, p90 -> p91).
///
/// Keep this narrower than the generic visible-host path: a single table,
/// stored (non-synthetic) line geometry, native HWP5, and an offset at least as
/// tall as the complete stored host span.  A shorter offset denotes a genuine
/// post-table host (#1686), and co-anchored table stacks have separate ordering
/// rules (#2439).
fn native_hwp5_rowbreak_host_precedes_first_fragment(
    para: &Paragraph,
    table: &crate::model::table::Table,
) -> bool {
    if !para_has_non_whitespace_text(para)
        || !visible_host_is_numbered_table_caption(para)
        || !is_para_topbottom_float(&table.common)
        || !matches!(
            table.layout_page_break(),
            crate::model::table::TablePageBreak::RowBreak
        )
        || para
            .controls
            .iter()
            .filter(|control| matches!(control, Control::Table(_)))
            .count()
            != 1
    {
        return false;
    }

    let vertical_offset = signed_hwpunit(table.common.vertical_offset);
    if vertical_offset <= 0 {
        return false;
    }

    let mut stored = para
        .line_segs
        .iter()
        .filter(|seg| !is_synthetic_line_seg(seg) && seg.line_height > 0);
    let Some(first) = stored.next() else {
        return false;
    };
    let last = stored.next_back().unwrap_or(first);
    let stored_host_span = last
        .vertical_pos
        .saturating_sub(first.vertical_pos)
        .saturating_add(last.line_height)
        .max(0);

    stored_host_span > 0 && stored_host_span <= vertical_offset
}

/// [#2098] 쪽-하단 고정 틀(vert=쪽, valign=Bottom) 표의 빈 앵커 문단 — 저장 vpos=0 은
/// 쪽 기준 절대배치 산물이라 흐름 리셋(새 쪽) 신호가 아니다 (opengov 결재문서 계열
/// 36358528 pi8: 한글은 p1 하단 배치인데 리셋 오독으로 p2 단독 +1쪽). 앵커 배치는
/// page-bottom footer 경로가 배타영역 fit 으로 자체 판정하므로(침범 시 스스로 다음 쪽
/// 이동) 리셋 신호 제외가 과충전을 만들지 않는다.
fn para_is_page_bottom_fixed_table_anchor(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para
            .controls
            .iter()
            .any(|c| matches!(c, Control::Table(t) if is_page_bottom_fixed_float(&t.common)))
}

/// [#2137] 문단의 컨트롤이 전부 비-TAC 자리차지(TopAndBottom, vert=문단) 그림/도형
/// float 인가. 저장 page-last 증거가 있는 단일 줄 앵커는 개체를 하단 여백으로
/// 스필하는 것이 한컴 정합(156618554: 앵커 저장 경계 70000 ≤ 본문 70018HU, 한글
/// 1쪽 — 소형 글상자 49.8px 를 여백으로 흘림)이라 saved-bounds 신뢰(#2093)에
/// 편입한다. 대형 박스를 한컴이 다음 쪽으로 넘기는 케이스(#1027-E2, AI 184p)는
/// 앵커 저장 vpos 가 다음 쪽을 인코딩해 경계 fit 에서 자연 배제된다. 표 float 는
/// footer 로직 소관이라 제외.
fn para_controls_only_topbottom_floats(para: &Paragraph) -> bool {
    !para.controls.is_empty()
        && para.controls.iter().all(|c| match c {
            Control::Picture(p) => is_para_topbottom_float(&p.common),
            Control::Shape(s) => is_para_topbottom_float(s.common()),
            _ => false,
        })
}

/// [#2137] 단일 줄의 treat_as_char TopAndBottom 그림/도형만 가진 문단.
/// 한컴은 이런 소형 개체 줄을 쪽 하단 여백으로 스필해 현재 쪽에 유지한다
/// (156637323 pi=19 실측). 저장 page-last 증거와 결합해서만 신뢰한다 —
/// 대형 박스는 저장 vpos 가 다음 쪽을 인코딩해 bounds 검사에서 자연 배제
/// (#1027-E2 push 정합 유지).
fn para_controls_only_tac_topbottom_objects(para: &Paragraph) -> bool {
    use crate::model::shape::TextWrap;
    !para.controls.is_empty()
        && para.controls.iter().all(|c| match c {
            Control::Picture(p) => {
                p.common.treat_as_char && matches!(p.common.text_wrap, TextWrap::TopAndBottom)
            }
            Control::Shape(s) => {
                s.common().treat_as_char && matches!(s.common().text_wrap, TextWrap::TopAndBottom)
            }
            _ => false,
        })
}

/// [#6535 잔여] 문단이 **쪽 기준 앵커**(`vert_rel_to == Page`) 자리차지 블록을 품는가.
///
/// 그런 블록의 저장 `vertical_pos` 는 흐름 좌표가 아니라 **절대배치의 산물**이라 대개
/// `0` 이다(`#6535`). 그 `0` 을 "한컴이 여기서 쪽을 끊었다"는 리셋 신호로 읽으면, 남은
/// 자리에 들어가는 표가 혼자 새 쪽으로 밀려 본문 없는 쪽이 생긴다.
///
/// 실측 `36399617_결재문서본문_외부강의신고 결재신청.hwpx` (한/글 1쪽, rhwp 2쪽):
///
/// ```text
/// pi=15 까지 cur_h=639.0 / 본문 990.2  → 잔여 351.2
/// pi=16  text="끝."  Table wrap=TopAndBottom vrel=Page tac=false  h=22234(296.5px)
///        line_segs=[(vpos 0, lh 1200)]
/// → cv==0 && pv=46278>5000 이 리셋으로 읽혀 flush_column, 2쪽의 used=0.0px
/// ```
fn para_hosts_page_anchored_block(para: &Paragraph) -> bool {
    use crate::model::shape::{TextWrap, VertRelTo};
    let is_page_anchored_block = |common: &crate::model::shape::CommonObjAttr| {
        !common.treat_as_char
            && matches!(common.vert_rel_to, VertRelTo::Page)
            && matches!(common.text_wrap, TextWrap::TopAndBottom)
    };
    para.controls.iter().any(|c| match c {
        Control::Table(t) => is_page_anchored_block(&t.common),
        Control::Picture(p) => is_page_anchored_block(&p.common),
        Control::Shape(sh) => is_page_anchored_block(sh.common()),
        _ => false,
    })
}

fn paragraph_saved_vpos_reset_starts_new_page_after(
    current_para: &Paragraph,
    next_para: &Paragraph,
    col_count: u16,
    is_hwp3_variant: bool,
) -> bool {
    if para_is_page_bottom_fixed_table_anchor(next_para) {
        return false;
    }

    let next_first_vpos = next_para.line_segs.first().map(|s| s.vertical_pos);
    // [#8904] 되감김은 앞 문단 끝과 다음 문단 시작 사이의 **저장** 사실이다. 저장 줄이 없어
    // 줄을 합성한 글 문단은 저장 당시와 줄 나눔이 같다는 근거가 없으므로(익명화 등으로 글이
    // 바뀐 문단), 합성 줄 끝을 그 사실의 앞쪽으로 쓰지 않는다. 글이 없는 문단은 글자 모양이
    // 정하는 한 줄이라 합성 줄도 저장 당시와 같은 점유를 가진다.
    let curr_last_vpos = if para_has_visible_text(current_para) {
        current_para
            .line_segs
            .iter()
            .rev()
            .find(|s| !is_synthetic_line_seg(s))
            .map(|s| s.vertical_pos)
    } else {
        current_para.line_segs.last().map(|s| s.vertical_pos)
    };
    let multi_col = col_count > 1;
    let allowed_top_vpos = if is_hwp3_variant { 1500 } else { 0 };

    matches!((next_first_vpos, curr_last_vpos), (Some(nv), Some(cl))
        if (if multi_col { nv < cl } else { nv <= allowed_top_vpos }) && cl > 5000)
}

/// 저장 `vpos` 되돌아감을 쪽 경계로 인정하려면 쪽이 이만큼 차 있어야 한다 [#3837].
///
/// 쪽 중간에서 인정하면 한 문서 안에서 가드가 연쇄 발동해 쪽수가 늘어난다
/// (`156633519 산업활동동향`: pi 501개 이동 +3쪽). 이 조건 하나로 PI 코호트 회귀가
/// 2건에서 0건이 됐고, 50·75·90% 가 모두 같은 결과라 가장 조인 값을 쓴다.
/// [#6718] 저장 사다리가 지시한 쪽 경계를 "이 문단은 어차피 넘치지 않는다"로 걸러낼 때
/// 쓰는 반올림 여유. 27469 `pi=62` 는 7줄 합 246.4 vs 예산 247.2 로 **0.8px** 차이로
/// 들어가 사다리(@6)를 못 따랐다 — 그 0.8px 은 조판 차이가 아니라 계산 오차 규모다.
const LADDER_FIT_EPSILON_PX: f64 = 1.0;

const STORED_VPOS_REWIND_MIN_FILL: f64 = 0.90;

/// [#6132] 저장 vpos 초과가 이 문단을 **새 쪽에서 시작시키는가** — 세 신호를 함께 본다.
///
/// 단일 신호("저장 자리가 본문을 넘는다")만으로는 부족하다. 같은 형상이 문단을 쪽 안에
/// 그대로 두는 문서에도 흔하게 나온다(실측 후보: 2025 행정업무편람 26곳 · 2070
/// 시장구조조사 13곳 · 2019 벤처투자 3곳 · hwp3-sample16 10곳). 그래서 ① 표를 단 문단
/// ② 저장 자리가 본문 바닥을 **근소하게** 초과 ③ 다음 문단이 되감김 셋을 함께 요구한다.
///
/// 쪽 잔여 조건은 상태라 호출자가 소유한다 — 이 Query 는 문단과 좌표만 읽는다.
pub(in crate::renderer::typeset) fn stored_vpos_overflow_defers_paragraph(
    para: &Paragraph,
    next_para: Option<&Paragraph>,
    body_bottom_px: f64,
    dpi: f64,
) -> bool {
    let first_stored = |p: &Paragraph| {
        p.line_segs
            .iter()
            .find(|seg| !is_synthetic_line_seg(seg))
            .map(|seg| seg.vertical_pos)
    };
    let (Some(own), Some(next)) = (first_stored(para), next_para.and_then(first_stored)) else {
        return false;
    };
    let hosts_table = para
        .controls
        .iter()
        .any(|c| matches!(c, crate::model::control::Control::Table(_)));
    let own_px = hwpunit_to_px(own, dpi);
    let overflows_body_narrowly =
        own > 0 && own_px > body_bottom_px && own_px - body_bottom_px <= MIN_TOP_KEEP_PX;
    hosts_table && overflows_body_narrowly && next < own
}

/// 저장 `vpos` 가 되돌아가는 자리 — 한글이 거기서 쪽을 끊었다는 신호다 [#3837].
///
/// 기존 [`paragraph_saved_vpos_reset_starts_new_page_after`] 는 단일 단에서 `nv == 0`
/// 만 인정하고, 그마저 fit 완화에만 쓰인다(#418 회피). 여기서는 되돌아감 자체를 본다.
///
/// 판별력 실측(r29 `PI_MISMATCH` n=1 코호트 66건): 어긋난 항목의 36% 가 되돌아감인데,
/// 같은 문서 **다른 쪽**의 마지막 항목은 1,134개 중 2개(0.2%)뿐이다 — 180배 농축.
fn stored_vpos_rewinds(prev_vpos: Option<i32>, para: &Paragraph) -> bool {
    stored_vpos_rewinds_after(prev_vpos.map(|vpos| (vpos, vpos)), para)
}

/// [`stored_vpos_rewinds`] 의 앞 줄 `(시작, 아래끝)` 판 — 하한 `5000` 을 앞 줄이 차지한
/// 아래끝까지로 잰다. 되돌아감 자체는 새 줄이 앞 줄의 **시작**보다 위인 것 그대로다.
/// 쓰는 곳은 통째로 안 들어가는 문단의 쪽 경계뿐이다(#8805, `whole_fit`).
fn stored_vpos_rewinds_after(prev_line: Option<(i32, i32)>, para: &Paragraph) -> bool {
    let Some(nv) = para
        .line_segs
        .iter()
        .find(|s| !is_synthetic_line_seg(s))
        .map(|s| s.vertical_pos)
    else {
        return false;
    };
    // `cl > 5000` 은 기존 vpos-reset 가드와 같은 하한 — 쪽 상단 근처에서 시작한 항목을
    // 기준으로 삼으면 되돌아감이 아니라 정상 흐름을 끊는다.
    prev_line.is_some_and(|(start, bottom)| nv < start && start.max(bottom) > 5000)
}

/// 저장 사다리가 **쪽 위쪽 띠에서 다시 시작**하는가 — 쪽 경계 되감김의 표지.
///
/// [`stored_vpos_rewinds`] 는 값이 줄기만 하면 참이라 같은 쪽 안의 부분 후퇴도 포함한다.
/// 쪽을 실제로 넘긴 자리는 새 쪽 상단에서 다시 시작하므로, 앞 값에 쓰는 `> 5000` 의
/// 거울로 새 값에 `<= 5000`(= 66.7px @96dpi)을 요구한다.
fn stored_vpos_restarts_near_body_top(para: &Paragraph) -> bool {
    para.line_segs
        .iter()
        .find(|s| !is_synthetic_line_seg(s))
        .is_some_and(|s| s.vertical_pos <= 5000)
}

/// 저장 되감김 **직전 자리**가 지금 조판 위치와 같은가 — 그 쪽 경계가 이 쪽의 경계인가.
///
/// `stored_vpos_rewind_break` 의 기존 관문은 "쪽이 90% 이상 찼는가"(`STORED_VPOS_REWIND_MIN_FILL`)
/// 다. 그런데 한글은 **덜 찬 쪽도** 끊는다 — 다음 블록(그림·표)이 남은 여백에 안 들어가면
/// 그렇다. 그 결정이 바로 저장 사다리의 되감김이고, 채움률 관문이 그걸 막는다.
///
/// 채움률 대신 **위치 일치**를 본다. 되감김 직전 문단의 저장 끝(`vpos + line_height +
/// line_spacing`)이 지금 흐름 위치와 한 줄 안에서 같으면, 사다리가 말한 그 경계가 지금
/// 이 자리다. 어긋나면 사다리의 그 쪽과 지금 쪽이 다른 쪽이므로 경계를 빌려 쓰면 안 된다.
///
/// 1480000-201900042 실측(96dpi):
///
/// ```text
///   pi=132 저장끝 496.3px  →  pi=133(vpos 600) 조판 481.6px   Δ  14.7px  ← 같은 자리
///   pi=202 저장끝 886.3px  →  pi=203(vpos 600) 조판  12.8px   Δ 873.5px  ← 다른 쪽
/// ```
///
/// 앞쪽은 한/글도 거기서 끊고(정본 14쪽이 `최종안 제시 및 보고 자료` 로 시작), 뒤쪽은
/// 한/글이 쪽 중간에 둔다. 허용치는 그 문단 자신의 줄 전진폭이라 글꼴·크기에 따라 같이 큰다.
fn stored_rewind_boundary_matches_current_flow(
    paragraphs: &[Paragraph],
    para_idx: usize,
    current_items: &[PageItem],
    current_height_px: f64,
    dpi: f64,
) -> bool {
    let Some((owner, (stored_end_hu, advance_hu))) = paragraphs[..para_idx.min(paragraphs.len())]
        .iter()
        .enumerate()
        .rev()
        .find_map(|(owner, para)| {
            paragraph::stored_lines::stored_tail_end_and_advance_hu(para).map(|tail| (owner, tail))
        })
    else {
        return false;
    };
    // [#8786] 저장 끝과 현재 문단 사이에 재조판 줄(합성 줄)로 소비한 문단이 있으면 지금
    // 흐름 위치는 그 문단들의 재조판 높이를 담는다. 저장 끝은 그 앞 지점이라 같은 경계를
    // 가리키지 않는다(36431892 2쪽: 저장 끝 문단 15 = 817.9px, 재조판 문단 16·17 소비 뒤
    // 흐름 838.6px 이 한 줄 반 허용치 안에서 우연히 맞아 낡은 되감김이 쪽을 끊었다).
    if paragraphs[owner + 1..para_idx.min(paragraphs.len())]
        .iter()
        .any(|between| {
            !between.line_segs.is_empty() && crate::renderer::para_has_no_stored_line_segs(between)
        })
    {
        return false;
    }
    // 이전 물리 쪽의 저장 끝과 현재 쪽의 재조판 끝은 숫자가 같아도 같은 경계가 아니다.
    // 저장 끝을 제공한 실제 소유자가 현재 frame에서 소비됐는지 먼저 확인한다.
    if !current_items
        .iter()
        .any(|item| page_item_para_index(item) == Some(owner))
    {
        return false;
    }
    let stored_end_px = hwpunit_to_px(stored_end_hu, dpi);
    // 저장 줄과 실제 글꼴 측정의 차이가 한 줄보다 약간 커질 수 있다. #7333의
    // 38→39쪽 경계는 20.8px 차이로, 한 줄 공차 16px만으로는 실제 저장 쪽 경계를 놓쳤다.
    // 되감김과 새 쪽 상단이라는 소유 조건은 호출부에서 그대로 확인한다.
    let tolerance_px = hwpunit_to_px(advance_hu.max(0), dpi) * 1.5;
    (current_height_px - stored_end_px).abs() <= tolerance_px
}

/// 값이 있는 가장 가까운 앞 문단의 마지막 저장 줄 `(vpos, vpos + line_height)`.
fn preceding_stored_line_span(paragraphs: &[Paragraph], para_idx: usize) -> Option<(i32, i32)> {
    paragraphs[..para_idx.min(paragraphs.len())]
        .iter()
        .rev()
        .find_map(|p| {
            p.line_segs
                .iter()
                .rev()
                .find(|s| !is_synthetic_line_seg(s))
                .map(|s| {
                    (
                        s.vertical_pos,
                        s.vertical_pos.saturating_add(s.line_height.max(0)),
                    )
                })
        })
}

/// 값이 있는 가장 가까운 앞 문단의 마지막 저장 `vpos` — 직전 문단이 비어 line_segs 가
/// 없을 수 있다.
fn preceding_stored_vpos(paragraphs: &[Paragraph], para_idx: usize) -> Option<i32> {
    paragraphs[..para_idx.min(paragraphs.len())]
        .iter()
        .rev()
        .find_map(|p| {
            p.line_segs
                .iter()
                .rev()
                .find(|s| !is_synthetic_line_seg(s))
                .map(|s| s.vertical_pos)
        })
}

/// 저장 줄이 쪽 하단까지 찬 직후 `vpos=0`으로 시작하는 문단은 다음 쪽 소유다.
///
/// 일반 되감김 판정은 직전 줄의 *시작* `vpos > 5000`을 요구한다. 거의 한 쪽 높이인
/// TAC 표처럼 줄 시작은 위쪽이지만 `line_height`가 본문 하단까지 닿는 경우에는 그
/// 조건으로 새 쪽 신호를 놓친다. 이 보조 판정은 atomic TAC의 하단 여백 spill 예외만
/// 제한하며, 저장 줄 하단이 본문의 85%에 못 미치거나 다음 줄이 정확히 0에서 시작하지
/// 않으면 기존 top-fit 동작을 유지한다.
fn stored_zero_vpos_after_near_full_line(
    paragraphs: &[Paragraph],
    para_idx: usize,
    body_height_hu: i32,
) -> bool {
    let current_starts_at_zero = paragraphs
        .get(para_idx)
        .and_then(|para| {
            para.line_segs
                .iter()
                .find(|seg| !is_synthetic_line_seg(seg))
        })
        .is_some_and(|seg| seg.vertical_pos == 0);
    if !current_starts_at_zero || body_height_hu <= 0 {
        return false;
    }

    paragraphs[..para_idx.min(paragraphs.len())]
        .iter()
        .rev()
        .find_map(|para| {
            para.line_segs
                .iter()
                .rev()
                .find(|seg| !is_synthetic_line_seg(seg))
        })
        .is_some_and(|seg| {
            let bottom = seg.vertical_pos.saturating_add(seg.line_height);
            bottom >= body_height_hu.saturating_mul(85) / 100
        })
}

/// Native HWP5의 저장된 다행 RowBreak 프레임을 현재 쪽 소유로 되감아도 되는
/// page-tail 서명인지 판정한다.
///
/// 순차 host-spacing 누적은 저장 top보다 소폭 앞설 수 있지만, 일반적인 과거
/// anchor까지 되감으면 표가 여러 쪽씩 압축된다. 실제 저장본에서 관측한 3.2px
/// drift와 5.1px body-tail 여유만 포괄하도록 양쪽 경계를 제한한다.
fn native_hwp5_saved_rowbreak_tail_frame_matches(
    source_top: f64,
    source_bottom: f64,
    current_height: f64,
    available: f64,
) -> bool {
    const MIN_HOST_SPACING_DRIFT_PX: f64 = 1.0;
    const MAX_HOST_SPACING_DRIFT_PX: f64 = 4.0;
    const MAX_BODY_TAIL_GAP_PX: f64 = 8.0;

    let host_spacing_drift = current_height - source_top;
    let body_tail_gap = available - source_bottom;
    host_spacing_drift >= MIN_HOST_SPACING_DRIFT_PX
        && host_spacing_drift <= MAX_HOST_SPACING_DRIFT_PX
        && body_tail_gap >= 0.0
        && body_tail_gap <= MAX_BODY_TAIL_GAP_PX
}

fn paragraph_forces_page_boundary_after(
    current_para: &Paragraph,
    next_para: &Paragraph,
    col_count: u16,
    is_hwp3_variant: bool,
) -> bool {
    matches!(
        next_para.column_type,
        ColumnBreakType::Page | ColumnBreakType::Section
    ) || paragraph_saved_vpos_reset_starts_new_page_after(
        current_para,
        next_para,
        col_count,
        is_hwp3_variant,
    )
}

/// 빈 ColumnBreak가 두 non-inline 표 사이에 있고 다음 표가 이미 PageBreak를
/// 소유하면, ColumnBreak는 별도 physical page가 아니라 다음 표의 carrier다.
/// 표의 shape, 크기, 저장 vpos가 아니라 형제 paragraph의 break 소유권만 쓴다.
fn empty_table_carrier_column_break_before_page_table(
    para_idx: usize,
    para: &Paragraph,
    paragraphs: &[Paragraph],
) -> bool {
    if para_idx == 0
        || para.column_type != ColumnBreakType::Column
        || !para.text.trim().is_empty()
        || !para.controls.is_empty()
    {
        return false;
    }

    let previous = &paragraphs[para_idx - 1];
    let Some(next) = paragraphs.get(para_idx + 1) else {
        return false;
    };

    matches!(previous.controls.as_slice(), [Control::Table(table)]
        if !table.common.treat_as_char)
        && next.column_type == ColumnBreakType::Page
        && matches!(next.controls.as_slice(), [Control::Table(table)]
            if !table.common.treat_as_char)
}

fn single_line_visible_bounds_px(
    para: &Paragraph,
    page_vpos_base: i32,
    dpi: f64,
) -> Option<(f64, f64)> {
    let mut real_lines = para
        .line_segs
        .iter()
        .filter(|ls| !is_synthetic_line_seg(ls));
    let line = real_lines.next()?;
    if real_lines.next().is_some() {
        return None;
    }

    line_seg_visible_bounds_px(line, page_vpos_base, dpi)
}

fn line_seg_visible_bounds_px(seg: &LineSeg, page_vpos_base: i32, dpi: f64) -> Option<(f64, f64)> {
    let top = seg.vertical_pos.saturating_sub(page_vpos_base);
    let bottom = seg
        .vertical_pos
        .saturating_add(seg.line_height)
        .saturating_sub(page_vpos_base);
    (top >= 0 && bottom >= 0).then(|| (hwpunit_to_px(top, dpi), hwpunit_to_px(bottom, dpi)))
}

const SAVED_TAIL_FIT_CHAIN_CAP: usize = 2;

#[derive(Debug, PartialEq, Eq)]
enum SavedTailFitChainDecision {
    NoChange,
    Advance,
    Break,
}

fn saved_tail_fit_chain_decision(
    tail_fit_chain: usize,
    saved_tail_vpos_fit: bool,
    hwp_authoritative: bool,
    native_hwp5_reset_tail_fits_actual_footnote_boundary: bool,
) -> SavedTailFitChainDecision {
    if !saved_tail_vpos_fit
        || hwp_authoritative
        || native_hwp5_reset_tail_fits_actual_footnote_boundary
    {
        SavedTailFitChainDecision::NoChange
    } else if tail_fit_chain >= SAVED_TAIL_FIT_CHAIN_CAP {
        SavedTailFitChainDecision::Break
    } else {
        SavedTailFitChainDecision::Advance
    }
}

const SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX: f64 = 16.0;
/// [#5822] 누적 흐름이 저장 object frame 안으로 앞서 들어갔을 때 그 frame 을
/// 물리 page owner 로 신뢰하는 최대 드리프트. 실측 42.2px(156634833 p6)를
/// 덮고, frame 깊숙이 지나간 stale anchor(수백 px 뒤처짐)는 기각한다.
const SAVED_FRAME_FLOW_DRIFT_TOLERANCE_PX: f64 = 64.0;

/// [#5941] "흐름이 body 바닥에 앉았다"고 볼 여유. 이보다 적게 남았으면 저장 tail 의
/// 쪽 배정은 일반 fit 의 소관이다(`task1725` 242쪽 핀: 여유 0.0).
const BODY_BOTTOM_SEAT_PX: f64 = 10.0;

/// [#2097→#5714] 표를 완결하는 마지막 행의 쪽 하단 압축 수용치 — 한글은 쪽
/// 경계에서 말미 행이 잔여를 이 이내로 초과하면 행 밴드를 잔여로 압축해 쪽을
/// 완결한다 (1741000 실측 초과 6.8px 수용, 삭제 전 #2097 상수 그대로).
const TERMINAL_ROW_BOTTOM_SQUEEZE_TOLERANCE_PX: f64 = 13.0;
/// [#2097→#5714] 압축 수용은 쪽 끝자락(잔여 ≤ 이 값)에서만 — 한글의 압축은 쪽
/// 마무리 동작이다 (1741000 잔여 73.5px 압축 vs kps-ai 잔여 237.3px 이월 실측).
const TERMINAL_ROW_BOTTOM_SQUEEZE_MAX_REST_PX: f64 = 100.0;
/// [#2097→#5714] 압축 수용에 필요한 콘텐츠 여유(잔여-콘텐츠) 하한 — 콘텐츠가
/// 눌릴 공간이 없으면 한글도 이월한다 (1741000 여유 25.9px 압축 실측).
const TERMINAL_ROW_BOTTOM_SQUEEZE_MIN_HEADROOM_PX: f64 = 12.0;

fn saved_bounds_overlap_current_flow(bounds: (f64, f64), current_height: f64) -> bool {
    let (top, bottom) = bounds;
    let line_height = (bottom - top).max(0.0);
    line_height > 0.0 && top <= current_height + line_height && current_height <= bottom
}

fn saved_line_is_anchored_to_current_flow(bounds: (f64, f64), current_height: f64) -> bool {
    let (top, bottom) = bounds;
    bottom > top
        && top <= current_height
        && current_height <= top + SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX
}

/// `fragment_flow_top` 은 이 조각이 흐름에서 시작한 높이, `line_flow_top` 은 판정 중인
/// 줄의 흐름 위치다. 저장 줄은 그 사이(시작 쪽은 앵커 허용오차만큼 위까지)에 있어야
/// 같은 좌표계의 저장 위치로 본다 — 흐름이 저장 사다리보다 앞서 있어도(앞 줄들의
/// 누적 드리프트) 그 조각 안의 저장 줄이면 받고, 조각보다 위의 낡은 좌표는 거부한다.
fn saved_line_clears_footnote_area(
    current_footnote_height: f64,
    is_single_column: bool,
    overflow: f64,
    saved_bounds: Option<(f64, f64)>,
    base_available_height: f64,
    fragment_flow_top: f64,
    line_flow_top: f64,
) -> bool {
    current_footnote_height > 0.0
        && is_single_column
        && overflow <= 0.0
        && saved_bounds.is_some_and(|(top, bottom)| {
            let text_limit = base_available_height - current_footnote_height;
            top >= 0.0
                && top <= base_available_height
                && bottom <= text_limit
                && bottom > top
                && top <= line_flow_top.max(fragment_flow_top)
                && fragment_flow_top <= top + SAVED_LINE_FLOW_ANCHOR_TOLERANCE_PX
        })
}

fn saved_bounds_fit_at_flow_tail(
    bounds: (f64, f64),
    current_height: f64,
    available: f64,
    bottom_spill: f64,
) -> bool {
    saved_bounds_overlap_current_flow(bounds, current_height)
        && bounds.1 <= available + bottom_spill
}

fn saved_table_bounds_fit_at_flow_tail(
    bounds: (f64, f64),
    current_height: f64,
    available: f64,
    table_height: f64,
) -> bool {
    let (top, _) = bounds;
    // 저장 object frame이 현재 누적 흐름보다 조금 앞에서 시작해도, 그 line이 현재
    // 흐름과 겹치고 object bottom이 같은 body 안에 있으면 그 frame이 물리 page
    // owner다. 반대로 현재 흐름보다 뒤처진 쪽 상단 frame은 stale anchor이므로
    // 일반 fit 경로에 맡긴다.
    let source_frame_leads_current_flow =
        current_height <= top && saved_bounds_overlap_current_flow(bounds, current_height);
    // [#5822] 흐름이 저장 frame **안**에 막 들어온 경우(top ≤ 흐름 ≤ top+드리프트
    // 허용, 흐름 ≤ bottom)도 그 frame 이 물리 page owner 다 — 누적 드리프트로
    // 흐름이 사다리보다 수십 px 앞서 달려도, 한글이 기록한 frame 이 body 에
    // 들어가면 표는 그 쪽에 앉는다 (156634833 p6 차트 표: 저장 748.2..929.1 ≤
    // body 933.6 인데 흐름 790.4(드리프트 +42.2px) 기준 적합검사가 밀어 40쪽 vs
    // 한글 39쪽 — 이하 절 전체가 한 쪽씩 밀렸다). 흐름이 frame 깊숙이(허용 초과)
    // 지나간 쪽 상단 stale anchor 는 여전히 일반 fit 경로에 맡긴다.
    //
    // [#5941 3240179] `top == 0` 은 frame 위치 증거가 아니라 "쪽 시작" vpos
    // 센티널이다 — 그 값에 드리프트 허용을 적용하면 흐름이 42~48px 내려간
    // 상태에서도 쪽-말미 크기 표(913~918px)가 현재 쪽에 강제로 앉아 문서가
    // 3쪽 압축된다(16→13, 한글 18). 실제 frame(top>0, 원 케이스 748.2)만
    // 이 갈래의 대상이다. top==0 + 흐름 0 은 기존 anchored 갈래가 그대로 담당.
    let current_flow_inside_source_frame = top > 0.0
        && top <= current_height
        && current_height <= top + SAVED_FRAME_FLOW_DRIFT_TOLERANCE_PX
        && current_height <= bounds.1;
    table_height.is_finite()
        && table_height > 0.0
        && (saved_line_is_anchored_to_current_flow(bounds, current_height)
            || source_frame_leads_current_flow
            || current_flow_inside_source_frame)
        && bounds.1 <= available
        && bounds.0 + table_height <= available
}

/// 저장 LineSeg에 앵커된 TAC 표는 `common.height`가 한컴이 기록한 물리 object
/// frame이다. 행 측정 총합에는 host의 outer margin이 더해질 수 있으므로, 저장 frame
/// fit을 판정할 때는 선언 frame을 우선하고 선언값이 없을 때만 측정 높이를 사용한다.
/// [#5699 H1] 저장 사다리가 자리차지(TAC) 표의 밴드 높이를 계상하지 않은
/// 자기모순 판별.
///
/// 저장 th 관례 기반 계상(`charged_px`)이 **선언 표높이와 실측 둘 다**의 1/4
/// 미만이고, 선언과 실측이 서로 정합(2배 이내)일 때만 참이다. 선언·실측이
/// 갈라지는 문서(#2237 측정-저장 발산, #2148 라벨 셀)는 정합 조건에서 빠져
/// 종전 동작 불변. 이 서명의 문서(자치법규/기계생성 균일 사다리)는 한글 2022 가
/// 저장 사다리를 버리고 재조판한다 — 영월군 20099369 오라클 실측: 한글 4쪽
/// 정상 배치 vs 저장 사다리 추종 2쪽 전면 겹침(#5699 H1 코호트 40문서).
pub(crate) fn stored_ladder_omits_tac_band(
    charged_px: f64,
    declared_px: f64,
    measured_px: f64,
) -> bool {
    declared_px > 1.0
        && measured_px > 1.0
        && declared_px.max(measured_px) < declared_px.min(measured_px) * 2.0
        && charged_px < declared_px.min(measured_px) * 0.25
}

fn stored_tac_table_frame_height(
    table: &crate::model::table::Table,
    dpi: f64,
    measured_height: f64,
) -> f64 {
    let declared_height = hwpunit_to_px(table.common.height.min(i32::MAX as u32) as i32, dpi);
    if declared_height.is_finite() && declared_height > 0.0 {
        declared_height
    } else {
        measured_height
    }
}

#[cfg(test)]
mod saved_tac_table_flow_tail_contract {
    use super::saved_table_bounds_fit_at_flow_tail;

    #[test]
    fn requires_the_table_object_not_just_its_anchor_line_to_fit() {
        assert!(saved_table_bounds_fit_at_flow_tail(
            (850.0, 870.0),
            858.0,
            971.0,
            100.0,
        ));
        assert!(
            !saved_table_bounds_fit_at_flow_tail((850.0, 870.0), 858.0, 971.0, 889.0,),
            "a tail anchor line cannot authorize a table that extends into the next page"
        );
    }

    #[test]
    fn accepts_a_forward_source_frame_that_overlaps_the_current_flow() {
        assert!(saved_table_bounds_fit_at_flow_tail(
            (120.0, 500.0),
            100.0,
            700.0,
            350.0,
        ));
        assert!(!saved_table_bounds_fit_at_flow_tail(
            (0.0, 500.0),
            400.0,
            700.0,
            350.0,
        ));
    }
}

fn paragraph_saved_visible_bounds(
    para: &Paragraph,
    page_vpos_base: i32,
    dpi: f64,
) -> Option<(f64, f64)> {
    let mut bounds: Option<(f64, f64)> = None;
    for seg in para
        .line_segs
        .iter()
        .filter(|seg| !is_synthetic_line_seg(seg))
    {
        let (top, bottom) = line_seg_visible_bounds_px(seg, page_vpos_base, dpi)?;
        bounds = Some(match bounds {
            Some((min_top, max_bottom)) => (min_top.min(top), max_bottom.max(bottom)),
            None => (top, bottom),
        });
    }
    bounds
}

fn saved_line_range_fits_body_tail(
    para: &Paragraph,
    start_line: usize,
    end_line: usize,
    body_height_px: f64,
    page_vpos_base: i32,
    dpi: f64,
) -> bool {
    if start_line >= end_line || end_line > para.line_segs.len() {
        return false;
    }

    let mut prev_vpos: Option<i32> = None;
    for seg in &para.line_segs[start_line..end_line] {
        if is_synthetic_line_seg(seg) || seg.vertical_pos <= 0 {
            return false;
        }
        if prev_vpos.is_some_and(|prev| seg.vertical_pos < prev) {
            return false;
        }
        let Some((_, bottom_px)) = line_seg_visible_bounds_px(seg, page_vpos_base, dpi) else {
            return false;
        };
        if bottom_px > body_height_px + 0.5 {
            return false;
        }
        prev_vpos = Some(seg.vertical_pos);
    }

    true
}

/// 원본 문단 내부 `vpos=0` reset은, reset 직전 fragment가 현재 flow 앵커에서
/// 시작할 때에만 다음 물리 쪽의 시작을 뜻한다. 이 경우 reset 전 줄들은 저장된
/// 현재 쪽 fragment의 owner이므로, 일반 줄 높이 예산만으로 중간 쪽으로 분리하지
/// 않는다. 본문을 밀지 않는 용지 기준 그림은 앵커 줄의 쪽 소유를 공유한다.
/// 흐름을 소비하는 개체·다단·로컬 원점 되감김은 이 계약 밖에 둔다.
fn stored_body_reset_fragment_matches_current_flow(
    st: &TypesetState,
    para: &Paragraph,
    start_line: usize,
    break_line: usize,
    current_page_vpos_base: i32,
    spacing_before: f64,
    dpi: f64,
) -> bool {
    paragraph::scan::stored_body_reset_fragment_matches_current_flow(
        &st.paragraph_line_scan_page(),
        para,
        start_line,
        break_line,
        current_page_vpos_base,
        spacing_before,
        dpi,
    )
}

fn paragraph_text_looks_like_list_continuation_tail(para: &Paragraph) -> bool {
    let text = para.text.trim_start();
    text.starts_with('.') || text.starts_with('-') || text.starts_with('·') || text.starts_with('•')
}

/// [Task #1749] 저장 flow 가 이 문단을 "페이지 마지막 줄"로 인코딩했는가.
///
/// saved bounds 신뢰(`saved_single_line_bottom_fits`)는 저장 LINE_SEG vpos 가 페이지
/// 배정을 인코딩한다는 전제 위에 있다. 페이지-마지막 증거는 세 가지다:
/// ① 다음 문단의 첫 실줄이 없음(문서/구역 끝 — fe6de3ef 합성 테스트 보호 케이스),
/// ② 다음 실줄이 현재 줄보다 작은 vpos 로 리셋(다음 줄이 새 쪽),
/// ③ 다음 실줄에 도달하기 전에 명시적 쪽/구역나누기 문단이 있음 — 누적좌표 문서는
///    쪽 경계에서도 vpos 가 리셋되지 않으므로(예: 결재문서 36375752 pi26→pi27
///    [쪽나누기]) 리셋 검사만으로는 이 증거를 볼 수 없다. 신뢰 경로는 vpos 를
///    페이지 기준점 상대값으로 쓰므로 누적좌표라도 페이지 내 위치는 유효하다.
/// 어느 증거도 없이 다음 vpos 가 증가 지속하면(예: 결재문서 36371084 pi18→pi19)
/// 저장 vpos 로 페이지를 알 수 없으므로 신뢰하지 않는다 — 누적높이 판정으로 복귀해
/// 쪽 경계 overfill 을 막는다.
fn saved_flow_marks_page_last(paragraphs: &[Paragraph], para_idx: usize) -> bool {
    let curr_vpos = match paragraphs
        .get(para_idx)
        .and_then(|p| p.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)))
    {
        Some(ls) => ls.vertical_pos,
        None => return false,
    };
    for next_para in paragraphs.iter().skip(para_idx + 1) {
        if matches!(
            next_para.column_type,
            ColumnBreakType::Page | ColumnBreakType::Section
        ) {
            return true;
        }
        if let Some(next) = next_para
            .line_segs
            .iter()
            .find(|ls| !is_synthetic_line_seg(ls))
        {
            return next.vertical_pos < curr_vpos;
        }
    }
    true
}

fn positive_vpos_end_before_negative_wrap(para: &Paragraph) -> Option<i32> {
    let last_real = para
        .line_segs
        .iter()
        .rev()
        .find(|ls| !is_synthetic_line_seg(ls))?;
    if last_real.vertical_pos >= 0 {
        return None;
    }

    para.line_segs
        .iter()
        .filter(|ls| !is_synthetic_line_seg(ls) && ls.vertical_pos > 0)
        .map(|ls| ls.vertical_pos.saturating_add(ls.line_height))
        .max()
}

fn para_near_rowbreak_table(paragraphs: &[Paragraph], para_idx: usize) -> bool {
    let start = para_idx.saturating_sub(1);
    let end = (para_idx + 3).min(paragraphs.len());
    paragraphs[start..end].iter().any(|para| {
        para.controls.iter().any(|control| {
            matches!(
                control,
                Control::Table(table)
                    if matches!(
                        table.layout_page_break(),
                        crate::model::table::TablePageBreak::RowBreak
                    )
            )
        })
    })
}

/// #1672 행정업무 편람 계열: raw TABLE attr 상위 바이트가 비어 있는 RowBreak 표는
/// 기존 4px 안전마진만으로도 페이지가 누적 과분할된다.
fn section_has_zero_high_attr_rowbreak_table(paragraphs: &[Paragraph]) -> bool {
    paragraphs.iter().any(|para| {
        para.controls.iter().any(|control| {
            matches!(
                control,
                Control::Table(table)
                    if matches!(
                        table.layout_page_break(),
                        crate::model::table::TablePageBreak::RowBreak
                    ) && (table.raw_table_record_attr & 0xff00_0000) == 0
            )
        })
    })
}

/// dump-pages가 프로덕션 `format_paragraph` 높이를 그대로 말하기 위한 분해 (#4628).
#[derive(Debug, Clone, Copy)]
pub(crate) struct DumpFormattedParagraphHeight {
    pub total: f64,
    pub spacing_before: f64,
    pub line_height_sum: f64,
    pub spacing_after: f64,
    pub line_spacing_sum: f64,
}
crate::storage::clone_copy!(DumpFormattedParagraphHeight);

mod controls;
#[path = "typeset/inline_flow.rs"]
mod inline_flow;
mod notes;
pub(crate) use notes::endnotes::content::endnote_first_para_render_offset;
mod paragraph;
mod section;
mod state;
mod stored_table_frame;
use state::TypesetState;
mod table;
pub(crate) use table::fit_measured_for_host;

/// [#2279 OMIT-eager] 저장 ladder 의 spacing-누락(OMIT) 서명 사전 판별.
///
/// #2383 의 lazy 판별(빈 host 문단의 표 성장 시점)은 첫 검출 지점 이전의
/// 페이지말 fit 에 문서군 규칙을 적용하지 못한다(36392557: 판별 pi27, 실제
/// 경계 pi14). 같은 서명 — 연속 문단쌍의 저장 스텝이 bare lh+ls 와 일치
/// (±2px)하면서 그 경계의 paraPr spacing(cur.sa + next.sb)을 반영하지 않음 —
/// 을 구역 시작 시점에 전방 스캔으로 검출한다. 2쌍 이상 요구(단발 우연 일치
/// 배제). 정상(스텝이 spacing 포함) 문서는 스텝이 lh+ls 보다 spacing 만큼
/// 길어 불일치한다.
fn ladder_spacing_omitted_signature(
    paragraphs: &[Paragraph],
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> bool {
    use crate::model::paragraph::LineSeg;
    // [#2279 OMIT-eager 판별 3요건] lineseg 가 통째로 드롭된 본문 문단(마스킹·
    // 생성기 드롭)이 **다수 비율**로 존재 — 한글이 저장 흐름을 신뢰하지 못하고
    // fresh 재계산하는 문서군의 본질 신호다. 실측 분리: 재계산 문서군은
    // 0.39~0.80(36475730/36360680/36392557), 저장 흐름 신뢰 문서는 0(보도자료
    // 156652332)~0.10(sample16 #2158 핀) — 임계 25% + 4문단, 이하는 국소
    // 드롭으로 보고 저장 흐름 신뢰를 유지한다(+1 회귀 실측).
    let mut text_paras = 0usize;
    let mut segless_text_paras = 0usize;
    for p in paragraphs {
        if p.text.trim().is_empty() {
            continue;
        }
        text_paras += 1;
        if !p
            .line_segs
            .iter()
            .any(|s| s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0)
        {
            segless_text_paras += 1;
        }
    }
    if segless_text_paras < 4 || segless_text_paras * 4 < text_paras {
        return false;
    }
    let mut hits = 0usize;
    let mut spacing_omitted = false;
    // [#2279 OMIT-eager 판별 2요건] 누적좌표 ladder 문서(리셋 없음, 예: 36386907)
    // 는 저장 좌표가 한글 fresh 와 일치하는 신뢰 문서군이라 spacing-누락 스텝이
    // 있어도 페이지말 fit 신뢰 철회 대상이 아니다(트림 수용이 정답 — 92셋 실측
    // 2건 +1 반증). 페이지별 vpos 리셋(재배치 사다리, 예: 36392557 pi14→pi15)
    // 을 함께 요구한다.
    let mut has_page_reset = false;
    for pair in paragraphs.windows(2) {
        let (cur, next) = (&pair[0], &pair[1]);
        let (Some(cur_last), Some(next_first)) = (cur.line_segs.last(), next.line_segs.first())
        else {
            continue;
        };
        if cur_last.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
            || next_first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
        {
            continue;
        }
        if next_first.vertical_pos <= cur_last.vertical_pos {
            // vpos 리셋/역행 경계 — 스텝 판정 불가. 쪽 하단→상단 리셋만 인정.
            // 개체(표/그림) host 문단의 v=0 은 TAC 장식·footer 표의 좌표 관례라
            // 쪽 리셋이 아니다(156652332 담당부서 표 오인 → +1 회귀 실측) —
            // 개체 없는 본문 텍스트 문단으로의 리셋만 페이지 재배치 신호로 본다.
            if cur_last.vertical_pos > 5000
                && next_first.vertical_pos < 5000
                && next.controls.is_empty()
                && para_has_visible_text(next)
            {
                has_page_reset = true;
            }
            continue;
        }
        if spacing_omitted {
            if has_page_reset {
                return true;
            }
            continue;
        }
        let sa = styles
            .para_styles
            .get(cur.para_shape_id as usize)
            .map(|s| s.spacing_after)
            .unwrap_or(0.0);
        let sb = styles
            .para_styles
            .get(next.para_shape_id as usize)
            .map(|s| s.spacing_before)
            .unwrap_or(0.0);
        let spacing_around = sa + sb;
        if spacing_around <= 2.5 {
            continue;
        }
        let step = hwpunit_to_px(next_first.vertical_pos - cur_last.vertical_pos, dpi);
        let bare = hwpunit_to_px(
            cur_last.line_height.saturating_add(cur_last.line_spacing),
            dpi,
        );
        if step <= 0.0 || bare <= 0.0 {
            continue;
        }
        if (step - bare).abs() < 2.0 && step + 1.0 < bare + spacing_around {
            hits += 1;
            if hits >= 2 {
                spacing_omitted = true;
                if has_page_reset {
                    return true;
                }
            }
        }
    }
    spacing_omitted && has_page_reset
}

fn debug_brief_line_text(text: &str, max_chars: usize) -> String {
    let mut out = String::new();
    for ch in text.chars().take(max_chars) {
        match ch {
            '\r' => out.push_str("\\r"),
            '\n' => out.push_str("\\n"),
            '\t' => out.push_str("\\t"),
            '\u{FFFC}' => out.push_str("<TAC>"),
            c if c.is_control() => out.push(' '),
            c => out.push(c),
        }
    }
    if text.chars().count() > max_chars {
        out.push('…');
    }
    out
}

/// [#2424 프로파일] `typeset_section_with_variant` 하위 단계 누적 실측 — 동작 불변.
/// `RHWP_2424_PROFILE=1`(native 전용)일 때만 채워지고 구역당 한 줄로 출력한다.
/// `(Duration, u32)` 는 (누적 시간, 호출 수). wasm 에서는 enabled=false 로 고정되어
/// `Instant::now` 가 호출되지 않는다 (`paginate_pass` 의 게이트 패턴과 동일).
#[derive(Default)]
struct Issue2424TypesetProfile {
    setup: std::time::Duration,
    wrap_around: (std::time::Duration, u32),
    text_para: (std::time::Duration, u32),
    table_para: (std::time::Duration, u32),
    deferred_flush: (std::time::Duration, u32),
    para_tail: (std::time::Duration, u32),
    endnotes: std::time::Duration,
}

impl Issue2424TypesetProfile {
    fn add(bucket: &mut (std::time::Duration, u32), started: Option<std::time::Instant>) {
        if let Some(started) = started {
            bucket.0 += started.elapsed();
            bucket.1 += 1;
        }
    }

    fn ms(duration: std::time::Duration) -> f64 {
        duration.as_secs_f64() * 1000.0
    }
}

impl TypesetEngine {
    pub fn new(dpi: f64) -> Self {
        Self::new_with_render_normalization(
            dpi,
            std::sync::Arc::new(
                crate::renderer::render_normalization::RenderNormalizationOverlay::default(),
            ),
        )
    }

    pub(crate) fn new_with_render_normalization(
        dpi: f64,
        render_normalization: std::sync::Arc<
            crate::renderer::render_normalization::RenderNormalizationOverlay,
        >,
    ) -> Self {
        Self {
            dpi,
            profile: std::cell::Cell::new(Default::default()),
            section_column_spacing_hu: std::cell::Cell::new(None),
            uniform_filler_ladder: std::cell::Cell::new(false),
            float_carve_evidence: std::cell::RefCell::new(Vec::new()),
            format_next_stored_vpos: std::cell::Cell::new(None),
            render_normalization,
            endnote_measure_memo: Default::default(),
        }
    }

    pub(crate) fn with_section_column_spacing_hu(self, spacing: i32) -> Self {
        self.section_column_spacing_hu.set(Some(spacing));
        self
    }

    fn prime_section_cell_context(&self, engine: &crate::renderer::layout::LayoutEngine) {
        if let Some(spacing) = self.section_column_spacing_hu.get() {
            engine.set_section_column_spacing_hu(spacing);
        }
    }

    pub(crate) fn with_render_normalization(
        mut self,
        overlay: std::sync::Arc<crate::renderer::render_normalization::RenderNormalizationOverlay>,
    ) -> Self {
        self.render_normalization = overlay;
        self
    }

    pub fn with_default_dpi() -> Self {
        Self::new(DEFAULT_DPI)
    }

    /// 구역 조판과 같은 format 문맥을 연다. dump-pages 진단이 pagination과
    /// 다른 높이를 말하지 않도록 `typeset_section_with_variant` 와 공유한다 (#4628).
    pub(crate) fn apply_section_format_context(
        &self,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        profile: crate::model::provenance::LayoutCompatibilityProfile,
        body_top_hu: i32,
    ) {
        self.profile.set(profile);
        self.uniform_filler_ladder
            .set(crate::renderer::stored_line_ladder_is_uniform_filler(
                paragraphs, styles,
            ));
        *self.float_carve_evidence.borrow_mut() =
            crate::renderer::float_placement::paper_or_page_float_carve_evidence(
                paragraphs,
                body_top_hu,
            );
    }

    /// 프로덕션 문단 높이 분해. pagination이 `format_paragraph` 로 쓰는 값과 같다.
    pub(crate) fn dump_formatted_paragraph_height(
        &self,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
        column_width_px: Option<f64>,
        endnote: bool,
        stored_host_plan: Option<&crate::renderer::inline_flow::InlineFlowPlan>,
        next_stored_vpos: Option<i32>,
    ) -> DumpFormattedParagraphHeight {
        let mut fmt = if endnote {
            self.format_endnote_paragraph(para, composed, styles, column_width_px)
        } else {
            // 본문 흐름과 같은 다음 문단 저장 vpos 를 실어 같은 구성 결과를 진단한다.
            self.format_next_stored_vpos.set(next_stored_vpos);
            let fmt = self.format_paragraph(para, composed, styles, column_width_px);
            self.format_next_stored_vpos.set(None);
            fmt
        };
        if let Some(plan) = stored_host_plan.filter(|plan| plan.stored_empty_host) {
            fmt.use_square_host_plan(plan.clone(), self.dpi);
        }
        DumpFormattedParagraphHeight {
            total: fmt.total_height,
            spacing_before: fmt.spacing_before,
            line_height_sum: fmt.line_heights.iter().sum(),
            line_spacing_sum: fmt.line_spacings.iter().sum(),
            spacing_after: fmt.spacing_after,
        }
    }

    fn predict_current_column_para_y(
        &self,
        st: &TypesetState,
        target_para_idx: usize,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        measured_tables: &[MeasuredTable],
        column_width: Option<f64>,
    ) -> Option<f64> {
        let mut local_paras: Vec<Paragraph> = Vec::new();
        let mut local_indices: Vec<(usize, usize)> = Vec::new();
        for pi in st
            .current_items
            .iter()
            .filter_map(page_item_para_index)
            .chain(std::iter::once(target_para_idx))
        {
            if local_indices.iter().any(|(global, _)| *global == pi) {
                continue;
            }
            if let Some(p) = paragraph_by_global_index(paragraphs, &st.endnote_paragraphs, pi) {
                let local = local_paras.len();
                local_paras.push(p.clone());
                local_indices.push((pi, local));
            }
        }
        let lookup_local = |pi: usize, indices: &[(usize, usize)]| {
            indices
                .iter()
                .find_map(|(global, local)| (*global == pi).then_some(*local))
        };
        let first_vpos = st
            .current_items
            .iter()
            .filter_map(page_item_para_index)
            .find_map(|pi| {
                paragraph_by_global_index(paragraphs, &st.endnote_paragraphs, pi)
                    .and_then(|p| p.line_segs.first())
                    .map(|seg| seg.vertical_pos)
            })?;

        let available = st.available_height();
        let mut hc = HeightCursor::new(
            self.dpi,
            0.0,
            available,
            st.current_start_height,
            Some(first_vpos),
            st.skip_spacing_before_prededuct,
            false,
            st.current_endnote_flow && st.current_start_height < -0.5,
            st.current_endnote_flow,
        );
        hc.endnote_between_notes_hu = st.endnote_between_notes_hu;
        hc.endnote_note_first_paras =
            endnote_first_local_paras(paragraphs.len(), &st.endnote_para_sources, &local_indices);
        hc.stored_equation_reflow = !st.profile.session_edited()
            && (st.profile.hwp5_container() || st.profile.hwpx_stored_layout());
        let mut y = st.current_start_height;
        for item in &st.current_items {
            let Some(pi) = page_item_para_index(item) else {
                continue;
            };
            let Some(local) = lookup_local(pi, &local_indices) else {
                continue;
            };
            y = hc.vpos_adjust(y, local, &local_paras, styles);
            let item_para = &local_paras[local];
            let item_composed =
                crate::renderer::composer::compose_paragraph_in_context(item_para, styles);
            let item_fmt =
                self.format_paragraph(item_para, Some(&item_composed), styles, column_width);
            y += match item {
                PageItem::PartialParagraph {
                    start_line,
                    end_line,
                    ..
                } => item_fmt.line_advances_sum(*start_line..*end_line),
                PageItem::FullParagraph { .. } => item_fmt.total_height,
                PageItem::Table {
                    para_index,
                    control_index,
                } => measured_tables
                    .iter()
                    .find(|mt| mt.para_index == *para_index && mt.control_index == *control_index)
                    .map(|mt| mt.total_height)
                    .unwrap_or(0.0),
                PageItem::PartialTable {
                    para_index,
                    control_index,
                    start_row,
                    end_row,
                    ..
                } => measured_tables
                    .iter()
                    .find(|mt| mt.para_index == *para_index && mt.control_index == *control_index)
                    .map(|mt| {
                        let start = mt
                            .cumulative_heights
                            .get(*start_row)
                            .copied()
                            .unwrap_or(0.0);
                        let end = mt
                            .cumulative_heights
                            .get(*end_row)
                            .copied()
                            .unwrap_or(mt.total_height);
                        (end - start).max(0.0)
                    })
                    .unwrap_or(0.0),
                _ => 0.0,
            };
            let current_vpos_rewinds_from_prev = hc
                .prev_layout_para
                .and_then(|prev_local| {
                    let prev_first = local_paras
                        .get(prev_local)
                        .and_then(|p| p.line_segs.first())
                        .map(|seg| seg.vertical_pos)?;
                    let curr_first = local_paras
                        .get(local)
                        .and_then(|p| p.line_segs.first())
                        .map(|seg| seg.vertical_pos)?;
                    Some(curr_first < prev_first)
                })
                .unwrap_or(false);
            if matches!(
                item,
                PageItem::PartialParagraph { start_line, .. } if *start_line > 0
            ) || current_vpos_rewinds_from_prev
            {
                hc.prev_layout_para = None;
                hc.vpos_page_base = None;
                hc.vpos_lazy_base = None;
            } else {
                hc.prev_layout_para = Some(local);
                hc.prev_reissued_equation_rows =
                    crate::renderer::composer::stored_row_projection::reissued_equation_rows(
                        item_para,
                        &item_composed,
                    );
            }
            hc.prev_item_was_partial_table = matches!(item, PageItem::PartialTable { .. });
        }

        let local = lookup_local(target_para_idx, &local_indices)?;
        Some(hc.vpos_adjust(y, local, &local_paras, styles))
    }

    /// 구역의 문단 목록을 조판한다 (단일 패스).
    ///
    /// 기존 paginate()와 동일한 PaginationResult를 반환하므로
    /// 기존 layout/render 파이프라인과 호환된다.
    /// [Task #1046] 비-variant 단축 호출 — `is_hwp3_variant=false` 로 delegate.
    /// 기존 PR/tests 가 사용. force_break_before 는 사후 reflow 이월 hint.
    #[allow(clippy::too_many_arguments)]
    pub fn typeset_section(
        &self,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        page_def: &PageDef,
        column_def: &ColumnDef,
        section_index: usize,
        measured_tables: &[MeasuredTable],
        hide_empty_line: bool,
        force_break_before: &std::collections::HashSet<usize>,
    ) -> PaginationResult {
        self.typeset_section_with_variant(
            paragraphs,
            composed,
            styles,
            page_def,
            column_def,
            section_index,
            measured_tables,
            hide_empty_line,
            Default::default(),
            false,
            false,
            None,
            None,
            force_break_before,
            EndnoteDeferral::None,
        )
    }

    /// [Task #2094] 표 없는 문단의 배치 마무리 국면 — 원본 무변경 통이동 (st 변이만).
    #[allow(clippy::too_many_arguments)]
    fn typeset_no_table_paragraph_tail(
        &self,
        st: &mut TypesetState,
        page_def: &PageDef,
        para: &Paragraph,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        para_idx: usize,
        has_table: bool,
    ) {
        controls::prepare_no_table_host_wrap(st, page_def, para, para_idx, has_table);
    }

    /// 저장된 쪽 말미 어울림 그림은 앵커 본문과 분리되어 다음 물리 쪽의 띠를 소유한다.
    ///
    /// 단순히 현재 단의 여유가 작다는 이유로 자리차지 그림을 이월하면 같은 쪽의
    /// 캡션과 그림 옆 본문까지 바뀐다. 따라서 다음 문단에 vpos=0의 좁은 어울림 줄이라는
    /// 저장 계약이 있고, 현재 쪽의 기존 각주를 고려하면 그림 프레임 자체가 더는
    /// 들어가지 않는 유효 저장 그림에만 적용한다. 같은 HWP/HWPX 계약을 함께 확인한다.
    fn stored_square_picture_next_page_owner(
        &self,
        st: &TypesetState,
        para_idx: usize,
        para: &Paragraph,
        paragraphs: &[Paragraph],
        ctrl: &Control,
        styles: &ResolvedStyleSet,
    ) -> Option<(Vec<usize>, crate::renderer::pagination::WrapAnchorRef)> {
        controls::deferred_picture::next_page_owner(
            st.deferred_picture_page(),
            || st.available_height(),
            self.dpi,
            para_idx,
            para,
            paragraphs,
            ctrl,
            styles,
        )
    }

    /// 후속 어울림 문단 처리는 Query/Command를 연결하는 조정자에 위임한다.
    /// 반환 true = 원본의 `continue`(이 문단은 흡수/기록 완료, 배치 생략) 신호.
    #[allow(clippy::too_many_arguments)]
    fn typeset_wrap_around_paragraph(
        &self,
        st: &mut TypesetState,
        para: &Paragraph,
        paragraphs: &[Paragraph],
        para_idx: usize,
        has_table: bool,
        page_def: &PageDef,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
    ) -> bool {
        controls::wrap_flow::place(
            self, st, para, paragraphs, para_idx, has_table, page_def, composed, styles,
        )
    }

    /// [Task #1007] HWP3 → HWP5 변환본 인지 typeset.
    /// 변환본 시 cross-paragraph vpos reset (이전 last vpos > body/2 + 현재 first vpos < body/4)
    /// 감지하여 page break 트리거 (한컴 인코딩 page break 시그널).
    ///
    /// [Task #1046] `force_break_before`: 사후 reflow 이월 hint — 이 para_idx 들은 현재
    /// 페이지에 이미 항목이 있으면 새 페이지에서 시작한다 (layout overflow 로 판정된 항목
    /// 이월). 빈 셋이면 무동작 → 기존 출력 불변.
    #[allow(clippy::too_many_arguments)]
    pub fn typeset_section_with_variant(
        &self,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        page_def: &PageDef,
        column_def: &ColumnDef,
        section_index: usize,
        measured_tables: &[MeasuredTable],
        hide_empty_line: bool,
        profile: crate::model::provenance::LayoutCompatibilityProfile,
        skip_spacing_before_prededuct: bool,
        hwp3_origin_page_tolerance: bool,
        footnote_shape: Option<&FootnoteShape>,
        endnote_shape: Option<&FootnoteShape>,
        force_break_before: &std::collections::HashSet<usize>,
        endnote_deferral: EndnoteDeferral<'_>,
    ) -> PaginationResult {
        match self.typeset_section_with_variant_with_storage(
            paragraphs,
            composed,
            styles,
            page_def,
            column_def,
            section_index,
            measured_tables,
            hide_empty_line,
            profile,
            skip_spacing_before_prededuct,
            hwp3_origin_page_tolerance,
            footnote_shape,
            endnote_shape,
            force_break_before,
            endnote_deferral,
            &crate::storage::Unbounded,
        ) {
            Ok(value) => value,
            Err(never) => match never {},
        }
    }

    #[allow(clippy::too_many_arguments)]
    pub(crate) fn typeset_section_with_variant_with_storage<S: crate::storage::Storage>(
        &self,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        page_def: &PageDef,
        column_def: &ColumnDef,
        section_index: usize,
        measured_tables: &[MeasuredTable],
        hide_empty_line: bool,
        profile: crate::model::provenance::LayoutCompatibilityProfile,
        skip_spacing_before_prededuct: bool,
        hwp3_origin_page_tolerance: bool,
        footnote_shape: Option<&FootnoteShape>,
        endnote_shape: Option<&FootnoteShape>,
        force_break_before: &std::collections::HashSet<usize>,
        endnote_deferral: EndnoteDeferral<'_>,
        storage: &S,
    ) -> Result<PaginationResult, S::Error> {
        self.run_section_with_storage(
            paragraphs,
            composed,
            styles,
            page_def,
            column_def,
            section_index,
            measured_tables,
            hide_empty_line,
            profile,
            skip_spacing_before_prededuct,
            hwp3_origin_page_tolerance,
            footnote_shape,
            endnote_shape,
            force_break_before,
            endnote_deferral,
            storage,
        )
    }

    // ========================================================
    // format: 문단의 실제 높이를 계산한다
    // ========================================================

    /// 프로덕션 문단 높이. dump-pages 진단도 이 경로만 읽는다 (#4628).
    fn format_paragraph(
        &self,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
        column_width_px: Option<f64>,
    ) -> FormattedParagraph {
        self.format_paragraph_for_flow(
            para,
            composed,
            styles,
            column_width_px,
            styles.hwp3_variant,
            false,
        )
    }

    fn format_paragraph_with_known_square_band_with_storage<S: crate::storage::Storage>(
        &self,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
        column_width_px: Option<f64>,
        known_square_band: bool,
        storage: &S,
    ) -> Result<FormattedParagraph, S::Error> {
        self.format_paragraph_for_flow_with_storage(
            para,
            composed,
            styles,
            column_width_px,
            styles.hwp3_variant,
            known_square_band,
            storage,
        )
    }

    fn format_paragraph_for_flow(
        &self,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
        column_width_px: Option<f64>,
        hwp3_body_reflow: bool,
        known_square_band: bool,
    ) -> FormattedParagraph {
        match self.format_paragraph_for_flow_with_storage(
            para,
            composed,
            styles,
            column_width_px,
            hwp3_body_reflow,
            known_square_band,
            &crate::storage::Unbounded,
        ) {
            Ok(value) => value,
            Err(never) => match never {},
        }
    }

    fn format_paragraph_for_flow_with_storage<S: crate::storage::Storage>(
        &self,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        styles: &ResolvedStyleSet,
        column_width_px: Option<f64>,
        hwp3_body_reflow: bool,
        known_square_band: bool,
        storage: &S,
    ) -> Result<FormattedParagraph, S::Error> {
        let context = paragraph::context::ParagraphFormatContext::new(
            self.dpi,
            &self.profile,
            &self.uniform_filler_ladder,
            &self.float_carve_evidence,
            self.format_next_stored_vpos.get(),
        );
        paragraph::format::format_paragraph_for_flow_with_storage(
            &context,
            para,
            composed,
            styles,
            column_width_px,
            hwp3_body_reflow,
            known_square_band,
            storage,
        )
    }

    // ========================================================
    // fits + place/split: 배치 판단과 실행
    // ========================================================

    /// 문단을 현재 페이지에 배치한다.
    /// fits → place(전체) 또는 split(줄 단위) → move(다음 페이지)
    fn typeset_paragraph(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        fmt: &FormattedParagraph,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        is_last_in_section: bool,
    ) {
        match self.typeset_paragraph_with_storage(
            st,
            para_idx,
            para,
            fmt,
            paragraphs,
            styles,
            is_last_in_section,
            &crate::storage::Unbounded,
        ) {
            Ok(value) => value,
            Err(never) => match never {},
        }
    }

    fn typeset_paragraph_with_storage<S: crate::storage::Storage>(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        fmt: &FormattedParagraph,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        is_last_in_section: bool,
        storage: &S,
    ) -> Result<(), S::Error> {
        paragraph::flow::place_with_storage(
            st,
            paragraph::flow::ParagraphFlowInput {
                para_idx,
                para,
                fmt,
                paragraphs,
                styles,
                is_last_in_section,
            },
            self,
            storage,
        )?;

        Ok(())
    }

    // ========================================================
    // Phase 2: Break Token 기반 표 조판
    // ========================================================

    /// 표의 조판 높이를 계산한다 (format 단계).
    /// MeasuredTable + host_spacing을 통합하여 layout과 동일한 규칙으로 계산.
    #[allow(clippy::too_many_arguments)]
    fn format_table(
        &self,
        para: &Paragraph,
        para_idx: usize,
        ctrl_idx: usize,
        table: &crate::model::table::Table,
        measured_tables: &[MeasuredTable],
        styles: &ResolvedStyleSet,
        composed: Option<&ComposedParagraph>,
        next_para: Option<&Paragraph>,
        is_column_top: bool,
    ) -> FormattedTable {
        match self.format_table_with_storage(
            para,
            para_idx,
            ctrl_idx,
            table,
            measured_tables,
            styles,
            composed,
            next_para,
            is_column_top,
            &crate::storage::Unbounded,
        ) {
            Ok(value) => value,
            Err(never) => match never {},
        }
    }

    fn format_table_with_storage<S: crate::storage::Storage>(
        &self,
        para: &Paragraph,
        para_idx: usize,
        ctrl_idx: usize,
        table: &crate::model::table::Table,
        measured_tables: &[MeasuredTable],
        styles: &ResolvedStyleSet,
        composed: Option<&ComposedParagraph>,
        next_para: Option<&Paragraph>,
        is_column_top: bool,
        storage: &S,
    ) -> Result<FormattedTable, S::Error> {
        let frame_engine = crate::renderer::layout::LayoutEngine::new(self.dpi);
        self.prime_section_cell_context(&frame_engine);
        frame_engine.set_layout_profile(self.profile.get());
        frame_engine
            .set_render_normalization_overlay(std::sync::Arc::clone(&self.render_normalization));
        let external_flow = frame_engine.reflow_unrestricted_table_flow(table, styles);
        table::format_with_storage(
            table::TableFormatInput {
                para,
                para_idx,
                ctrl_idx,
                table,
                measured_tables,
                styles,
                composed,
                next_para,
                is_column_top,
                external_flow,
                unchanged_coanchored_frame: self.profile.get().hwp5_stored_pagination_layout()
                    && !self.render_normalization.table_text_reflowed(table)
                    && crate::renderer::float_placement::stored_inline_host_has_separate_float_frame(
                        para, table,
                    ),
            },
            self.dpi,
            || self.profile.get(),
            || self.uses_tac_table_flow(table),
            storage,
        )
    }

    #[allow(clippy::too_many_arguments)]
    fn flush_deferred_table_controls(
        &self,
        st: &mut TypesetState,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        measured_tables: &[MeasuredTable],
        flush_point: DeferredTableFlushPoint,
    ) {
        controls::flush_deferred_tables(st, paragraphs, flush_point, |st, deferred| {
            self.place_deferred_table_control(
                st,
                deferred,
                paragraphs,
                composed,
                styles,
                measured_tables,
            );
        });
    }

    /// 지연 큐에서 선택된 표 하나를 현재 열에서 다시 측정하고 배치한다.
    #[allow(clippy::too_many_arguments)]
    fn place_deferred_table_control(
        &self,
        st: &mut TypesetState,
        deferred: DeferredTableControl,
        paragraphs: &[Paragraph],
        composed: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        measured_tables: &[MeasuredTable],
    ) {
        controls::deferred_placement::place(
            self,
            st,
            deferred,
            paragraphs,
            composed,
            styles,
            measured_tables,
        );
    }

    /// 표가 포함된 문단을 처리한다.
    /// 각 컨트롤(표/도형)에 대해 format → fits → place/split 패턴 적용.
    #[allow(clippy::too_many_arguments)]
    fn typeset_table_paragraph(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        next_para: Option<&Paragraph>,
        styles: &ResolvedStyleSet,
        measured_tables: &[MeasuredTable],
        _page_def: &PageDef,
        // [Task #1753] 지연 이월 표의 후속 문단 prefill 용 전체 슬라이스.
        paragraphs_all: &[Paragraph],
        composed_all: &[ComposedParagraph],
    ) {
        match self.typeset_table_paragraph_with_storage(
            st,
            para_idx,
            para,
            composed,
            next_para,
            styles,
            measured_tables,
            _page_def, // [Task #1753] 지연 이월 표의 후속 문단 prefill 용 전체 슬라이스.
            paragraphs_all,
            composed_all,
            &crate::storage::Unbounded,
        ) {
            Ok(value) => value,
            Err(never) => match never {},
        }
    }

    fn typeset_table_paragraph_with_storage<S: crate::storage::Storage>(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        composed: Option<&ComposedParagraph>,
        next_para: Option<&Paragraph>,
        styles: &ResolvedStyleSet,
        measured_tables: &[MeasuredTable],
        _page_def: &PageDef,
        // [Task #1753] 지연 이월 표의 후속 문단 prefill 용 전체 슬라이스.
        paragraphs_all: &[Paragraph],
        composed_all: &[ComposedParagraph],
        storage: &S,
    ) -> Result<(), S::Error> {
        controls::paragraph_flow::place_with_storage(
            self,
            st,
            controls::paragraph_flow::TableParagraphInput {
                para_idx,
                para,
                composed,
                next_para,
                styles,
                measured_tables,
                paragraphs_all,
                composed_all,
            },
            storage,
        )?;

        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    fn try_typeset_empty_para_float_table(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        ctrl_idx: usize,
        para: &Paragraph,
        table: &crate::model::table::Table,
        ft: &FormattedTable,
        composed: Option<&ComposedParagraph>,
        prev_para: Option<&Paragraph>,
        next_para: Option<&Paragraph>,
        styles: &ResolvedStyleSet,
        para_start_height: f64,
        lanes: &mut FloatLaneSet,
        paragraphs: &[Paragraph],
    ) -> bool {
        if self.stored_cell_page_frames_require_split(table, styles) {
            return false;
        }
        // 앞 조각의 새 문자 줄로 현재 단의 흐름이 바뀌었으면 후속 표의
        // 원본 절대 vpos를 같은 물리 원점으로 다시 인증할 수 없다.
        let preceding_fragment_reflowed = st.current_items.iter().any(|item| {
            let PageItem::PartialTable {
                para_index,
                control_index,
                ..
            } = item
            else {
                return false;
            };
            *para_index < para_idx
                && paragraphs
                    .get(*para_index)
                    .and_then(|paragraph| paragraph.controls.get(*control_index))
                    .is_some_and(|control| match control {
                        Control::Table(previous) => {
                            self.render_normalization.table_text_reflowed(previous)
                        }
                        _ => false,
                    })
        });
        controls::try_place_empty_para_float_table(
            st,
            para_idx,
            ctrl_idx,
            para,
            table,
            ft,
            composed,
            prev_para,
            next_para,
            styles,
            para_start_height,
            lanes,
            paragraphs,
            self.render_normalization.table_text_reflowed(table),
            preceding_fragment_reflowed,
            self.dpi,
        )
    }

    /// TAC(treat_as_char) 표의 조판.
    #[allow(clippy::too_many_arguments)]
    fn typeset_tac_table(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        ctrl_idx: usize,
        para: &Paragraph,
        table: &crate::model::table::Table,
        ft: &FormattedTable,
        fmt: &FormattedParagraph,
        tac_count: usize,
        is_first_placed: bool,
        is_last_placed: bool,
        styles: &ResolvedStyleSet,
        composed: Option<&ComposedParagraph>,
        next_para: Option<&Paragraph>,
        // [#3837] 값이 있는 가장 가까운 앞 문단의 마지막 저장 vpos.
        prev_stored_vpos: Option<i32>,
    ) {
        // [Task #1152] 호스트 문단의 intra-paragraph vpos-reset 가드.
        // empty-text host paragraph 가 N controls + N line_segs 1:1 매핑이고,
        // 현재 TAC 표의 매핑 line_seg(ctrl_idx>0) 의 vpos==0 이면 HWP 가 "이 표를
        // 새 페이지 상단부터" 라고 명시한 신호. fit 검사는 표 크기가 잔여 영역에
        // 들어가면 통과시키지만 명시 신호를 존중하려면 fit 이전에 advance.
        // 케이스: 2022년 국립국어원 업무계획.hwp pi=586 ci=1 (별첨 박스).
        let tac_table_line_idx = self.tac_table_line_index(para, table, fmt);
        let prior_tac = para
            .controls
            .iter()
            .take(ctrl_idx)
            .filter(|c| matches!(c, Control::Table(t) if self.is_effective_tac_table(para, t, fmt)))
            .count();
        let tac_seg_idx = if tac_count > 1 {
            // [#2322] 텍스트-host 다중 TAC: 선행 텍스트 줄 수만큼 lineseg 매핑을
            // 오프셋한다. 종전 count 기반 매핑은 제목 줄이 있는 문단에서 표1을
            // 텍스트 줄(예: 16px)에 매핑해 851px 표가 16px 로 계상됐다 (20862337
            // r15 재검증 −1 서식 계열). 빈-host 1:1 문서는 오프셋 0 으로 불변.
            let leading_offset = para
                .controls
                .iter()
                .find_map(|c| match c {
                    Control::Table(t) if self.is_effective_tac_table(para, t, fmt) => Some(t),
                    _ => None,
                })
                .and_then(|t| self.tac_table_line_index(para, t, fmt))
                .unwrap_or(0);
            leading_offset + prior_tac
        } else {
            tac_table_line_idx.unwrap_or(0)
        };

        let owned_single_tac_row_height =
            (st.profile.hwpx_stored_layout() && tac_count == 1 && fmt.line_heights.len() == 1)
                .then(|| crate::renderer::composer::owned_rowbreak_tac_height(para, ctrl_idx))
                .flatten()
                .map(|height| hwpunit_to_px(height, self.dpi));
        // HWPX RowBreak TAC 표는 대개 host LINE_SEG가 표의 물리 줄을 보존한다.
        // 다만 단일 빈 host에 큰 다행 표가 있는데 저장 줄이 선언 높이를 전혀
        // 담지 못하면, 그 줄은 표 band의 소유 증거가 아니다. 이 형상을 짧은
        // host 줄로 계상하면 표와 뒤 문단이 한 쪽에 겹친다. 실측 표 높이와
        // trailing line spacing을 써야 한컴의 새 쪽 배치를 재현한다.
        let hwpx_rowbreak_tac_missing_owned_line = st.profile.hwpx_stored_layout()
            && table.common.treat_as_char
            && table.common.flow_with_text
            && matches!(
                table.layout_page_break(),
                crate::model::table::TablePageBreak::RowBreak
            )
            && tac_count == 1
            && para.controls.len() == 1
            && table.row_count == 3
            && table.col_count == 1
            && table.cells.len() == 3
            && !table.repeat_header
            && !para_has_visible_text(para)
            && fmt.line_heights.len() == 1
            && para.line_segs.len() == 1
            && para.line_segs.first().is_some_and(|seg| {
                !is_synthetic_line_seg(seg)
                    && hwpunit_to_px(seg.line_height, self.dpi) + 0.5 < ft.total_height
            });

        // [Task #1152] 호스트 문단의 intra-paragraph vpos-reset 가드 —
        // (a) 빈-host ctrl 1:1 매핑(원형), (b) [#2322] 텍스트-host 포함 일반형:
        // 표의 매핑 lineseg(tac_seg_idx>0)가 저장 vpos==0 이면 "이 표를 새 쪽
        // 상단부터"라는 명시 신호다. fit 이전에 advance 로 존중한다.
        let ctrl_reset = ctrl_idx > 0
            && para.text.is_empty()
            && para.line_segs.len() == para.controls.len()
            && para
                .line_segs
                .get(ctrl_idx)
                .map(|s| s.vertical_pos)
                .unwrap_or(-1)
                == 0;
        let seg_reset = tac_seg_idx > 0
            && para
                .line_segs
                .get(tac_seg_idx)
                .filter(|s| !is_synthetic_line_seg(s))
                .map(|s| s.vertical_pos)
                == Some(0);
        let intra_para_reset = ctrl_reset || seg_reset;
        if intra_para_reset && !st.current_items.is_empty() {
            st.advance_column_or_new_page();
        }
        // [#9016] 글자 없는 문단의 제목 차례 표시는 CTRL_HEADER 없이 개체보다 앞 슬롯을
        // 차지하고 자기 저장 줄을 쌓는다(1730000-202000011 pi=168: ts 0 titM 줄 th 2000,
        // ts 8 표 줄 vpos +2000). 이 문단의 첫 배치 표가 그 뒤 줄을 소유하면 표 원점과
        // 적합 판정이 그 줄 원점에서 시작하도록 앞 줄의 저장 전진을 먼저 쌓는다.
        if is_first_placed && !st.pre_emitted_host_paras.contains(&para_idx) {
            if let Some(prefix) = title_mark_prefix_advance(para, ctrl_idx, self.dpi) {
                st.advance_flow_by(prefix);
            }
        }
        // 다중 TAC 표: LINE_SEG 기반 개별 높이 계산
        let table_height = if tac_count > 1 {
            // [#2322] 마지막 TAC 판정은 개수 기반(prior_tac) — tac_seg_idx 는
            // 선행 텍스트 줄 오프셋을 포함하므로 count 비교에 쓰지 않는다.
            let is_last_tac = prior_tac + 1 == tac_count;
            // [compat 2024] 이월 앵커 사다리: 빈 host 의 마지막 저장 seg 가
            // vpos==0(다음 쪽 상단 앵커 줄, 2022 계상)이고 이 호출이 새 단
            // 최상단에서 일어나면, 한글 2024 는 그 이월 계상을 하지 않는다
            // (156609754 pi25 실측: 2022 재저장 ls=3(이월 세그) ↔ 2024 ls=2,
            // 다음 쪽 사다리가 3,597HU 위로). 계상을 0 으로 하고 회수를 적립해
            // 그 쪽의 저장 경계 재적합 자격을 준다.
            let carried_anchor_ladder = st.profile.hangul2024_layout()
                && st.current_items.is_empty()
                && !para_has_visible_text(para)
                && para
                    .line_segs
                    .last()
                    .is_some_and(|s| s.vertical_pos == 0 && !is_synthetic_line_seg(s))
                && para
                    .line_segs
                    .get(tac_seg_idx)
                    .is_some_and(|s| s.vertical_pos > 0);
            let charged = para
                .line_segs
                .get(tac_seg_idx)
                .map(|seg| {
                    let line_h = hwpunit_to_px(seg.line_height, self.dpi);
                    if is_last_tac {
                        line_h
                    } else {
                        line_h + hwpunit_to_px(seg.line_spacing, self.dpi)
                    }
                })
                .unwrap_or(ft.total_height);
            if carried_anchor_ladder {
                st.record_reclaimed_host_spacing(charged);
                if std::env::var("RHWP_DIAG_COMPAT24").is_ok() {
                    eprintln!(
                        "DIAG_COMPAT24 pi={para_idx} ci={ctrl_idx} carried_reclaim={charged:.1} \
                         total_reclaimed={:.1}",
                        st.hangul2024_reclaimed
                    );
                }
                0.0
            } else {
                charged
            }
        } else if let Some(owned_row_height) = owned_single_tac_row_height {
            owned_row_height
        } else if let Some((owner, _)) =
            crate::renderer::composer::stored_owned_tac_line(para, ctrl_idx).filter(|(owner, _)| {
                !st.profile.session_edited()
                    && !self.render_normalization.table_text_reflowed(table)
                    && fmt.line_heights.len() == para.line_segs.len()
                    && *owner > 0
                    && *owner + 1 < fmt.line_heights.len()
            })
        {
            // 저장 표 줄 앞의 공백 전진은 포함하되, 표 뒤 독립 줄은 그 줄의
            // PartialParagraph가 소비한다. 문단 전체 적합 높이로 예약하면 꼬리까지
            // 표에 넣은 뒤 다시 쌓게 된다.
            fmt.line_content_height(0..owner + 1, 0.0)
        } else if tac_table_line_idx == Some(0) && fmt.line_heights.len() > 1 {
            // PR #1088 follow-up: hwp-multi-001 pi=46 처럼 TAC 표가 문단의
            // 첫 줄이고 뒤따르는 제목 줄이 같은 문단의 line1(vpos reset)로
            // 인코딩된 경우가 있다. 표 자체는 현재 페이지에 들어가고 post-text
            // 만 다음 페이지로 넘어가야 하는데, 문단 전체 height_for_fit으로
            // fit 판단하면 표까지 다음 페이지로 밀린다.
            //
            // 이때 fit 기준은 line_height만 사용한다. line_spacing까지 포함한
            // line_advance를 쓰면 HWPX lineSeg가 `표줄 + 다음 텍스트줄`로
            // 분리된 문서에서, 표 자체는 남은 영역에 들어가는데도 spacing 때문에
            // 표가 다음 페이지로 밀린다(2025 donations HWPX pi=25).
            fmt.line_heights[0]
        } else if intra_para_reset && tac_seg_idx < fmt.line_heights.len() {
            // [#2311] intra-para reset(저장 vpos==0)으로 새 쪽에 온 표는 자신의
            // 줄(매핑 lineseg)부터만 계상한다. 문단 전체 height_for_fit 을
            // 쓰면 이전 쪽에 남은 선행 줄(전면 tac 그림 등)의 높이가 새 쪽에
            // 유령 계상되어 후속 문단을 한 쪽 더 밀어낸다 (156744475 4쪽→3쪽).
            (tac_seg_idx..fmt.line_heights.len())
                .map(|li| fmt.line_advance(li))
                .sum::<f64>()
        } else if st.profile.hangul2024_layout()
            && tac_seg_idx > 0
            && tac_seg_idx < fmt.line_heights.len()
            // [#8507] 필드 시작 뒤로 넘긴 표의 빈 필드 줄은 한/글 2024 도 쌓는다(합성
            // field_over19·field_over1414 의 2020·2024 Print 래스터 동일). 줄 재조판이 정한
            // 개체 줄은 저장 재저장본의 앞 앵커 줄 회수 대상이 아니다.
            && !crate::renderer::para_has_composed_object_rows(para)
            // [#8543] 앞 저장 줄이 TAC 도형·그림의 실제 줄이면 빈 앵커로 회수할 수 없다.
            // 한컴 2024 Print도 이 줄을 남긴다. #5524의 빈 앵커 회수는 유지한다.
            && !(st.profile.hwp5_stored_pagination_layout()
                && hwp5_tac_prefix_has_owned_object_line(para, tac_seg_idx))
        {
            // [compat 2024] 한글 2024 는 자리차지 표 앵커 문단의 선행 앵커 줄
            // 세그먼트를 흐름에 계상하지 않는다 — 2022 재저장본은 앵커 문단
            // lineseg 2개(선행 줄 + 표 밴드), 2024 재저장본은 밴드 1개
            // (output/poc/hangul_version_compat_phase0_20260818 Phase 1, Δ1).
            // 표 밴드 세그부터만 계상해 표와 후속 흐름을 그만큼 당기고, 회수량은
            // 저장 vpos 되감김 경계의 재적합 자격으로 적립한다.
            let reclaimed = (0..tac_seg_idx).map(|li| fmt.line_advance(li)).sum::<f64>();
            st.record_reclaimed_host_spacing(reclaimed);
            if std::env::var("RHWP_DIAG_COMPAT24").is_ok() {
                eprintln!(
                    "DIAG_COMPAT24 pi={para_idx} ci={ctrl_idx} anchor_reclaim={reclaimed:.1} \
                     tac_seg_idx={tac_seg_idx} total_reclaimed={:.1}",
                    st.hangul2024_reclaimed
                );
            }
            (tac_seg_idx..fmt.line_heights.len())
                .map(|li| fmt.line_advance(li))
                .sum::<f64>()
        } else if fmt.total_height > 0.0 {
            // 단일 TAC: 호스트 문단의 height_for_fit 사용
            fmt.height_for_fit
        } else {
            ft.total_height
        };
        // [#2319] 저장 lineseg 없는(기계생성) 문단은 fresh 컴포즈가 tac 표 높이를
        // 줄에 반영하지 못해, 위 fmt 기반 분기가 텍스트 줄높이(예: 17.3px)를
        // 858px 표의 높이로 채택한다 — 서식 문서 과소분할(−1쪽 계열 26건, r15
        // 재검증). 측정 높이보다 작으면 측정 높이로 보정한다. 저장 lineseg 보유
        // 문서는 불변 (#2237 측정-저장 발산 축과 격리).
        let table_height = if para.line_segs.is_empty() && table_height + 0.5 < ft.total_height {
            ft.total_height
        } else {
            table_height
        };
        // [#2279 stale-lh] 마스킹 도구가 셀 내용·cellSz 를 축소하고 표 선언
        // 높이(common.height)와 host lineseg lh 를 갱신하지 않은 생성기 잔존:
        // 저장 lh 기반 table_height 가 실측(ft)의 2배 이상이고 선언 표높이도
        // 같은 배율로 모순이면 실측을 신뢰한다 — 36382471 pi10 현황사진 표:
        // 선언=lh 154.2px vs 셀 실측 25px(재저장 fresh 24.6px 정합), 잔존
        // 154px 소비가 말미 2문단을 밀어 +1쪽. 정상 host 줄박스(표<글자줄,
        // 배율 ~1.1x)와 실측-이상 lh(#2243 커버형, 배율 ~1x)는 불변.
        let table_height = if !para.line_segs.is_empty()
            && ft.total_height > 1.0
            && table_height > ft.total_height * 2.0
            && hwpunit_to_px(table.common.height as i32, self.dpi) > ft.total_height * 2.0
        {
            ft.total_height
        } else {
            table_height
        };
        // [#5699 H1] 위와 대칭인 과소 방향: 저장 lineseg 보유 문서인데 저장 th 관례
        // 기반 계상이 선언·실측 표높이 둘 다의 1/4 미만이면, 생성기 사다리가 표
        // 밴드를 계상하지 않은 자기모순이다(자치법규 서식류 균일 사다리). 실측
        // 높이로 교정해 쪽 나눔이 실기하를 따르게 하고(한글 2022 재조판 정합 —
        // 영월군 20099369 오라클 4쪽 실측), 후속 저장 vpos 후방 스냅이 교정분을
        // 되돌리지 못하게 dirty 처리한다. 선언·실측 발산 문서(#2237/#2148)는
        // 정합 조건에서 배제되어 불변.
        // 게이트: ① HWPX 컨테이너 제외 — 기계 결재문서(36397752 하자검사조서)는
        // 같은 서명이어도 한글 1쪽 유지(오라클 PDF 실측)라 발동 시 +1 회귀(그 축은
        // #2279 OMIT 기계 소관). ② 직파싱 HWP3 는 tac=true "모순 조합" 표만 허용 —
        // 영월군 20099369(HWP3 V3.00, tac=true)는 한글 2022 가 재조판(오라클 4쪽,
        // 표 아래 깨끗한 배치)하는 반면, tac=false TopAndBottom 은 겹침이 한글
        // 정본인 계열(#4533 하동군)이라 기존 no-reserve 규칙에 맡긴다.
        // 밴드-앞 계상 방면: 한글 저장 사다리의 자리차지 표는 밴드가 앵커 줄 **앞**에
        // 계상되는 형(앵커 vpos = 밴드 아래)이 있다 — 직전 문단 저장 vpos 와 앵커
        // 사이 갭이 이미 밴드급이면 사다리는 정상이다(간장 보고서 3738 계열: 갭
        // 음수/대형 — 오라클-잠금 계약 5종이 th-단독 술어를 반증). 갭이 양수이면서
        // 밴드의 절반 미만일 때만 자기모순으로 본다(영월군 실측 27px vs 397px).
        let band_min_px = hwpunit_to_px(table.common.height as i32, self.dpi).min(ft.total_height);
        let anchor_vpos = para.line_segs.get(tac_seg_idx).map(|seg| seg.vertical_pos);
        let anchor_gap_px = anchor_vpos
            .zip(prev_stored_vpos)
            .filter(|(anchor, prev)| anchor > prev)
            .map(|(anchor, prev)| hwpunit_to_px(anchor - prev, self.dpi));
        // 밴드-뒤 계상(관례 A: 앵커 다음 문단 vpos 가 밴드만큼 진행) 방면 —
        // 다음 문단 갭도 함께 소형이어야 진짜 미계상이다(synam-001 pi10·간장
        // 보고서 실측: before-갭은 정상 사다리에서도 자연히 한 줄이라 단독
        // 판별자가 못 된다).
        let next_gap_px = st
            .next_para_first_stored_vpos
            .zip(anchor_vpos)
            .filter(|(next, anchor)| next > anchor)
            .map(|(next, anchor)| hwpunit_to_px(next - anchor, self.dpi));
        let ladder_omits_band = !st.profile.hwpx_container()
            && (!st.profile.hwp3_native_layout() || table.common.treat_as_char)
            && !para.line_segs.is_empty()
            && anchor_gap_px.is_some_and(|gap| gap < band_min_px * 0.5)
            && next_gap_px.is_some_and(|gap| gap < band_min_px * 0.5)
            && stored_ladder_omits_tac_band(
                table_height,
                hwpunit_to_px(table.common.height as i32, self.dpi),
                ft.total_height,
            );
        let unstored_cell_band = self
            .tac_flow_query()
            .single_tac_line_has_current_cell_rows(para, table, fmt, tac_count, &ft.cells)
            && ft.total_height > table_height + 0.5;
        let owns_tac_band =
            ladder_omits_band || hwpx_rowbreak_tac_missing_owned_line || unstored_cell_band;
        let table_height = if owns_tac_band {
            if std::env::var("RHWP_5699_DBG").is_ok() {
                eprintln!(
                    "DBG5699_TS pi={} ci={} th_charge={:.1} decl={:.1} meas={:.1} gap={:?} unowned_hwpx={}",
                    para_idx,
                    ctrl_idx,
                    table_height,
                    hwpunit_to_px(table.common.height as i32, self.dpi),
                    ft.total_height,
                    anchor_gap_px,
                    hwpx_rowbreak_tac_missing_owned_line,
                );
            }
            st.mark_vpos_ladder_dirty();
            st.record_ladder_band_table((para_idx, ctrl_idx));
            ft.total_height
        } else {
            table_height
        };

        // TAC 표는 분할하지 않고 통째로 배치
        let column = st.inline_flow_column();
        let style = styles.para_styles.get(para.para_shape_id as usize);
        let left = style.map_or(0.0, |s| s.margin_left);
        let right = style.map_or(0.0, |s| s.margin_right);
        let owned_row = (tac_count > 1
            && st.profile.hwp5_stored_pagination_layout()
            && !st.profile.session_edited()
            && !self.render_normalization.table_text_reflowed(table)
            && ft.table_footnotes.is_empty())
        .then(|| {
            controls::stored_tac::owned_row::prepare(
                para,
                table,
                ctrl_idx,
                composed,
                ft.effective_height,
                styles,
                self.dpi,
            )
        })
        .flatten()
        .or_else(|| {
            ((st.profile.session_edited() || table.caption.is_some())
                && ft.table_footnotes.is_empty())
            .then(|| {
                controls::stored_tac::owned_row::prepare_occupied(
                    para,
                    table,
                    ctrl_idx,
                    composed,
                    &fmt.line_heights,
                    ft.effective_height,
                    styles,
                    self.dpi,
                )
            })
            .flatten()
        });
        let stored_host_frame = (st.profile.hwp5_stored_pagination_layout()
            && !st.profile.session_edited()
            && !self.render_normalization.table_text_reflowed(table)
            && (ft.effective_height - hwpunit_to_px(table.common.height as i32, self.dpi)).abs()
                <= self.dpi / 7200.0)
            .then(|| crate::renderer::composer::stored_tac_host_frame(para))
            .flatten()
            .filter(|frame| frame.control == ctrl_idx);
        let table_height = stored_host_frame.as_ref().map_or(table_height, |frame| {
            hwpunit_to_px(frame.object_advance_hu, self.dpi)
        });
        // 앞선 TAC 소유 줄은 이미 각자의 표 경로에서 소비됐다.
        let before_text: f64 = if owned_row.is_some() {
            0.0
        } else {
            (0..tac_table_line_idx.unwrap_or(0))
                .map(|line| fmt.line_advance(line))
                .sum()
        };
        let advance = hwpunit_to_px(
            (table.common.width as i32)
                .saturating_add(i32::from(table.outer_margin_left))
                .saturating_add(i32::from(table.outer_margin_right)),
            self.dpi,
        );
        // total_height에는 host 문단 간격도 들어 있다. 점유 줄 상자는 표의
        // 측정 높이와 바깥 여백만 쓰고, 문단 간격은 기존 회계가 한 번 소비한다.
        let band_height = ft.effective_height
            + hwpunit_to_px(
                i32::from(table.outer_margin_top) + i32::from(table.outer_margin_bottom),
                self.dpi,
            );
        let exclusions: Vec<_> = st.side_wrap_exclusions.values().cloned().collect();
        let natural_top = st.current_height + before_text;
        let mut side_wrap_placement = super::float_placement::place_inline_box(
            (column.x + left)..(column.x + column.width - right),
            column.y + natural_top.max(st.inline_box_flow_bottom),
            advance,
            band_height,
            style.map_or(crate::model::style::Alignment::Left, |s| s.alignment),
            &exclusions,
            self.dpi,
        )
        .map(|mut placement| {
            placement.clearance = (placement.y - column.y - natural_top).max(0.0);
            placement
        });
        let clearance = side_wrap_placement.map_or(0.0, |p| p.clearance);
        // 회피 프레임에서 수용한 원본 개체 줄은 본체·바깥여백·뒤 간격을
        // 하나의 끝점으로 발행한다. 저장 줄 상한이 이 공간을 회수하거나
        // paint가 같은 간격을 다시 추측하지 않게 한다.
        let stored_wrap_row = controls::stored_tac::side_wrap_row(
            para,
            ctrl_idx,
            table,
            ft.effective_height,
            fmt,
            next_para,
            next_para
                .and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
                .map_or(0.0, |style| style.spacing_before),
            st.profile,
            side_wrap_placement.is_some(),
            self.render_normalization.table_text_reflowed(table),
            self.dpi,
        );
        let resolve_wrap_row = |placement: Option<super::float_placement::InlineBoxPlacement>,
                                column: crate::renderer::page_layout::LayoutRect,
                                origin: f64| {
            stored_wrap_row.map(|(occupied, trailing)| {
                let mut placement =
                    placement.unwrap_or(super::float_placement::InlineBoxPlacement {
                        x: column.x + left,
                        y: column.y + origin,
                        clearance: 0.0,
                        resolved_x: false,
                        stored_column_frame: None,
                        stored_horizontal_pen: None,
                        advance_end: None,
                    });
                let leading = if origin < 1.0 {
                    0.0
                } else {
                    fmt.spacing_before
                };
                placement.y = placement.y.max(column.y + origin + leading);
                placement.clearance = placement.y - column.y - origin;
                placement.advance_end = Some(placement.y - column.y + occupied + trailing);
                placement
            })
        };
        side_wrap_placement =
            resolve_wrap_row(side_wrap_placement, column, natural_top).or(side_wrap_placement);
        let clearance = side_wrap_placement.map_or(clearance, |placement| placement.clearance);
        // 그림 회피로 확정한 물리 줄은 저장 host 줄높이가 작아도 축소되지 않는다.
        // 렌더만 아래로 옮기고 fit에는 짧은 host 높이를 쓰면 쪽 하단을 넘는다.
        let table_outgrew_saved_row = st.profile.session_edited()
            && ft.effective_height > hwpunit_to_px(table.common.height as i32, self.dpi) + 0.5;
        let mut table_height = if side_wrap_placement.is_some() || table_outgrew_saved_row {
            // Edited cell content can outgrow its saved object row even when
            // the table is too wide for an inline side-wrap placement. Fit the
            // same prefix and measured band that paint will actually consume.
            table_height.max(before_text + band_height)
        } else {
            table_height
        };
        // An original TAC owner distinguishes its occupied box from the
        // trailing gap which advances the following line. The gap may end
        // past the body bottom when the following owner starts a new page;
        // fit the closed object box, and still consume the unchanged end.
        let occupied_height_for_fit = if let Some((occupied, _)) = stored_wrap_row {
            occupied
        } else if tac_count > 1
            && st.profile.hwp5_stored_pagination_layout()
            && !st.profile.session_edited()
            && !para.stored_text_partition_is_dirty()
            && !para.cell_format_vpos_dirty
            && !self.render_normalization.table_text_reflowed(table)
            && table.caption.is_none()
        {
            para.line_segs
                .get(tac_seg_idx)
                .filter(|seg| {
                    !is_synthetic_line_seg(seg)
                        && seg.line_spacing >= 0
                        && i64::from(seg.line_height)
                            == i64::from(table.common.height)
                                + i64::from(table.outer_margin_top)
                                + i64::from(table.outer_margin_bottom)
                        && (ft.effective_height
                            - hwpunit_to_px(table.common.height as i32, self.dpi))
                        .abs()
                            <= self.dpi / 7200.0
                })
                .map_or(table_height, |seg| hwpunit_to_px(seg.line_height, self.dpi))
        } else {
            table_height
        };
        let available = st.available_height();
        let fits_after_overlay_shapes =
            st.current_column_has_only_overlay_shapes() && table_height <= available + 12.0;
        let tac_trailing_spacing_for_fit = if hwpx_rowbreak_tac_missing_owned_line {
            (fmt.total_height - fmt.height_for_fit).max(0.0)
        } else {
            0.0
        };
        let saved_tac_table_frame_height =
            stored_tac_table_frame_height(table, self.dpi, table_height);
        let current_page_vpos_base = st.vpos_page_base.unwrap_or(0);
        let saved_tac_table_bottom_fits = !hwpx_rowbreak_tac_missing_owned_line
            && !table_outgrew_saved_row
            && Some(current_page_vpos_base)
                .and_then(|base| {
                    para.line_segs
                        .get(tac_seg_idx)
                        .and_then(|seg| line_seg_visible_bounds_px(seg, base, self.dpi))
                })
                .is_some_and(|bounds| {
                    saved_table_bounds_fit_at_flow_tail(
                        bounds,
                        st.current_height,
                        available,
                        saved_tac_table_frame_height,
                    )
                });
        // [#3837] 저장 vpos 되돌아감은 한글이 이 표를 다음 쪽 맨 위에 뒀다는 신호다
        // (21967401 응시원서: 직전 항목 vpos=41645 인데 이 표는 1000).
        // 이 문단이 이 쪽에서 이미 시작했으면 걸지 않는다 — 되돌아감은 "이 문단이 새 쪽에서
        // 시작한다"는 뜻이라 이미 시작한 뒤에 걸면 문단을 쪼갠다(156483831: 그림은 4쪽,
        // 같은 문단의 표만 5쪽으로 밀려 4->5쪽).
        let same_para_already_placed = st
            .current_items
            .iter()
            .any(|it| page_item_para_index(it) == Some(para_idx));
        let stored_vpos_rewind_break = st.col_count == 1
            && !st.current_items.is_empty()
            && !same_para_already_placed
            && st.current_height >= available * STORED_VPOS_REWIND_MIN_FILL
            && stored_vpos_rewinds(prev_stored_vpos, para);
        if (st.current_height + clearance + occupied_height_for_fit + tac_trailing_spacing_for_fit
            > available
            && (!fits_after_overlay_shapes || side_wrap_placement.is_some())
            && (!saved_tac_table_bottom_fits || side_wrap_placement.is_some())
            && !st.current_items.is_empty())
            || stored_vpos_rewind_break
        {
            let mut prefix_carried_separately = false;
            if tac_table_line_idx
                .is_some_and(|owner| crate::renderer::composer::owned_tac_prefix_rows(para, owner))
                && before_text > 0.0
                && st.current_height + fmt.line_content_height(0..tac_table_line_idx.unwrap(), 0.0)
                    <= available
                && !st.pre_emitted_host_paras.contains(&para_idx)
            {
                // Consume the real prefix on this page before carrying only
                // the object row. Its height is no longer in the next fragment.
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: 0,
                    end_line: tac_table_line_idx.unwrap(),
                });
                st.advance_flow_by(before_text);
                st.mark_pre_emitted_host(para_idx);
                table_height -= before_text;
                prefix_carried_separately = true;
            }
            st.advance_column_or_new_page();
            // A bare object row without saved LineSeg uses the formatted
            // table band. Its old-column paragraph-before band is not part
            // of the new column's object box: paint starts this row at the
            // column top and retains only the table's own outer top margin.
            // Stored rows and visible text prefixes have their own origins.
            if para.line_segs.is_empty() && !para_has_non_whitespace_text(para) {
                let outer_top = hwpunit_to_px(table.outer_margin_top as i32, self.dpi);
                table_height -= ft.host_spacing.before - outer_top;
            }
            // 이전 단의 그림은 새 단을 점유하지 않는다. 이미 확정한 다른 표의 metadata는
            // flush가 전 단에 보존하고 이 표는 새 단의 기존 배치 정책으로 시작한다.
            side_wrap_placement = None;
            side_wrap_placement = resolve_wrap_row(
                side_wrap_placement,
                st.inline_flow_column(),
                st.current_height,
            );
            if prefix_carried_separately {
                // Publish the next column's object-row origin to paint too.
                // A whole TAC wider than the column still owns that row; it
                // must not recover the preceding page's stored host origin.
                let next_column = st.inline_flow_column();
                side_wrap_placement = super::float_placement::place_inline_box(
                    (next_column.x + left)..(next_column.x + next_column.width - right),
                    next_column.y + st.current_height,
                    advance,
                    band_height,
                    style.map_or(crate::model::style::Alignment::Left, |s| s.alignment),
                    &[],
                    self.dpi,
                )
                .or(Some(super::float_placement::InlineBoxPlacement {
                    x: next_column.x + left,
                    y: next_column.y + st.current_height,
                    clearance: 0.0,
                    resolved_x: true,
                    advance_end: None,
                    stored_horizontal_pen: None,
                    stored_column_frame: None,
                }));
            }
        }

        // [#8474] 단 맨 위에서는 저장 첫 줄이 증언하는 쪽 위 간격을 원점에 둔다.
        // paint 는 이 계획의 원점을 그대로 쓴다(`layout_table_control_block`).
        let leading_spacing = if st.current_height < 1.0 {
            crate::renderer::stored_line_ladder::stored_column_top_spacing(
                para,
                fmt.spacing_before,
                (st.profile.hwp5_stored_pagination_layout() || st.profile.hwpx_stored_layout())
                    && !st.profile.session_edited(),
                self.dpi,
            )
        } else {
            fmt.spacing_before
        };
        if let Some(mut placement) = side_wrap_placement {
            st.advance_flow_by(placement.clearance);
            let placement_column = st.inline_flow_column();
            placement.x -= placement_column.x;
            placement.y -= placement_column.y;
            st.record_inline_placement((para_idx, ctrl_idx), placement);
            st.invalidate_vpos_after_clearance(placement.clearance);
        }
        if let Some(row) = owned_row.filter(|_| side_wrap_placement.is_none()) {
            // 가로 펜과 점유 높이의 일치는 세로 원점의 증거가 아니다.
            // 원본 줄과 현재 단의 축이 실제 펜까지 일치할 때만 세로 끝을 발행한다.
            let stored_vertical_pen =
                crate::renderer::composer::control_slot_line_index(para, ctrl_idx)
                    .and_then(|owner| para.line_segs.get(owner))
                    .filter(|line| {
                        line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                            == 0
                    })
                    .and_then(|line| {
                        let previous = controls::stored_tac::owned_row::preceding_owned_row_top(
                            para,
                            para_idx,
                            ctrl_idx,
                            &st.inline_placements,
                            self.dpi,
                        );
                        let base = st.vpos_page_base.or(st.vpos_lazy_base).or_else(|| {
                            (st.current_items.is_empty()
                                && st.current_height == 0.0
                                && line.vertical_pos == 0)
                                .then_some(0)
                        });
                        let top = previous.or_else(|| {
                            Some(
                                st.vpos_col_anchor
                                    + hwpunit_to_px(
                                        line.vertical_pos.checked_sub(base?)?,
                                        self.dpi,
                                    ),
                            )
                        })?;
                        ((top - st.current_height).abs() <= self.dpi / 7200.0).then_some(top)
                    });
            let owns_vertical_frame = st.profile.session_edited() || stored_vertical_pen.is_some();
            st.record_inline_placement(
                (para_idx, ctrl_idx),
                super::float_placement::InlineBoxPlacement {
                    x: row.horizontal_pen,
                    resolved_x: false,
                    y: st.current_height,
                    clearance: 0.0,
                    advance_end: owns_vertical_frame.then_some(st.current_height + table_height),
                    stored_horizontal_pen: Some(row.horizontal_pen),
                    stored_column_frame: None,
                },
            );
        }
        // place_table_with_text의 후속 텍스트가 새 단으로 넘어가면 flush가 폐기한다.
        // 호출 뒤 갱신하면 이전 단의 표 하단을 새 단에 유출할 수 있다.
        st.record_inline_flow_bottom(
            st.current_height.max(st.inline_box_flow_bottom)
                + if st.pre_emitted_host_paras.contains(&para_idx) {
                    0.0
                } else {
                    before_text
                }
                + band_height,
        );
        if let Some(mut placement) = controls::physical_tac::prepare(
            para,
            ctrl_idx,
            next_para,
            next_para
                .and_then(|next| styles.para_styles.get(next.para_shape_id as usize))
                .map_or(0.0, |style| style.spacing_before),
            fmt,
            ft.effective_height,
            st.profile,
            self.render_normalization.inline_host_frame_expanded(table),
            st.current_height,
            leading_spacing,
            st.available_height(),
            st.stored_tac_line_frame(para, next_para, styles),
            self.dpi,
        ) {
            // 회피로 확정한 가로 원점도 보존한다. 흐름 끝을 paint에 전달하고
            // 뒤 문단의 cap이 그 물리 간격을 다시 회수하지 않게 한다.
            if let Some(inline) = st.inline_placements.get(&(para_idx, ctrl_idx)) {
                placement.inline.x = inline.x;
                placement.inline.clearance = inline.clearance;
            }
            let end = placement.end;
            st.commit_stored_tac_control(para_idx, placement);
            st.record_inline_flow_bottom(end);
            st.protect_current_ladder_floor();
            return;
        }
        self.place_table_with_text(
            st,
            para_idx,
            ctrl_idx,
            para,
            table,
            fmt,
            st.current_height,
            table_height,
            is_first_placed,
            is_last_placed,
            // 이 형상은 host LINE_SEG가 표의 물리 하단을 전혀 나타내지 않는다.
            // 표 뒤 일반 문단도 실제 표 하단을 기준으로 trailing spacing까지 포함해
            // 한 번 엄격하게 적합성을 판정해야 다음 쪽으로 올바르게 이월된다.
            ft.strict_following_plain_text_fit
                || hwpx_rowbreak_tac_missing_owned_line
                || unstored_cell_band
                || self.render_normalization.inline_host_frame_expanded(table),
            styles,
        );
        if let Some(end) = side_wrap_placement.and_then(|placement| placement.advance_end) {
            // 같은 줄은 텍스트 꼬리나 각주를 소유하지 않으므로 별도 이월이 없다.
            // 원본 줄의 수용 끝을 예약·paint·다음 내용의 시작에 공통 적용한다.
            st.align_flow_to(end);
            st.record_inline_flow_bottom(end);
        }
        // [#5699 H1] 교정 계상으로 확보한 표 밴드 하단을 흐름 바닥으로 고정 —
        // 후속 문단의 저장 vpos 스냅이 밴드 위로 되감지 못한다(쪽/단 단위 리셋).
        if owns_tac_band || side_wrap_placement.is_some() {
            st.protect_current_ladder_floor();
        }
    }

    /// [#2279 TAC host] 모순 조합(treat_as_char=true + wrap=자리차지) 표의
    /// host 빈 줄박스 높이 (한글 fresh 가 표 위에 별도 배치하는 성분).
    ///
    /// 정상 문서의 TAC 표는 줄박스에 포함되어 별도 가산이 없다 — 본 판정은
    /// 기계생성 결재문서 특유의 모순 조합 + 빈 host 문단에만 발동한다.
    /// 반환 = host 첫 글자모양의 폰트 크기(px) — 한글 PDF 괘선 실측
    /// (36392557 pi27: 진입 22px ≈ om_top 1.9 + 15pt 줄박스 20px)과 정합.
    fn tac_topbottom_conflict_host_line_px(
        &self,
        para: &Paragraph,
        table: &crate::model::table::Table,
        styles: &ResolvedStyleSet,
    ) -> Option<f64> {
        if !table.common.treat_as_char
            || !matches!(
                table.common.text_wrap,
                crate::model::shape::TextWrap::TopAndBottom
            )
            || para_has_non_whitespace_text(para)
        {
            return None;
        }
        let cs_id = para
            .char_shape_id_at(0)
            .or_else(|| para.char_shapes.first().map(|cs| cs.char_shape_id))?
            as usize;
        let font_size = styles.char_styles.get(cs_id)?.font_size;
        if font_size <= 0.0 {
            return None;
        }
        Some(font_size)
    }

    /// 표를 pre-text/table/post-text와 함께 배치한다 (Paginator place_table_fits 동일).
    #[allow(clippy::too_many_arguments)]
    fn place_table_with_text(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        ctrl_idx: usize,
        para: &Paragraph,
        table: &crate::model::table::Table,
        fmt: &FormattedParagraph,
        para_start_height: f64,
        table_total_height: f64,
        is_first_placed: bool,
        is_last_placed: bool,
        strict_following_plain_text_fit: bool,
        styles: &ResolvedStyleSet,
    ) {
        // [#2279 footer-오염] PAGE-앵커 Top 절대배치 표 기록 — 같은 쪽 후속
        // footer 의 저장 vpos 동기화 차단용. 이 표들의 저장 누적은 절대 위치
        // 산물이라 본문 흐름 좌표가 아니다(36496000 pi3 실측).
        if !table.common.treat_as_char
            && matches!(
                table.common.vert_rel_to,
                crate::model::shape::VertRelTo::Page
            )
            && matches!(table.common.vert_align, crate::model::shape::VertAlign::Top)
        {
            st.mark_page_absolute_top_table();
        }
        let vertical_offset = Self::get_table_vertical_offset(table);
        // [#7687] 글자 없는 host 라도 자리차지 표가 둘 이상이고 양수 오프셋 표가 있으면 한/글은
        // 글 있는 host 와 같은 공동 앵커 모델(첫 띠는 흐름 전진, 양수 오프셋은 배제 띠, host 줄은
        // 첫 띠 아래)로 조판한다 — 술어·근거는 `is_textless_coanchored_float_host`.
        let is_textless_coanchored_host = is_textless_coanchored_float_host(para);
        let is_visible_para_float = is_para_topbottom_float(&table.common)
            && (para_has_non_whitespace_text(para)
                || is_textless_coanchored_host
                || crate::renderer::float_placement::whitespace_host_line_below_float(para));
        // 단 오른쪽 밖으로 통째로 벗어난 자리차지 개체는 본문 세로 공간을 차지하지
        // 않는다(재현 문서 D: horz=단 227.6mm, A4 폭 210mm — 화면 밖). 이 계약은
        let signed_vertical_offset = vertical_offset as i32;
        let total_lines = fmt.line_heights.len();
        // [#5871] 공백만 있는 host 문단이 두 술어 사이 틈에 빠진다 —
        // `is_visible_para_float` 는 공백을 글자로 안 세는데(`para_has_non_
        // whitespace_text`) 아래 pre-text 판정은 `!para.text.is_empty()` 라 공백
        // 한 칸도 글자로 셌다. 그 결과 저장 줄상자를 표 앞 텍스트로 한 번 방출하고
        // 그 아래에 같은 표를 다시 그려 표가 제 높이만큼 밀렸다(10895 [별표 3]
        // 8쪽 둘째 표 667.7 → 1012.7, 본문 하한 1028.1 초과·쪽번호와 겹침).
        //
        // 다만 "공백=무텍스트" 로만 넓히면 저장 줄상자가 표와 무관한 문서에서
        // 쪽이 늘어난다(19952675 서식 6→7, 한글 6). 발동은 **저장 줄상자가 이미
        // 표를 담고 있다는 증거**가 있을 때로 한정한다 — 첫 저장 줄의 lh 가
        // 표 높이 + 위·아래 바깥여백 이상(10895: lh 24276 = 23710+283+283).
        let whitespace_host_line_covers_table = !para_has_non_whitespace_text(para)
            && !para.text.is_empty()
            && para
                .line_segs
                .iter()
                .find(|ls| !is_synthetic_line_seg(ls))
                .is_some_and(|ls| {
                    i64::from(ls.line_height)
                        >= i64::from(table.common.height.min(i32::MAX as u32))
                            + i64::from(table.outer_margin_top)
                            + i64::from(table.outer_margin_bottom)
                            - 10
                });
        // 저장 줄이 없는 host 의 Square 표: 글자 띠는 표 기하로 도출한다(layout 과 같은
        // helper). 띠가 없으면(표가 단 폭을 채움) 글자는 옆으로 흐를 수 없어 표 **아래**로
        // 간다 — 양수 세로 오프셋이어도 표 앞 글자로 방출하지 않는다.
        let no_lineseg_square_host = !table.common.treat_as_char
            && matches!(
                table.common.text_wrap,
                crate::model::shape::TextWrap::Square
            )
            && crate::renderer::is_no_lineseg_visible_text_host(para);
        let col_w_hu = crate::renderer::px_to_hwpunit(
            st.layout
                .column_areas
                .get(st.current_column as usize)
                .map_or(st.layout.body_area.width, |area| area.width),
            self.dpi,
        );
        let no_lineseg_square_band = no_lineseg_square_host
            .then(|| crate::renderer::no_lineseg_square_table_host_band(para, col_w_hu))
            .flatten();
        // 쪽·종이 기준 표는 host 흐름 밖이라 host 글자를 표 아래로 보내지 않는다(#7548,
        // layout 의 host 줄 페인트 소유자와 같은 판정).
        let no_lineseg_host_flows_below = no_lineseg_square_host
            && crate::renderer::no_lineseg_host_text_flows_below_square_table(para, col_w_hu)
            && fmt.square_host_plan.is_none();
        // Corroborate the existing table-height row with the control's stored
        // stream position. Whitespace-only hosts can own real prefix rows;
        // PUA carriers retain their specialized filler placement owner.
        let tac_table_line_idx = self.tac_table_line_index(para, table, fmt);
        // [#8782] 글자 없는 host 의 저장 필드 시작 줄도 표 앞 줄이다.
        let has_owned_tac_prefix = para.char_offsets.len() == para.text.chars().count()
            && tac_table_line_idx.is_some_and(|line| {
                crate::renderer::composer::owned_tac_prefix_rows(para, line)
                    && crate::renderer::layout::control_line_seg_index(para, ctrl_idx) == Some(line)
            });
        let split_host_prefix = st
            .paragraph_float_placements
            .get(&(para_idx, ctrl_idx))
            .and_then(|placement| placement.split_host_prefix());
        let pre_table_end_line = if let Some(prefix) = split_host_prefix {
            prefix
        } else if !is_visible_para_float
            && signed_vertical_offset > 0
            && !para.text.is_empty()
            && !whitespace_host_line_covers_table
            // 앞·뒤 저장 줄로 확정한 표 뒤 호스트는 pre-text가 아니다.
            // 같은 저장 원점에서 post-text로 한 번만 배치·전진한다.
            && !st
                .paragraph_float_placements
                .get(&(para_idx, ctrl_idx))
                .is_some_and(|placement| {
                    placement.stored_host_origin.is_some_and(|origin| {
                        placement.table_top < origin && placement.occupied_bottom <= origin
                    })
                })
            // 확정 프레임이 있고 저장 앵커가 앞쪽에서 소진된 경우에만
            // 그 공백 줄을 이월된 표 앞에 다시 방출하지 않는다.
            // 현재 쪽의 일반 공백 줄은 기존 점유 높이를 유지한다.
            && !(st.paragraph_float_placements.contains_key(&(para_idx, ctrl_idx))
                && !st.profile.session_edited()
                && crate::renderer::float_placement::para_offset_consumed_by_page_break(
                    para, table, st.base_available_height(), self.dpi,
                ))
            && !no_lineseg_host_flows_below
            && fmt.square_host_plan.is_none()
        {
            total_lines
        } else if table.common.treat_as_char
            && total_lines > 1
            && (has_owned_tac_prefix
                || para.text.chars().any(|ch| {
                    !ch.is_whitespace()
                        && ch > '\u{001F}'
                        && ch != '\u{FFFC}'
                        && !('\u{E000}'..='\u{F8FF}').contains(&ch)
                        && (ch as u32) < 0xF0000
                }))
        {
            // Keep the legacy text-host route when source positions are absent;
            // mapped hosts use row ownership rather than glyph visibility.
            tac_table_line_idx.unwrap_or(0)
        } else {
            0
        };

        // [Task #439] Square wrap (어울림) 표 식별.
        // 어울림 표는 호스트 문단 텍스트와 같은 수직 영역에 배치되므로
        // current_height 누적은 max(host_text, v_off + table) 한 번만.
        // engine.rs:1328 와 동일 시멘틱.
        let is_wrap_around_table = !table.common.treat_as_char
            && matches!(
                table.common.text_wrap,
                crate::model::shape::TextWrap::Square
            );

        // pre-table 텍스트 (첫 번째 표에서만)
        // [참고2 fix] 배열순서가 아닌 배치순서 기준 (typeset_table_paragraph 산출).
        let is_first_table = is_first_placed;
        if split_host_prefix.is_some() {
            st.finish_deferred_host_line();
        }
        let defer_host_line = st.defer_host_line_item_para == Some(para_idx);
        let pre_height: f64 = if pre_table_end_line > 0
            && is_first_table
            && !st.pre_emitted_host_paras.contains(&para_idx)
        {
            let h = fmt
                .host_text_bounds(para, 0..pre_table_end_line, self.dpi)
                .1;
            if !defer_host_line {
                st.record_host_text_fragment(para_idx, 0..pre_table_end_line, para, fmt, self.dpi);
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: 0,
                    end_line: pre_table_end_line,
                });
            }
            h
        } else {
            0.0
        };

        // 표 배치
        // [#2243] 표가 컬럼 첫 항목이면 vpos 앵커 확립 — 표 경로는
        // vpos_snap_current_height 를 거치지 않아 page_base 가 미확립으로 남고,
        // 후속 문단 스냅이 드리프트 역산 lazy base(-796HU 등)로 고착되던 결함.
        // 저장 lineseg 가 개체 높이를 온전히 포함하는 호스트(기계생성 결재문서
        // lh = 표 + outMargin)로 한정한다.
        if st.profile.hwpx_stored_layout()
            && st.col_count == 1
            && st.current_items.is_empty()
            && pre_height <= 0.5
        {
            if let Some(s0) = para.line_segs.first() {
                let stored =
                    s0.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0;
                let covers = s0.line_height as i64
                    >= table.common.height as i64
                        + table.outer_margin_top as i64
                        + table.outer_margin_bottom as i64;
                if stored && covers {
                    st.record_vpos_column_anchor(st.current_height);
                    st.record_vpos_page_origin(Some(s0.vertical_pos));
                    st.record_vpos_lazy_origin(None);
                    st.record_vpos_origin_provenance(true);
                    st.record_vpos_ladder_validity(false);
                }
            }
        }
        // 저장 줄이 없는 단일 TAC 표와 뒤 본문은 같은 확정 줄 구성을 소비한다.
        // 표 본체만 전진한 뒤 표 전용 상한으로 본문 줄을 지우지 않도록,
        // 개체 줄의 여백·뒤 간격까지 포함한 끝점을 paint에도 전달한다.
        let computed_table_body_height = hwpunit_to_px(table.common.height as i32, self.dpi);
        let computed_table_outer_height = hwpunit_to_px(
            i32::from(table.outer_margin_top) + i32::from(table.outer_margin_bottom),
            self.dpi,
        );
        let computed_table_row_end = if crate::renderer::para_has_no_stored_line_segs(para)
            && is_first_table
            && is_last_placed
            && table.common.treat_as_char
            && matches!(
                table.common.text_wrap,
                crate::model::shape::TextWrap::TopAndBottom
            )
            && self.tac_table_line_index(para, table, fmt) == Some(0)
            && fmt.line_count() > 1
            && fmt.line_spacings[0] >= 0.0
            && (fmt.line_heights[0] - computed_table_body_height).abs() < 1.0
            && (table_total_height - computed_table_body_height).abs() < 1.0
        {
            let origin = st.current_height;
            // 재구성한 개체 줄은 본체 높이만 담고, 문단 포맷의 별도 여백 예약을
            // 개체 줄 끝에 한 번 소비한다. 저장 줄의 외곽 높이에는 적용하지 않는다.
            let end = origin + fmt.line_advance(0) + computed_table_outer_height;
            st.record_inline_placement(
                (para_idx, ctrl_idx),
                super::float_placement::InlineBoxPlacement {
                    x: 0.0,
                    y: origin,
                    clearance: 0.0,
                    resolved_x: false,
                    advance_end: Some(end),
                    stored_horizontal_pen: None,
                    stored_column_frame: None,
                },
            );
            Some(end)
        } else {
            None
        };
        // 실제 수용한 독립 개체 줄의 pen을 paint에 전달한다. 후행 표가 이미 소비한
        // 앞 표의 줄 오프셋을 다시 더하지 않도록 저장/현재 줄의 좌표계를 구분한다.
        let composed_table_row_origin = crate::renderer::composer::composed_tac_row(para, ctrl_idx)
            .filter(|&row| {
                fmt.line_count() == para.line_segs.len()
                    && self.is_effective_tac_table(para, table, fmt)
                    && fmt.line_heights.get(row).is_some_and(|height| {
                        (*height - table_total_height).abs() <= self.dpi / 7200.0
                    })
            })
            .map(|_| st.current_height + pre_height);
        let mut stored_table_row_origin = None;
        // 단일 원본 개체 줄의 원점은 실제 수용 끝에서 같은 줄 전진을 제외해 얻는다.
        // 문단 위 간격을 소비하기 전의 커서나 저장 제품군으로 원점을 추정하지 않는다.
        // 공백 호스트도 같은 단일 줄을 소유한다. 앞뒤 가시 텍스트나 별도 prefix
        // 줄의 소비는 기존 경로가 맡고, 공백의 수평 advance/정렬은 유지한다.
        let stored_single_row_source = (!st.profile.session_edited()
            && is_first_placed
            && is_last_placed
            && table.common.treat_as_char
            && !para_has_non_whitespace_text(para)
            && para.controls.len() == 1
            && para.line_segs.len() == 1
            && fmt.line_heights.len() == 1
            && fmt.line_spacings.len() == 1
            && fmt.line_spacings[0] >= 0.0
            && !para.stored_text_partition_is_dirty()
            && !para.cell_format_vpos_dirty
            && !self.render_normalization.table_text_reflowed(table)
            && !st.inline_placements.contains_key(&(para_idx, ctrl_idx)))
        .then(|| {
            let line = &para.line_segs[0];
            let outer_band = i64::from(table.common.height)
                + i64::from(table.outer_margin_top)
                + i64::from(table.outer_margin_bottom);
            if is_synthetic_line_seg(line)
                || i64::from(line.line_height) != outer_band
                || (fmt.line_heights[0] - hwpunit_to_px(line.line_height, self.dpi)).abs()
                    > hwpunit_to_px(1, self.dpi)
            {
                return None;
            }
            // 쪽 기준이 없는 첫 원본 줄도 실제 수용 후 원점을 검증할 수 있게
            // Source 좌표와 배치 전의 빈 단 상태를 보존한다.
            Some((
                line.vertical_pos,
                // 텍스트 누적 끝에서 역산한 lazy base는 개체 줄의 물리
                // 쪽 원점을 증명하지 않는다. 그 축에서 현재 커서와 같다는
                // 이유로 표 paint를 덮어쓰면 앞 저장 본문 위로 되감긴다.
                st.vpos_page_base,
                st.col_count == 1
                    && st.current_items.is_empty()
                    && st.current_height.abs() <= hwpunit_to_px(1, self.dpi),
            ))
        })
        .flatten();
        // 원본 개체 전용 줄은 본체와 바깥 여백을 함께 예약한다. 별도 Table
        // 항목으로 방출해도 수용한 줄 pen을 잃지 않아야 paint가 위 여백을
        // 한 번 소비한다. 절대 저장 vpos 대신 현재 단의 실제 수용 원점을 넘긴다.
        if st.profile.hwp5_stored_pagination_layout()
            && !st.profile.session_edited()
            && table.common.treat_as_char
            && para.text.is_empty()
            && !para.stored_text_partition_is_dirty()
            && !para.cell_format_vpos_dirty
            && !self.render_normalization.table_text_reflowed(table)
            && !st.inline_placements.contains_key(&(para_idx, ctrl_idx))
        {
            if let Some(line_index) =
                crate::renderer::layout::control_line_seg_index(para, ctrl_idx)
            {
                let owns_line = para.controls.iter().enumerate().all(|(index, control)| {
                    matches!(control, Control::Table(other) if other.common.treat_as_char
                        && (index == ctrl_idx
                            || crate::renderer::layout::control_line_seg_index(para, index)
                                != Some(line_index)))
                });
                let outer_band = i64::from(table.common.height)
                    + i64::from(table.outer_margin_top)
                    + i64::from(table.outer_margin_bottom);
                let origin = st.current_height + pre_height;
                let source_origin = para.line_segs.get(line_index).and_then(|line| {
                    let base = st.vpos_page_base.or(st.vpos_lazy_base).unwrap_or(0);
                    line.vertical_pos.checked_sub(base)
                });
                // 줄 높이의 일치만으로 현재 커서를 저장 줄의 원점으로 확정할
                // 수 없다. 같은 원본 쪽 기준으로 환산한 줄 pen도 일치해야 한다.
                // 앞 내용/개체가 이동한 경우 기존 원점 조회를 덮어쓰지 않는다.
                let source_pen_is_accepted = source_origin.is_some_and(|position| {
                    position >= 0
                        && (hwpunit_to_px(position, self.dpi) - origin).abs()
                            <= hwpunit_to_px(2, self.dpi)
                });
                if owns_line
                    && source_pen_is_accepted
                    && para.line_segs.get(line_index).is_some_and(|line| {
                        !is_synthetic_line_seg(line)
                            && i64::from(line.line_height) == outer_band
                            && line.line_spacing >= 0
                    })
                    && table_total_height + 0.5
                        >= computed_table_body_height + computed_table_outer_height
                {
                    stored_table_row_origin = Some(origin);
                }
            }
        }
        st.append_item(PageItem::Table {
            para_index: para_idx,
            control_index: ctrl_idx,
        });

        // [Task #439] 누적 정책:
        // - Square wrap (어울림): max(pre_height, v_off + table_total)
        //     호스트 텍스트와 표가 같은 y 영역을 공유하므로 더 큰 쪽만 누적.
        // - 그 외 (TopAndBottom 등): pre_height + table_total 합산 (기존 동작).
        // 전폭 TAC 표가 자기 줄(line index = pre_table_end_line)에 놓인 split 케이스:
        // table_total_height(=fmt.height_for_fit)는 pre-text 줄까지 포함하므로 pre_height
        // 를 따로 더하면 이중 계산이 된다. 또 표가 차지한 줄은 post-text 에서 제외해야 한다.
        // (Task #853)
        let tac_wrap_split = table.common.treat_as_char
            && pre_table_end_line > 0
            && pre_table_end_line < total_lines;
        let has_preceding_coanchored_float = is_visible_para_float
            && para.controls.iter().take(ctrl_idx).any(|control| {
                matches!(control, Control::Table(previous)
                    if is_para_topbottom_float(&previous.common))
            });
        let issue2439_visible_host_stack = st.profile.hwp5_stored_pagination_layout()
            && st.col_count == 1
            && st.current_zone_y_offset.abs() < 0.5
            && is_visible_para_float
            // [#7687] 글자 없는 다중 자리차지 host 의 저장 사다리는 양수 오프셋 표를 흐름에
            // 싣지 않는다(hwpspec pi=130: host 줄 10810 = 첫 띠 끝). 서명문 host 전용이다.
            && para_has_non_whitespace_text(para)
            && signed_vertical_offset > 0
            && has_preceding_coanchored_float
            && para
                .controls
                .iter()
                .filter(|control| matches!(control, Control::Table(_)))
                .count()
                == 2
            && para.line_segs.iter().any(|seg| !is_synthetic_line_seg(seg));

        let page_anchored_square = is_wrap_around_table
            && matches!(
                table.common.vert_rel_to,
                crate::model::shape::VertRelTo::Page | crate::model::shape::VertRelTo::Paper
            );
        // 저장 줄이 없는 host 의 Square 표는 host 글자가 표 옆 띠로 흐른다 — 띠는 표
        // 기하로 도출한다(layout 이 같은 helper 로 글자를 그린다). 표 앞 글자로 분류되지
        // 않는 음수·0 세로 오프셋에서도 흐름은 [Task #439] 와 같이 max(글자, 표) 한 번만
        // 전진하고, 같은 글자를 표 아래 post-text 로 다시 쌓지 않는다.
        let no_lineseg_band_host = is_wrap_around_table
            && is_first_table
            && pre_height <= 0.0
            && (fmt.square_host_plan.is_some() || no_lineseg_square_band.is_some());
        if is_wrap_around_table
            && crate::renderer::para_has_no_stored_line_segs(para)
            && matches!(
                table.common.vert_rel_to,
                crate::model::shape::VertRelTo::Para
            )
            && matches!(
                table.common.horz_rel_to,
                crate::model::shape::HorzRelTo::Column | crate::model::shape::HorzRelTo::Para
            )
            && matches!(
                table.common.horz_align,
                crate::model::shape::HorzAlign::Left
            )
        {
            let column = st.inline_flow_column();
            let x0 =
                column.x + hwpunit_to_px(signed_hwpunit(table.common.horizontal_offset), self.dpi);
            let x1 = x0
                + hwpunit_to_px(table.common.width as i32, self.dpi)
                + hwpunit_to_px(i32::from(table.outer_margin_left), self.dpi)
                + hwpunit_to_px(i32::from(table.outer_margin_right), self.dpi);
            let top = para_start_height + hwpunit_to_px(signed_vertical_offset, self.dpi);
            let bottom = top
                + hwpunit_to_px(i32::from(table.outer_margin_top), self.dpi)
                + hwpunit_to_px(table.common.height as i32, self.dpi)
                + hwpunit_to_px(i32::from(table.outer_margin_bottom), self.dpi);
            st.record_unstored_square_box(para_idx, x0..x1, top..bottom);
        }
        // 저장 줄이 없는 **빈** host 의 전폭 Square 표: 표는 오프셋·바깥여백 위 아래에
        // 놓이고 host 빈 줄은 표 아래로 내려간다(layout 과 같은 helper).
        let empty_square_host_geometry = (is_wrap_around_table && is_first_table)
            .then(|| {
                let col_w_px = st
                    .layout
                    .column_areas
                    .get(st.current_column as usize)
                    .map_or(st.layout.body_area.width, |area| area.width);
                crate::renderer::unstored_empty_square_table_host_geometry_px(
                    para,
                    table,
                    col_w_px,
                    styles,
                    styles.para_styles.get(para.para_shape_id as usize),
                    self.dpi,
                )
            })
            .flatten();
        if no_lineseg_band_host {
            let v_off_px = crate::renderer::hwpunit_to_px(signed_vertical_offset, self.dpi);
            let host_h = if fmt.square_host_plan.is_some() {
                fmt.total_height
            } else {
                fmt.line_advances_sum(0..total_lines)
            };
            let host_origin = st.current_height;
            let advance = if fmt.square_host_plan.is_some() {
                host_h
            } else {
                host_h.max(v_off_px + table_total_height)
            };
            st.advance_flow_by(advance);
            if let Some(mut plan) = fmt.square_host_plan.clone() {
                plan.relative_to(0.0, -host_origin);
                st.record_square_host_flow(para_idx, plan);
            }
        } else if let Some((table_top, below)) = empty_square_host_geometry {
            st.advance_flow_by(pre_height + table_top + table_total_height + below);
        } else if page_anchored_square {
            // [#7548] 쪽·종이 기준 어울림 표는 앵커 흐름 밖(절대 위치)에 놓인다 — 흐름에는
            // host 본문만 전진하고 표 높이를 예약하지 않는다(layout 의 절대 배치와 짝).
            // 뒤 문단이 표 띠를 피하는 것은 저장 vpos 가 증언한다(36295751 pi=9).
            st.advance_flow_by(pre_height);
            // 저장 줄이 없는 host 면 뒤 재조판 문단이 표 상자를 직접 피한다.
            st.register_page_anchored_square_table(para_idx, ctrl_idx, para, table);
        } else if is_wrap_around_table
            && crate::renderer::float_placement::square_successor_starts_beside_table(
                para,
                st.next_para_lane_probe,
                table,
            )
        {
            // 뒤 소유 항목이 host 텍스트를 소비해도 표는 배타 영역을 남긴다.
            // 같은 host 줄을 표 앞에서 다시 전진시키지 않는다.
            if pre_height <= 0.0 {
                st.register_square_band(st.current_height, st.current_height + table_total_height);
            }
            st.advance_flow_by(pre_height);
        } else if is_wrap_around_table && pre_height > 0.0 {
            let v_off_px = crate::renderer::hwpunit_to_px(vertical_offset as i32, self.dpi);
            let table_bottom = v_off_px + table_total_height;
            // 표 옆 차선에 흡수되는 뒤 문단의 저장 줄은 host 줄 원점에서 잰다. 그 줄이
            // 표 바닥보다 아래까지 이어지면 띠도 그 끝까지 늘어나야 하므로, 앞 글자가
            // 있는 host 도 같은 원점으로 띠를 등록한다(흐름 전진은 그대로).
            let host_origin = st.current_height;
            st.register_square_band(host_origin, host_origin + pre_height.max(table_bottom));
            st.advance_flow_by(pre_height.max(table_bottom));
        } else if is_visible_para_float {
            // 통째 배치의 fit 판정에서 확정한 결과를 그대로 소비한다.
            // 이월 뒤에는 이전 단의 원점으로 배치를 재생성하지 않는다.
            let resolved = st
                .paragraph_float_placements
                .get(&(para_idx, ctrl_idx))
                .copied();
            let v_off_px = hwpunit_to_px(signed_vertical_offset, self.dpi);
            let outer_top_px = hwpunit_to_px(table.outer_margin_top as i32, self.dpi);
            let pushed_anchor_top = crate::renderer::layout::pushed_anchor_line_table_top_px(
                para, table, ctrl_idx, self.dpi,
            );
            let table_top = if let Some(placement) = resolved {
                placement.table_top
            } else if let Some(top) = pushed_anchor_top {
                // [#8435] 앞 TAC 줄 뒤에 앵커돼 그 줄을 밀어낸 표는 앵커 줄 자리(앞 줄 끝)
                // + 바깥 위 여백이 상단이다 — layout 과 같은 helper 를 소비한다.
                para_start_height + top + v_off_px
            } else if signed_vertical_offset > 0 {
                // [#6879] 세로 기준점은 앵커 줄이다 — layout 이 같은 값을 더하므로
                // 흐름 예약도 함께 내려야 배치와 어긋나지 않는다. layout 과 **같은**
                // 게이트(TAC 형제 유무)를 써야 배치와 예약이 갈리지 않는다.
                let anchor_offset_px = crate::renderer::layout::tac_sibling_float_anchor_offset_px(
                    para, table, ctrl_idx, self.dpi,
                );
                let stored_top = para_start_height + anchor_offset_px + outer_top_px + v_off_px;
                // [#2439] 같은 visible host 의 첫 표가 offset=0이면 flow 를 전진시키지만
                // exclusion 은 만들지 않는다. 후행 양수-offset 표의 저장 상단이 그 표
                // 내부에 있으면 한컴은 앞 표 아래로 밀어 전체 높이를 보존한다. 저장
                // 상단/하단만 쓰면 후행 exclusion 높이가 겹친 만큼 잘려 후속 본문이
                // 표 안으로 들어가므로, 이미 소비한 co-anchored flow 를 하한으로 둔다.
                if has_preceding_coanchored_float {
                    let stacked_top = if issue2439_visible_host_stack {
                        // #2439: native HWP의 저장된 다중 visible-host 표는 선행 표에
                        // 밀려난 뒤에도 후행 표 자신의 outer-top을 보존한다. 이를
                        // 빼면 표 스택과 후속 안내문이 매 양식마다 약 3.8px 앞당겨진다.
                        st.current_height + outer_top_px
                    } else {
                        st.current_height
                    };
                    stored_top.max(stacked_top)
                } else {
                    stored_top
                }
            } else if st.profile.hwpx_stored_layout() {
                // HWPX visible float 는 같은 문단 안의 앞선 float 뒤에 이어 쌓인다.
                // B/C처럼 둘 다 non-positive offset 이면 문단 시작점이 아니라 현재 흐름
                // 높이를 기준으로 reserve 해야 layout 의 세로 stacking 과 page break 가 맞는다.
                let flow_at_para_start = (st.current_height - para_start_height).abs() < 0.5;
                st.current_height
                    + if flow_at_para_start {
                        outer_top_px
                    } else {
                        0.0
                    }
                    + v_off_px.max(0.0)
            } else {
                para_start_height + outer_top_px + v_off_px
            };
            // 저장 줄을 재사용하지 못한 visible host도 현재 측정 상자의 원점을
            // 한 번 확정한다. 같은 occupied-band 제약을 통째 배치 경로와 공유하고,
            // paint가 다시 형제 표를 피하면서 흐름 예약과 갈라지지 않게 전달한다.
            let resolved = resolved.or_else(|| {
                (signed_vertical_offset > 0
                    && para_has_non_whitespace_text(para)
                    && !table.common.allow_overlap)
                    .then(|| {
                        table::block::host_placement::HostPlacementConstraint {
                            table,
                            has_preceding_coanchored_float,
                            dpi: self.dpi,
                        }
                        .constrain(
                            crate::renderer::float_placement::ParagraphFloatPlacement {
                                flow:
                                    crate::renderer::float_placement::ParagraphFloatFlow::Exclusion,
                                anchor_y: para_start_height,
                                stored_host_origin: None,
                                stored_successor_line_origin: None,
                                table_left: None,
                                table_top,
                                occupied_bottom: table_top
                                    + table_total_height.max(0.0)
                                    + hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi),
                            },
                            st,
                        )
                    })
            });
            let table_top = resolved.map_or(table_top, |placement| placement.table_top);
            let table_bottom = table_top + table_total_height.max(0.0);
            let table_bottom = if let Some(mut placement) = resolved {
                placement.occupied_bottom += table_top - placement.table_top;
                placement.table_top = table_top;
                st.record_paragraph_float_placement((para_idx, ctrl_idx), placement);
                placement.occupied_bottom
            } else {
                // 흐름을 바로 전진시키는 표는 paint와 같이 아래 바깥여백까지
                // 소비한다. 양수 오프셋의 배제 밴드도 배치(`layout`)의 zone 과 같이 아래
                // 바깥여백까지 담는다 — 한/글 저장 사다리가 띠 끝을 `오프셋 + 위여백 +
                // 높이 + 아래여백` 으로 적는다(hwpspec pi=132 28197, #7687).
                table_bottom + hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi)
            };
            // 단 오른쪽 밖 개체는 배제 영역도 만들지 않는다 — 배제 영역을 만들면
            // 뒤따르는 본문 표가 그만큼 밀려 마지막 블록이 다음 쪽으로 넘어간다.
            if resolved.is_some_and(|placement| placement.split_host_prefix().is_some()) {
                // 앞 줄의 예약·표·뒤 줄은 이미 한 소유 계획으로 확정됐다.
                st.align_flow_to(table_bottom);
            } else if signed_vertical_offset > 0 {
                if table_bottom > table_top + 0.5 {
                    st.add_visible_float_exclusion(VisibleFloatExclusion {
                        para_index: para_idx,
                        top: resolved.map_or(table_top, |p| p.exclusion_top(table, self.dpi)),
                        bottom: table_bottom,
                    });
                }
                if issue2439_visible_host_stack {
                    // 이 저장 형상은 후행 표가 선행 표 아래로 실제 stacking되어
                    // host 흐름을 소비한다. native 일반 float처럼 현재 높이를
                    // 그대로 두면 post-text probe가 outer-top 틈 앞에서 멈춘다.
                    st.align_flow_to(st.current_height.max(table_bottom));
                } else {
                    st.advance_flow_by(pre_height);
                }
            } else {
                let resolved_frame_consumes_flow = resolved.is_some_and(|placement| {
                    placement.flow
                        == crate::renderer::float_placement::ParagraphFloatFlow::CoanchoredTable
                });
                let following_non_positive =
                    has_following_non_positive_visible_float(para, ctrl_idx);
                let inter_float_gap = if !resolved_frame_consumes_flow
                    && st.profile.hwpx_stored_layout()
                    && following_non_positive
                {
                    para_line_spacing_px(para, self.dpi)
                } else {
                    0.0
                };
                st.align_flow_to(st.current_height.max(table_bottom + inter_float_gap));
            }
        } else if let Some(placement) = st
            .paragraph_float_placements
            .get(&(para_idx, ctrl_idx))
            .filter(|placement| {
                placement.flow
                    != crate::renderer::float_placement::ParagraphFloatFlow::StoredSquareWrap
            })
            .copied()
        {
            // 빈 저장 호스트도 닫힌 원본 프레임을 소유할 수 있다.
            // 수용한 물리 하단을 소비하며 호스트·안내 줄을 다시 전진시키지 않는다.
            if let crate::renderer::float_placement::ParagraphFloatFlow::ComputedEmptyHost {
                outer_box_top,
                ..
            } = placement.flow
            {
                st.add_visible_float_exclusion(VisibleFloatExclusion {
                    para_index: para_idx,
                    top: outer_box_top,
                    bottom: placement.occupied_bottom,
                });
                st.align_flow_to(placement.paragraph_end(st.current_height, fmt.spacing_after));
            } else {
                st.align_flow_to(placement.occupied_bottom);
            }
        } else if let Some(end) = computed_table_row_end {
            st.align_flow_to(end);
        } else if tac_wrap_split {
            // 단일 TAC 의 높이는 문단 height_for_fit 이라 앞 글줄을 이미 담는다. 여러 TAC
            // 표는 각자의 저장 줄만 계상하므로(typeset_tac_table) 첫 표 앞 글줄을 따로 더한다.
            // 표 줄이 vpos 를 되감아 새 쪽에서 시작하면 앞 글줄은 앞 쪽의 사다리라 더하지 않는다
            // (1490000-200900057 pi=420: 더하면 같은 쪽 뒤 표가 넘쳐 쪽이 하나 는다).
            let prefix_continues_into_table = pre_table_end_line > 0
                && para
                    .line_segs
                    .get(pre_table_end_line)
                    .zip(para.line_segs.get(pre_table_end_line - 1))
                    .is_some_and(|(table_line, prefix_line)| {
                        table_line.vertical_pos > prefix_line.vertical_pos
                    });
            let per_line_tac_height = prefix_continues_into_table
                && para
                    .controls
                    .iter()
                    .filter(|control| {
                        matches!(control, Control::Table(other)
                        if self.is_effective_tac_table(para, other, fmt))
                    })
                    .count()
                    > 1;
            st.advance_flow_by(
                table_total_height + if per_line_tac_height { pre_height } else { 0.0 },
            );
        } else if let Some(host_spacing_px) = if st.profile.hwpx_stored_layout()
            && is_last_placed
            && total_lines <= pre_table_end_line + 1
            && fmt.spacing_before + fmt.spacing_after > 0.5
            && self
                .tac_topbottom_conflict_host_line_px(para, table, styles)
                .is_some()
        {
            // [#2279 10k] host spacing 가산은 **문단당 1회** — 다중 표 문단에서
            // 표마다 가산하면 중간 표 배치의 fit 이 과대해져 후속 표가 조기
            // 개행된다 (156767148 보도자료 pi7: 표2개 문단, 한글 1쪽 vs +1쪽,
            // 10k 회귀 +29건 군집의 지배 형상). 마지막 표 배치 시점으로 이연.
            // [#2279 sec0] host 문단에 표 줄 외 추가 줄박스(트레일러 빈 줄)가
            // 이미 있으면 그 줄의 fmt 가 spacing 을 계상하므로 제외(36392557
            // sec0 표지: 표 892.5 + 트레일러 25.6 = 918.1 로 한글 1쪽).
            Some(fmt.spacing_before + fmt.spacing_after)
        } else {
            None
        } {
            // [#2279 sb+α 종결] 기계생성 문서의 TAC-모순(treat_as_char=true +
            // wrap=자리차지) host 표: 한글 fresh 는 host CS 크기의 "빈 줄박스"가
            // 아니라 host paraPr 의 **sb+sa 를 순수 가산**한다(α=0) — 재저장
            // ladder 실측: 36399374 pi4→5 = bare + (pi4.sa 500 + pi5.sb 300)
            // 정확, pi3(sb/sa=0)→4 = bare, 계열X 보도자료 156745609 host 4개
            // 전부 bare. 종전 font_size 근사(#2352 CS-근사)는 2557 pi27
            // (sb 1000)에서 우연히 ±2px 로 맞았던 것. 가산 후에는 생성기 압축
            // anchor 로의 후방 스냅이 성장분을 되돌리지 못하게 dirty 처리.
            st.advance_flow_by(host_spacing_px + pre_height + table_total_height);
            st.mark_vpos_ladder_dirty();
            // [#2279 sb+α 진단] host spacing 가산 내역. 동작 불변.
            if std::env::var("RHWP_DIAG_TAC").is_ok() {
                eprintln!(
                    "DIAG_HOSTBOX pi={} add={:.1} host_sb={:.1} host_sa={:.1} stored_gap_hu={}",
                    para_idx,
                    host_spacing_px,
                    fmt.spacing_before,
                    fmt.spacing_after,
                    para.line_segs.first().map(|s| s.line_spacing).unwrap_or(-1),
                );
            }
        } else {
            // [#2097 프로브 기록] 빈 host 자리차지 float(v_off>0)의 흐름 전진에
            // v_off + outer_bottom 을 더하는 기하 정합(82802 pi75: 저장 322.6 =
            // v_off 21.6 + outer 3.8 + 표 297.2, rhwp 299.1)은 격리 수정으로
            // 반증됨: 페어 상대측(후속 NO_LS 빈 문단 +12 재계산 축)과 결합되어
            // 순효과가 반전되고, v_off 를 저장이 소비하지 않는 하위 형상
            // (pi114: +20.5→+44.1 악화) 존재. 82802 56→57(hc=51) 악화 실측.
            // vpos-스냅/NO_LS 축과의 동시 정합 없이는 적용 불가.
            //
            // [#4090] 단독 Square 어울림 표는 한글이 옆으로 글을 흘린다. 저장 사다리의 host
            // 줄높이가 표 높이의 1/4 미만이면 한글은 표 높이를 흐름에 예약하지 않은 것이다.
            // 그때는 흐름을 host 줄만큼만 전진시키고 표 높이는 **세로 배제 밴드**로 잡는다 —
            // 밴드를 벗어나거나 쪽이 끝날 때 `close_square_band` 가 흐름을 밴드 바닥으로
            // 끌어올린다. 전진량만 줄이면(밴드 없이) 텍스트가 표를 지나쳐 계속 옆으로 흘러
            // 과소가 된다(실측: 156492236 24쪽 → 14쪽, 정답 17).
            let stored_host_line_px = para
                .line_segs
                .iter()
                .find(|seg| !is_synthetic_line_seg(seg))
                .map(|seg| crate::renderer::hwpunit_to_px(seg.line_height as i32, self.dpi));
            let hangul_flowed_beside_table = is_wrap_around_table
                && table_total_height > 1.0
                && stored_host_line_px.is_some_and(|lh| lh < table_total_height * 0.25);
            // [#4533 HWP3] 비-tac TopAndBottom float 인데 저장 사다리가 표를
            // 예약하지 않은 서식 문서(하동군 21918361: host lh 13.3px·다음 문단
            // 델타 21.3px vs 표 730px — 표·텍스트 겹침이 한글의 정본인데
            // typeset/layout 이 +709 과소비). host lh 와 다음 문단 저장 델타가
            // 둘 다 표 높이의 1/4 미만이면 흐름은 host 줄만 전진한다. HWP5 는
            // 같은 서명이 2중 반증된 환원불가 계열이라 HWP3 계보 한정.
            let next_gap_px = st
                .next_para_first_stored_vpos
                .zip(para.line_segs.first().map(|seg| seg.vertical_pos))
                .filter(|(nv, hv)| nv > hv)
                .map(|(nv, hv)| crate::renderer::hwpunit_to_px(nv - hv, self.dpi));
            // 게이트: 직파싱 HWP3 + rhwp 자신의 HWPX 산출물(마커 계보)만.
            // HWP5 컨테이너 변환본은 한글이 재저장하며 재조판한 것이라 저장
            // lineseg 가 HWP5 계약이다 — 환경정책기본법 1480000-201600147 실측:
            // hwp3_lineage 휴리스틱 HWP5 에 발화하면 52.7→369.8 악화.
            let hwp3_topbottom_no_reserve = (st.profile.hwp3_native_layout()
                || (st.profile.hwp3_layout() && st.profile.hwpx_container()))
                && !table.common.treat_as_char
                && matches!(
                    table.common.text_wrap,
                    crate::model::shape::TextWrap::TopAndBottom
                )
                && table_total_height > 1.0
                && stored_host_line_px.is_some_and(|lh| lh < table_total_height * 0.25)
                && next_gap_px.is_some_and(|g| g < table_total_height * 0.25);
            // [#5870] 빈 host 자리차지 float(vert=문단)의 흐름 전진에 v_off 와
            // 위·아래 바깥여백을 계상한다 — 단, 이 문단의 저장 사다리가 그 물리
            // 공식과 정확히 일치할 때만(`empty_host_physical_ladder_extras_hu`,
            // #2097 반증 회피 근거도 그쪽 주석에). 합성 lineseg(HWP3 계열)는
            // rhwp 가 물리식으로 만들어 자기참조가 되므로 실저장 줄만 증거로
            // 인정하고, 다중 표 host 는 델타가 표 합이라 단일 표 등식에 걸리지
            // 않는다(표 1개 조건으로 명시). layout 의 lane flow-bottom 가산과
            // 대칭이어야 조판·렌더가 어긋나지 않는다.
            let empty_host_physical_extras_hu = ((st.profile.hwp5_stored_pagination_layout()
                || st.profile.hwpx_stored_layout())
                && st.next_para_is_empty_float_table_anchor
                && is_para_topbottom_float(&table.common)
                && !para_has_non_whitespace_text(para)
                && para
                    .controls
                    .iter()
                    .filter(|control| matches!(control, Control::Table(_)))
                    .count()
                    == 1)
                .then(|| {
                    st.next_para_first_stored_vpos
                        .zip(
                            para.line_segs
                                .iter()
                                .find(|seg| !is_synthetic_line_seg(seg))
                                .map(|seg| seg.vertical_pos),
                        )
                        .and_then(|(next_vpos, host_vpos)| {
                            crate::renderer::float_placement::empty_host_physical_ladder_extras_hu(
                                table, host_vpos, next_vpos,
                            )
                        })
                })
                .flatten();
            // 쪽 기준 자리차지 표 띠에 걸린 빈 host 줄은 띠 아래의 독립 줄이다([#8554] 배치와
            // 같은 판정). 흐름이 아직 띠 아래끝에 이르지 않았을 때만 띠 끝으로 옮긴다.
            let page_band_host_line = (!table.common.treat_as_char
                && is_first_placed
                && is_last_placed
                && pre_height <= 0.0)
                .then(|| {
                    st.page_band_host_line
                        .filter(|(para, ctrl, ..)| *para == para_idx && *ctrl == ctrl_idx)
                        .map(|(_, _, band_bottom, advance)| (band_bottom, advance))
                })
                .flatten()
                .filter(|(band_bottom, _)| st.current_height + 0.5 < *band_bottom);
            if hwp3_topbottom_no_reserve {
                st.advance_flow_by(pre_height + stored_host_line_px.unwrap_or(0.0));
            } else if hangul_flowed_beside_table {
                let band_top = st.current_height + pre_height;
                st.align_flow_to(band_top + stored_host_line_px.unwrap_or(0.0));
                let frame = st.paragraph_float_placements.get(&(para_idx, ctrl_idx));
                st.register_square_band(
                    // Absorbed source offsets are relative to the host's
                    // line origin, not the displaced object's physical top.
                    band_top,
                    frame.map_or(band_top + table_total_height, |frame| frame.occupied_bottom),
                );
            } else if let Some((band_bottom, host_advance_hu)) = page_band_host_line {
                // 배치는 host 에 이르면 띠 아래끝으로 점프하고(`calculate_shape_reserved_heights`)
                // 그 아래에 host 줄을 둔다. 조판도 같은 끝점까지 흐름을 옮긴다.
                st.align_flow_to(band_bottom);
                st.advance_flow_by(hwpunit_to_px(host_advance_hu, self.dpi));
            } else if let Some(extras_hu) = empty_host_physical_extras_hu {
                st.advance_flow_by(
                    pre_height + table_total_height + hwpunit_to_px(extras_hu as i32, self.dpi),
                );
            } else {
                st.advance_flow_by(pre_height + table_total_height);
            }
        }
        // [#2243 진단] TAC 표 라인 회계 분해 — 동작 불변.
        if std::env::var("RHWP_DIAG_TAC").is_ok() {
            eprintln!(
                "DIAG_TAC pi={} tac={} pre_h={:.1} table_total={:.1} fmt_total={:.1} fmt_fit={:.1} stored_ls={} cur_h_after={:.1} page={} computed_end={:?} line_heights={:?} line_spacings={:?} stored_row={:?} spacing_before={} spacing_after={} reflowed={}",
                para_idx,
                table.common.treat_as_char,
                pre_height,
                table_total_height,
                fmt.total_height,
                fmt.height_for_fit,
                !para.line_segs.is_empty(),
                st.current_height,
                st.pages.len(),
                computed_table_row_end,
                fmt.line_heights,
                fmt.line_spacings,
                stored_single_row_source,
                fmt.spacing_before,
                fmt.spacing_after,
                self.render_normalization.table_text_reflowed(table),
            );
        }

        // [#2813] 이연된 host 앵커 줄 아이템 — 마지막 float 뒤에 한글 문서순으로
        // 삽입한다. 렌더는 이 순서대로 표를 흐름 상단부터, 줄을 저장 vpos 로 놓는다.
        if defer_host_line && is_last_placed {
            st.append_item(PageItem::PartialParagraph {
                para_index: para_idx,
                start_line: 0,
                end_line: pre_table_end_line.max(1),
            });
            st.finish_deferred_host_line();
        }

        // post-table 텍스트
        let is_last_table = is_last_placed;
        let tac_table_count = para
            .controls
            .iter()
            .filter(|c| matches!(c, Control::Table(t) if self.is_effective_tac_table(para, t, fmt)))
            .count();
        let stored_owned_table_line = (!st.profile.session_edited()
            && fmt.line_heights.len() == para.line_segs.len())
        .then(|| crate::renderer::composer::stored_owned_tac_line(para, ctrl_idx))
        .flatten();
        let post_table_start = if let Some((owner, _)) = stored_owned_table_line {
            // 앞 공백 줄의 line_height가 개체 최대 높이를 반복해도 소유 줄은
            // 제어 슬롯이 결정한다. 이미 소비한 표 줄을 꼬리에 다시 넣지 않는다.
            (owner + 1).min(total_lines)
        } else if tac_wrap_split {
            (pre_table_end_line + 1).min(total_lines).max(1)
        } else if self.uses_tac_table_flow(table) {
            pre_table_end_line.max(1)
        } else if table.common.treat_as_char && total_lines > pre_table_end_line + 1 {
            // HWPX TAC 표(attr 비트0=0): 표줄(pre_table_end_line) 다음에 실제 본문 줄이
            // 있으면 표줄을 post-text 에서 제외(HWP5 attr&0x01 의 pre_end.max(1) 와 정합).
            // 단일 줄(표줄만)은 건드리지 않아 기존 동작 보존.
            pre_table_end_line + 1
        } else if is_last_table && !is_first_table {
            0
        } else {
            pre_table_end_line
        };
        // 중복 방지: 이전 표가 이미 같은 문단의 pre-text(start_line=0)를 추가했으면 건너뜀
        // (engine.rs:1418-1421 와 동일한 가드 — 다중 TopAndBottom 표 문단에서
        //  같은 line 범위가 두 번 emit되어 본문이 두 번 렌더되는 문제 차단)
        // [#6184] 이 가드는 `current_items` 만 보는데, 표가 쪽을 넘긴 뒤에는 그것이
        // **새 쪽**의 항목이라 앞 쪽에 pre-emit 해 둔 host 줄을 못 본다. 그러면 같은
        // 줄이 두 쪽에 모두 그려진다(156489124 pi=324: 12쪽 1030.3 과 13쪽 75.6).
        // pre-emit 기록은 쪽을 넘어 남으므로 함께 본다.
        let pre_text_exists = post_table_start == 0
            && (st.pre_emitted_host_paras.contains(&para_idx)
                || st.current_items.iter().any(|item| {
                    matches!(item, PageItem::PartialParagraph { para_index, start_line, .. }
                    if *para_index == para_idx && *start_line == 0)
                }));
        let has_substantive_text = para_has_non_whitespace_text(para);
        let whitespace_only_single_tac_host_line = !has_substantive_text
            && !para.text.is_empty()
            && table.common.treat_as_char
            && pre_table_end_line == 0
            && total_lines <= 1;
        // [#7330] 같은 문단의 **앞선 표가 이미 놓은** host 줄을 마지막 표가 한 번 더
        // "표 뒤 본문" 으로 내보내는 갈래를 막는다 — 같은 줄의 **이중 방출**이다.
        //
        // 한 문단에 표가 둘이고 마지막 표가 비-TAC 이면 위 `post_table_start` 가
        // `is_last_table && !is_first_table` 갈래로 **0** 이 된다. 그러면 앞선 TAC 표가
        // `pre_table_end_line`(=1)까지로 이미 배치한 줄이 `post_table_start..total_lines`
        // = `0..1` 로 통째로 다시 실려 나간다. 그 두 번째 사본은 저장 vpos 가 아니라
        // 흐름 꼬리를 받으므로 자리차지 표 **아래**에 그려지고 뒤 문단을 그만큼 민다.
        //
        // 실측 `36374873_결재문서본문_야간방호일지` pi=3 (공백 42칸, 줄 1개):
        //   host 줄  978.2 (13×8 표가 끝나는 976.9 뒤)  → 수정 후 251.5 (그 표 앞)
        //   pi=5..7  1125.5 / 1146.8 / 1168.1  → 용지(1122.5) 밖
        //   수정 후  pi=5..7  1030.6 / 1052.0 / 1073.3 (줄 하나 93.5px 이 흐름에서 빠져 -94.9px)
        //
        // `is_first_table` 로 좁히는 것이 핵심이다. 첫 표가 곧 마지막 표인 host
        // (`#6925` 의 `148751598-briefing.hwp` pi=0: `first=last=true`, `pre_end=0`)는
        // 그 줄을 **처음** 놓는 것이므로 막으면 저장 슬롯이 접혀 뒤가 24px 당겨진다.
        let whitespace_only_host_line_already_placed = !has_substantive_text
            && !para.text.is_empty()
            && total_lines <= 1
            && !is_first_table
            && pre_table_end_line > 0
            && post_table_start == 0;
        let has_post_text = !para.text.is_empty()
            && total_lines > post_table_start
            && !whitespace_only_single_tac_host_line
            && !whitespace_only_host_line_already_placed;
        let should_add_post_text = is_last_table
            && tac_table_count <= 1
            && has_post_text
            && !pre_text_exists
            && !no_lineseg_band_host;
        if should_add_post_text {
            let (post_content_height, post_height) =
                fmt.host_text_bounds(para, post_table_start..total_lines, self.dpi);
            let stored_host_origin = st
                .paragraph_float_placements
                .get(&(para_idx, ctrl_idx))
                .and_then(|placement| placement.stored_host_origin)
                .filter(|_| post_table_start == 0);
            if let Some(origin) = stored_host_origin {
                // The host was resolved before fit, even though its text item is
                // emitted after the floating table. Consume that same origin.
                st.align_flow_to(origin);
            } else if let Some(step) =
                self.stored_tac_line_step_to_post_text(para, table, fmt, post_table_start)
            {
                // [#8095] 표 줄 0 의 적합 높이는 줄 높이만 센다(뒤 글줄이 저장 되감김으로
                // 다음 쪽에 갈 수 있다). 뒤 글줄이 같은 저장 프레임에서 `표 줄 높이 +
                // 줄간격` 뒤에 이어지면 그 줄간격도 흐름이 지나간다 — 빼면 뒤 문단 조판
                // 원점이 저장 사다리보다 그만큼 위로 간다(156465345 1쪽 pi=0, 12.8px).
                let extra = step - table_total_height;
                if extra > 0.5 {
                    st.advance_flow_by(extra);
                } else if extra < -0.5 {
                    // 음수 줄간격: 뒤 글줄은 표 줄 끝보다 그만큼 위에서 시작한다.
                    st.reclaim_flow_by(-extra);
                }
            }
            // [#2808] 소비 조건을 layout 의 same_owner_table_precedes 와 동일하게
            // 다중 co-anchored float host 로 한정 — 단일 표 host post-text 는 기존
            // 앵커 유지(#1549) 경로로 남긴다.
            // 오프셋 안에 글줄이 들어가지 않는 host 는 표 아래에서 글을 잇는다 —
            // 출력(layout)의 같은 판정과 함께 표 점유 끝으로 흐름을 옮긴다.
            if is_visible_para_float
                && crate::renderer::float_placement::visible_host_text_flows_below_offset_float(
                    para,
                    table,
                    st.next_para_first_stored_vpos,
                )
            {
                if let Some(bottom) = st
                    .visible_float_exclusions
                    .iter()
                    .filter(|zone| zone.para_index == para_idx)
                    .map(|zone| zone.bottom)
                    .reduce(f64::max)
                {
                    if bottom > st.current_height {
                        st.align_flow_to(bottom);
                    }
                }
            }
            if is_visible_para_float && has_preceding_coanchored_float {
                // [#2439] 다중 visible-host float 의 host 텍스트가 마지막 표 뒤에서
                // emit 되는 경우, 같은 문단 소유 exclusion 도 post-text 에는 적용한다.
                // 첫 표 offset=0 뒤의 양수-offset 표가 아래로 밀렸을 때 이 동기화가
                // 없으면 서명란이 두 번째 표의 상단에 겹치고 flow도 한 표 높이만큼
                // 과소 소비된다. 선행 제목은 pre-table 경로라 영향 없다.
                // [#7680] 줄 상자가 띠에 **걸리기만 해도** 그 줄은 띠 아래로 간다 — 첫 줄 높이로
                // 짚는다(전체 post 높이로 짚으면 멀리 있는 띠까지 넘긴다). hwpspec pi=133 의
                // 「참고문헌」은 첫 띠 끝 603.9 에서 시작해 둘째 띠 607.7~ 에 걸쳤는데 HWP5 는
                // 겹침 프로브가 꺼져 있어 띠 위에 그대로 놓였다(정본 849.5 vs 672.6).
                let first_post_line_height = fmt
                    .line_heights
                    .get(post_table_start)
                    .copied()
                    .unwrap_or(post_height);
                st.apply_visible_float_exclusions(first_post_line_height, None);
                if issue2439_visible_host_stack && is_last_table {
                    // 마지막 표의 exclusion은 표 본체까지만 담는다. 한컴 저장 흐름은
                    // 그 뒤의 outer-bottom과 host LineSeg 간격을 거친 뒤 서명문을
                    // 배치하므로, 해당 두 성분을 post-text 앞에서 한 번만 복원한다.
                    st.advance_flow_by(
                        hwpunit_to_px(table.outer_margin_bottom as i32, self.dpi)
                            + para_line_spacing_px(para, self.dpi),
                    );
                }
            }
            // [편집 세션] 자리차지(topbottom) 표가 Enter로 자라 post-text가 본문
            // 하한을 넘으면 문구를 새 쪽으로 보낸다. 저장 형상 열람은 저장 vpos를
            // 신뢰하므로 제외한다(셀 끝 Enter 재현: 하단 문구·로고가 페이지
            // 밖으로 잘리던 구간).
            let session_grown_topbottom_spill = (self.profile.get().session_edited()
                || split_host_prefix.is_some())
                && !table.common.treat_as_char
                && is_para_topbottom_float(&table.common);
            // 쪽 끝의 마지막 줄은 글줄의 점유 끝으로 수용한다. 줄 뒤 간격은
            // 다음 흐름에는 보존하지만, 그 간격만 용지 밖에 남는다는 이유로
            // 본문에 들어가는 줄을 다음 쪽으로 옮기지 않는다.
            // 표 뒤 첫 글줄이 저장 쪽 리셋이면 한/글은 그 줄부터 다음 쪽에 둔다. 표 줄이
            // 문단 몇 번째 줄이든 같다(표 줄 자체의 리셋은 `needs_stored_line_advance`).
            let post_text_restarts_page = !self.profile.get().session_edited()
                && self
                    .tac_table_line_index(para, table, fmt)
                    .filter(|&table_line| post_table_start > table_line)
                    .and_then(|table_line| para.line_segs.get(table_line))
                    .zip(para.line_segs.get(post_table_start))
                    .is_some_and(|(prev, next)| stored_line_restarts_page(prev, next));
            if ((self.tac_table_line_index(para, table, fmt) == Some(0)
                || session_grown_topbottom_spill)
                && st.current_height + post_content_height > st.available_height() + 0.5
                || post_text_restarts_page)
                && !st.current_items.is_empty()
            {
                st.advance_column_or_new_page();
            }
            // [#7330] 같은 문단의 자리차지 표가 첫 글줄을 민 경우 앞 간격은 문단 상단에서
            // 잰 거리다: 글줄 원점 = max(문단 상단 + 앞 간격, 표 점유 끝). 표 점유 끝 위에
            // 남는 앞 간격만 흐름에 소비하고 같은 값을 배치에 넘긴다(배치는 이 값을
            // 확정 앞 간격으로 받아 다시 더하거나 단 맨 위 규칙으로 바꾸지 않는다).
            // 저장 원점을 소비한 host 는 그 원점이 이미 앞 간격을 포함한다.
            // [#8836] 쪽·용지 기준 자리차지 표가 같은 문단의 첫 글줄을 민 경우도 같다 — 띠의
            // 기준이 문단이 아닐 뿐, 밀린 줄 원점과 앞 간격의 관계는 같은 규칙이다.
            if post_table_start == 0
                && (is_visible_para_float
                    || crate::renderer::float_placement::is_absolute_topbottom_float_text_host(
                        para, table,
                    ))
                && stored_host_origin.is_none()
                && st.current_height > para_start_height + 0.5
            {
                let spacing = crate::renderer::float_placement::float_pushed_line_spacing_before(
                    para_start_height,
                    fmt.spacing_before,
                    st.current_height,
                );
                st.consume_float_pushed_line_spacing(para_idx, spacing);
            }
            // [#7678] 자리차지 표 뒤 host 글이 쪽 끝에 걸리면 한/글은 들어가는 줄까지 이 쪽에
            // 두고 나머지 줄을 다음 쪽 맨 위로 넘긴다(넘긴 줄은 문단 안의 줄이라 앞 간격이
            // 없다). 종전엔 표 뒤 글 전체를 한 항목으로 붙여 넘친 줄이 본문 하단 아래에
            // 그려졌다. 줄 fit 은 그 줄의 말미 줄간격을 빼고 잰다(#6184 — 쪽 마지막 줄 뒤의
            // 간격은 쪽을 채우지 않는다). 첫 줄부터 안 들어가는 경우는 종전 경로에 둔다.
            let post_split_line = (is_visible_para_float
                && !table.common.treat_as_char
                && !session_grown_topbottom_spill
                && st.current_height + post_height > st.available_height() + 0.5)
                .then(|| {
                    let mut fitted = post_table_start;
                    for line in post_table_start..total_lines {
                        let content = fmt
                            .host_text_bounds(para, post_table_start..line + 1, self.dpi)
                            .0;
                        if st.current_height + content > st.available_height() + 0.5 {
                            break;
                        }
                        fitted = line + 1;
                    }
                    fitted
                })
                .filter(|&line| line > post_table_start && line < total_lines);
            if let Some(split_line) = post_split_line {
                st.record_host_text_fragment(
                    para_idx,
                    post_table_start..split_line,
                    para,
                    fmt,
                    self.dpi,
                );
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: post_table_start,
                    end_line: split_line,
                });
                st.advance_flow_by(
                    fmt.host_text_bounds(para, post_table_start..split_line, self.dpi)
                        .1,
                );
                st.advance_column_or_new_page();
                st.record_host_text_fragment(
                    para_idx,
                    split_line..total_lines,
                    para,
                    fmt,
                    self.dpi,
                );
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: split_line,
                    end_line: total_lines,
                });
                st.advance_flow_by(
                    fmt.host_text_bounds(para, split_line..total_lines, self.dpi)
                        .1,
                );
            } else {
                st.record_host_text_fragment(
                    para_idx,
                    post_table_start..total_lines,
                    para,
                    fmt,
                    self.dpi,
                );
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: post_table_start,
                    end_line: total_lines,
                });
                st.advance_flow_by(post_height);
            }
            if computed_table_row_end.is_some() {
                // 개체 줄과 실제로 방출한 본문 줄의 합은 후행 표의 흐름 하한이다.
                // 같은 단에서만 갱신하며, 본문이 이월되면 이전 단 끝을 유출하지 않는다.
                st.record_inline_flow_bottom(st.current_height);
            }
        } else if is_visible_para_float && is_last_table {
            // [#6312] host 글줄을 post-text 로 방출하지 못한 자리차지 표.
            // 저장 사다리가 lh+ls 만 증언하면 그 줄 상자를 표 밴드 아래에 계상한다.
            let next_vpos = if st.next_para_is_plain_text {
                st.next_para_first_stored_vpos
            } else {
                None
            };
            if let Some(line_advance) = stored_visible_anchor_band_host_line_advance_from_vpos(
                st.profile.hwp5_stored_pagination_layout() || st.profile.hwpx_stored_layout(),
                para,
                ctrl_idx,
                next_vpos,
            ) {
                st.advance_flow_by(hwpunit_to_px(line_advance, self.dpi));
            } else if is_textless_coanchored_host
                && para.text.is_empty()
                && is_last_para_topbottom_float(para, ctrl_idx)
                && total_lines > 0
                && !para.controls.iter().any(|control| {
                    matches!(control, Control::Table(candidate)
                        if crate::renderer::empty_host_line_absorbed_by_topbottom_float(
                            para, &candidate.common))
                })
            {
                // [#7687] 빈 host 의 줄 상자는 첫 띠 아래에 놓이고(hwpspec pi=130 저장 host 줄
                // 10810 = 첫 띠 끝, 합성 H1~H6 도 같음), 그 줄이 양수 오프셋 띠에 걸리면 그 줄만
                // 띠 아래로 간다. 폭 0 으로 저장된 흡수 줄(#7470)은 종전대로 띠에 든다.
                // 글 있는 host 의 post-text 와 같은 계약으로 낸다 — 줄 항목(`PartialParagraph`
                // 0..1, 저장 줄 host 는 위 [#2813] 이연 항목이 이미 냈다)·띠 위에 남는 앞 간격만
                // 소비·흐름 전진. 배치는 그 항목을 같은 띠 프로브로 놓는다.
                st.apply_visible_float_exclusions(fmt.line_heights[0], None);
                if st.current_height > para_start_height + 0.5 {
                    let spacing =
                        crate::renderer::float_placement::float_pushed_line_spacing_before(
                            para_start_height,
                            fmt.spacing_before,
                            st.current_height,
                        );
                    st.consume_float_pushed_line_spacing(para_idx, spacing);
                }
                let host_line_already_emitted = st.current_items.iter().any(|item| {
                    matches!(item, PageItem::PartialParagraph { para_index, start_line: 0, .. }
                        if *para_index == para_idx)
                });
                if !host_line_already_emitted {
                    st.append_item(PageItem::PartialParagraph {
                        para_index: para_idx,
                        start_line: 0,
                        end_line: 1,
                    });
                }
                st.advance_flow_by(fmt.line_advance(0));
            }
        }

        // TAC 표: trailing line_spacing 복원 (Paginator place_table_fits:777-783 동일)
        // has_post_text는 tac_table_count와 무관하게 텍스트 줄 존재 여부만 확인
        let is_tac = self.is_effective_tac_table(para, table, fmt);
        // Multi-line TAC flow already includes this line's outgoing spacing
        // in every nonterminal table_height. Restoring the paragraph's tail
        // after each table reserves the same spacing a second time and shifts
        // the intervening floating object away from its accepted line frame.
        let has_following_tac_table = para.controls.iter().skip(ctrl_idx + 1).any(|control| {
            matches!(control, Control::Table(next) if self.is_effective_tac_table(para, next, fmt))
        });
        // 표 줄 뒤에 컨트롤만 남은 저장 줄(쪽 번호 감추기 등)은 post-text 로 나가지 않지만
        // 한/글은 그 줄 상자를 쌓는다. 표 줄 간격과 그 줄들을 여기서 더하고, 마지막 줄
        // 간격은 아래 terminal 복원이 더한다. 표 줄 간격 뒤 그 줄이 쪽에 들어가지 않으면
        // 한/글은 다음 쪽 맨 위에 줄을 놓는다(저장 vpos 재시작) — 그 줄을 다음 쪽 항목으로 낸다.
        let control_only_tail = (is_tac
            && !has_post_text
            && !has_following_tac_table
            && tac_table_count == 1
            && total_lines == para.line_segs.len()
            && self.tac_table_line_index(para, table, fmt) == Some(0))
        .then(|| crate::renderer::tac_host_control_only_tail(para, 0))
        .flatten();
        if let Some(tail) = control_only_tail {
            st.advance_flow_by(hwpunit_to_px(para.line_segs[0].line_spacing, self.dpi));
            let first_tail_height = hwpunit_to_px(tail.lines[0].line_height, self.dpi);
            if st.current_height + first_tail_height > st.available_height() + 0.5
                && !st.current_items.is_empty()
            {
                st.advance_column_or_new_page();
                st.record_host_text_fragment(para_idx, 1..total_lines, para, fmt, self.dpi);
                st.append_item(PageItem::PartialParagraph {
                    para_index: para_idx,
                    start_line: 1,
                    end_line: total_lines,
                });
            }
            let tail_hu: i32 = tail
                .lines
                .iter()
                .map(|line| line.line_height + line.line_spacing)
                .sum::<i32>()
                - tail.lines.last().map_or(0, |line| line.line_spacing);
            st.advance_flow_by(hwpunit_to_px(tail_hu, self.dpi));
        }
        let stored_tail = (is_last_placed
            && table.common.treat_as_char
            && table.caption.is_none()
            && !controls::stored_tac::table_has_notes(table)
            && !para.stored_text_partition_is_dirty()
            && !para.cell_format_vpos_dirty
            && para
                .source_line_seg_vertical_pos
                .as_ref()
                .is_none_or(|source| {
                    source.len() == para.line_segs.len()
                        && source
                            .iter()
                            .zip(&para.line_segs)
                            .all(|(&position, line)| position == line.vertical_pos)
                })
            && fmt.computed_host_lines.is_none()
            && fmt.line_count() == para.line_segs.len()
            && para
                .line_segs
                .iter()
                .all(|line| !is_synthetic_line_seg(line))
            && (para.empty_control_stream_position(0).is_some()
                || controls::order::complete_whitespace_table_stream(para)))
        .then(|| crate::renderer::composer::control_slot_line_index(para, ctrl_idx))
        .flatten()
        .filter(|&owner| owner + 1 == para.line_segs.len())
        .and_then(|owner| {
            let line = &para.line_segs[owner];
            let occupied = i64::from(table.common.height)
                + i64::from(table.outer_margin_top)
                + i64::from(table.outer_margin_bottom);
            (line.line_spacing >= 0
                && i64::from(line.line_height) == occupied
                && (fmt.line_heights[owner] - hwpunit_to_px(line.line_height, self.dpi)).abs()
                    <= self.dpi / 7200.0
                && (table_total_height - fmt.line_heights[owner]).abs() <= self.dpi / 7200.0)
                .then_some((owner, line))
        });
        // 제어 사이 공백은 마지막 표 뒤의 본문 줄이 아니며 그 줄의 닫는 간격을 소유하지 않는다.
        let whitespace_ends_before_table = stored_tail.is_some()
            && !should_add_post_text
            && para.control_text_positions().get(ctrl_idx).copied()
                == Some(para.text.chars().count());
        let composed_tail_owns_spacing = crate::renderer::composer::composed_object_tail(para)
            .is_some_and(|tail| tail.end == fmt.line_count());
        let restore_terminal_tac_spacing = is_tac
            && (!has_post_text || whitespace_ends_before_table)
            && !has_following_tac_table
            && !composed_tail_owns_spacing;
        if restore_terminal_tac_spacing {
            let occupied_end = st.current_height;
            st.advance_flow_by(fmt.total_height - fmt.height_for_fit);
            // 같은 줄의 확정 끝에도 복원한 간격을 반영해 뒤 상한이 되감지 않게 한다.
            // [#8418] 저장 pen이 소유한 끝은 1HU 이내의 환산 잡음까지 같은 끝으로 본다.
            if let Some(mut placement) = st
                .inline_placements
                .get(&(para_idx, ctrl_idx))
                .copied()
                .filter(|placement| {
                    placement.advance_end == Some(occupied_end)
                        || (placement.stored_horizontal_pen.is_some()
                            && placement
                                .advance_end
                                .is_some_and(|end| (end - occupied_end).abs() <= self.dpi / 7200.0))
                })
            {
                placement.advance_end = Some(st.current_height);
                st.record_inline_placement((para_idx, ctrl_idx), placement);
            }
        }
        if restore_terminal_tac_spacing {
            if let Some((owner, line)) = stored_tail {
                let origin = st.current_height - fmt.line_advance(owner) - fmt.spacing_after;
                let existing = st.inline_placements.get(&(para_idx, ctrl_idx)).copied();
                let first_zero = line.vertical_pos == 0
                    && origin == 0.0
                    && st.vpos_col_anchor == 0.0
                    && matches!(st.current_items.first(), Some(PageItem::Table { para_index, control_index })
                        if *para_index == para_idx && *control_index == ctrl_idx);
                let base = st
                    .vpos_page_base
                    .filter(|_| st.vpos_page_base_stored)
                    .or_else(|| first_zero.then_some(0));
                if let Some(base) = base.filter(|&base| {
                    let pen = st.vpos_col_anchor
                        + hwpunit_to_px(line.vertical_pos.saturating_sub(base), self.dpi);
                    (pen - origin).abs() <= self.dpi / 7200.0
                        && existing.is_none_or(|placement| {
                            placement.stored_column_frame.is_none()
                                && placement
                                    .advance_end
                                    .is_none_or(|end| end == st.current_height)
                                && (placement.y - origin).abs() <= self.dpi / 7200.0
                        })
                }) {
                    // 수용한 같은 원점과 끝을 함께 발행해 후속 문단의 lazy 역산을 막는다.
                    let mut placement =
                        existing.unwrap_or(super::float_placement::InlineBoxPlacement {
                            x: 0.0,
                            y: origin,
                            clearance: 0.0,
                            resolved_x: false,
                            advance_end: None,
                            stored_horizontal_pen: None,
                            stored_column_frame: None,
                        });
                    placement.advance_end = Some(st.current_height);
                    placement.stored_column_frame =
                        Some(super::float_placement::StoredColumnFrame {
                            source_origin_hu: base,
                            column_anchor_y: st.vpos_col_anchor,
                        });
                    st.record_inline_placement((para_idx, ctrl_idx), placement);
                }
            }
        }
        let accepted_single_row_origin = stored_single_row_source.and_then(
            |(source_vpos, source_base, column_started_at_zero)| {
                if st.inline_placements.contains_key(&(para_idx, ctrl_idx)) {
                    return None;
                }
                let origin = st.current_height - fmt.line_advance(0) - fmt.spacing_after;
                let establishes_origin = source_base.is_none()
                    && st.vpos_page_base.or(st.vpos_lazy_base).is_none()
                    && column_started_at_zero
                    && source_vpos >= 0
                    && fmt.spacing_before.is_finite()
                    && fmt.spacing_before >= 0.0
                    && (origin - fmt.spacing_before).abs() <= hwpunit_to_px(2, self.dpi)
                    && (hwpunit_to_px(source_vpos, self.dpi) - origin).abs()
                        <= hwpunit_to_px(2, self.dpi);
                let base = source_base.or_else(|| establishes_origin.then_some(0))?;
                let source_pen = source_vpos.checked_sub(base)?;
                if source_pen < 0
                    || (hwpunit_to_px(source_pen, self.dpi) - origin).abs()
                        > hwpunit_to_px(2, self.dpi)
                {
                    return None;
                }
                if establishes_origin {
                    // 첫 줄의 위 간격은 줄 pen에 포함되지만 단의 원점은 0이다.
                    // 실제 수용 끝에서 확인한 같은 원점을 첫 paint에도 전달한다.
                    st.record_paragraph_origin(super::pagination::ParagraphOrigin {
                        paragraph_index: para_idx,
                        spacing_before: fmt.spacing_before,
                        source_vpos_base: base,
                        flow_start: 0.0,
                        flow_end: st.current_height,
                    });
                }
                Some(origin)
            },
        );
        let stored_table_row_origin = stored_table_row_origin
            .or(accepted_single_row_origin)
            .or_else(|| {
                composed_table_row_origin
                    .filter(|_| !st.inline_placements.contains_key(&(para_idx, ctrl_idx)))
            });
        if let Some(origin) = stored_table_row_origin {
            // 줄 뒤 간격까지 실제로 수용한 같은 흐름 끝을 전달한다. 본체 높이로
            // 끝을 다시 추정하면 뒤 문단이 저장 줄 간격만큼 위로 이동한다.
            st.record_inline_placement(
                (para_idx, ctrl_idx),
                super::float_placement::InlineBoxPlacement {
                    x: 0.0,
                    y: origin,
                    clearance: 0.0,
                    resolved_x: false,
                    advance_end: Some(st.current_height),
                    stored_horizontal_pen: None,
                    stored_column_frame: None,
                },
            );
        }
        // [#2243 진단] 배치 종료 시 누적 — 동작 불변.
        if std::env::var("RHWP_DIAG_TAC").is_ok() {
            eprintln!(
                "DIAG_TAC_END pi={} cur_h={:.1} trailing_fired={} has_post_text={} delta={:.1} accepted_origin={:?} page_base={:?} lazy_base={:?} row_advance={} inline={:?}",
                para_idx,
                st.current_height,
                restore_terminal_tac_spacing,
                has_post_text,
                fmt.total_height - fmt.height_for_fit,
                accepted_single_row_origin,
                st.vpos_page_base,
                st.vpos_lazy_base,
                fmt.line_advance(0),
                st.inline_placements.get(&(para_idx, ctrl_idx)),
            );
        }
        if strict_following_plain_text_fit && is_last_placed {
            st.require_strict_following_text_fit();
        }
    }

    /// 표 줄 다음 글줄이 같은 저장 프레임에서 끊김 없이 이어질 때의 저장 걸음(px).
    /// 앞 공백 줄이 따로 있으면 같은 구성에서 소비한 앞 전진도 포함한다.
    /// 되감김·합성 줄·편집 세션은 `None` 이다.
    fn stored_tac_line_step_to_post_text(
        &self,
        para: &Paragraph,
        table: &crate::model::table::Table,
        fmt: &FormattedParagraph,
        post_table_start: usize,
    ) -> Option<f64> {
        let owner = self.tac_table_line_index(para, table, fmt)?;
        if post_table_start != owner + 1 || self.profile.get().session_edited() {
            return None;
        }
        let (table_line, post_line) = para
            .line_segs
            .get(owner)
            .zip(para.line_segs.get(post_table_start))?;
        let prefix = if owner == 0 {
            0.0
        } else {
            let control = para.controls.iter().position(|control| {
                matches!(control, Control::Table(candidate) if std::ptr::eq(candidate.as_ref(), table))
            })?;
            let (stored_owner, _) =
                crate::renderer::composer::stored_owned_tac_line(para, control)?;
            let advance = fmt.line_advances_sum(0..owner);
            let stored_advance = hwpunit_to_px(
                table_line
                    .vertical_pos
                    .checked_sub(para.line_segs.first()?.vertical_pos)?,
                self.dpi,
            );
            if stored_owner != owner
                || (advance - stored_advance).abs() > hwpunit_to_px(1, self.dpi)
            {
                return None;
            }
            advance
        };
        // 줄간격은 음수일 수도 있다. 뒤 글줄이 그 간격만큼 표 줄 끝보다 위에서 시작한다는
        // 저장 증언도 같은 프레임의 흐름이다.
        if is_synthetic_line_seg(table_line)
            || is_synthetic_line_seg(post_line)
            || table_line.line_spacing == 0
        {
            return None;
        }
        let step = table_line
            .vertical_pos
            .checked_add(table_line.line_height)?
            .checked_add(table_line.line_spacing)?;
        (post_line.vertical_pos == step).then(|| {
            prefix + hwpunit_to_px(table_line.line_height + table_line.line_spacing, self.dpi)
        })
    }

    fn tac_flow_query(&self) -> controls::tac_flow::TacFlowQuery<'_> {
        controls::tac_flow::TacFlowQuery::new(self.dpi, &self.profile)
    }

    fn tac_table_line_index(
        &self,
        para: &Paragraph,
        table: &crate::model::table::Table,
        fmt: &FormattedParagraph,
    ) -> Option<usize> {
        self.tac_flow_query().tac_table_line_index(para, table, fmt)
    }

    fn is_effective_tac_table(
        &self,
        para: &Paragraph,
        table: &crate::model::table::Table,
        fmt: &FormattedParagraph,
    ) -> bool {
        self.tac_flow_query()
            .is_effective_tac_table(para, table, fmt)
    }

    fn uses_tac_table_flow(&self, table: &crate::model::table::Table) -> bool {
        self.tac_flow_query().uses_tac_table_flow(table)
    }

    /// 비-TAC 블록 표의 조판: fits → place / split(Break Token 기반).
    /// 기존 Paginator의 split_table_rows와 동일한 세밀한 분할 로직.
    #[allow(clippy::too_many_arguments)]
    fn pre_emit_visible_rowbreak_host_text(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        composed_all: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
    ) -> bool {
        if !para_has_visible_text(para) {
            return false;
        }
        self.pre_emit_deferred_host_lines(st, para_idx, para, composed_all, styles)
    }

    /// [#7677] 쪽을 넘긴 자리차지(PARA·TopAndBottom) RowBreak 표의 **마지막 조각 뒤** host 글줄을
    /// 흐름에 예약한다.
    ///
    /// 한/글은 그 host 첫 글줄을 마지막 조각 하단 + 표 바깥 아래 여백에 둔다 — 앞 간격은 문단
    /// 상단(첫 조각이 있던 쪽)에서 이미 소비됐다. 종전엔 typeset 이 이 줄을 예약하지 않아
    /// layout 만 조각 끝에서 문단을 새로 시작하듯 앞 간격을 다시 더해 그렸고(합성 S 6쪽: 정본
    /// 조각 하단 +11.3 ↔ rhwp +18.5), 뒤 문단의 쪽 소속 판정도 그 줄 높이만큼 비어 있었다.
    ///
    /// 호출 시점은 끝 조각을 커밋한 직후라 흐름이 이미 조각 하단 + 바깥 아래 여백에 서 있다.
    /// 여기서 `PartialParagraph`(글 줄 범위)를 내고 줄 전진만 더한다. 배치는 조각 하단에서
    /// 다시 시작하므로, 흐름이 조각 하단보다 더 내려간 몫(`host_push`, 바깥 아래 여백)을
    /// 확정 앞 간격으로 기록해(`float_pushed_line_spacings`, #7330 계약) 배치가 문단 앞 간격
    /// 대신 그 값만큼 내려 같은 자리에 줄을 두게 한다. 호스트 글을 앞 쪽에 선방출했거나
    /// (`pre_emit_visible_rowbreak_host_text`) 같은 쪽에 이미 항목이 있으면 내지 않고, 줄이
    /// 쪽에 안 들어가면 종전대로 배치의 지연 렌더에 맡긴다.
    #[allow(clippy::too_many_arguments)]
    fn post_emit_visible_rowbreak_host_text(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        ctrl_idx: usize,
        para: &Paragraph,
        table: &crate::model::table::Table,
        composed_all: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
        host_push: f64,
    ) -> bool {
        if !crate::renderer::float_placement::partial_table_defers_visible_host(
            para, table, ctrl_idx,
        ) || st.pre_emitted_host_paras.contains(&para_idx)
        {
            return false;
        }
        let already_emitted = st.current_items.iter().any(|item| {
            matches!(item, PageItem::FullParagraph { para_index }
                | PageItem::PartialParagraph { para_index, .. }
                if *para_index == para_idx)
        });
        if already_emitted {
            return false;
        }
        let Some(comp) = composed_all.get(para_idx) else {
            return false;
        };
        let has_real_text = |line: &crate::renderer::composer::ComposedLine| {
            line.runs
                .iter()
                .any(|run| run.text.chars().any(|c| c > '\u{001F}' && c != '\u{FFFC}'))
        };
        let Some(start_line) = comp.lines.iter().position(has_real_text) else {
            return false;
        };
        let end_line = comp
            .lines
            .iter()
            .rposition(has_real_text)
            .map_or(comp.lines.len(), |i| i + 1);
        let col_w = st
            .layout
            .column_areas
            .get(st.current_column as usize)
            .map(|a| a.width)
            .unwrap_or(st.layout.body_area.width);
        let host_fmt = self.format_paragraph(para, Some(comp), styles, Some(col_w));
        let end_line = end_line.min(host_fmt.line_heights.len());
        if start_line >= end_line {
            return false;
        }
        let host_h = host_fmt.line_advances_sum(start_line..end_line);
        // 쪽 마지막 줄 뒤 줄간격은 쪽을 채우지 않는다(#6184 와 같은 fit 규약).
        let trailing_spacing = host_fmt
            .line_spacings
            .get(end_line - 1)
            .copied()
            .unwrap_or(0.0)
            .max(0.0);
        if st.current_height + (host_h - trailing_spacing).max(0.0) > st.available_height() {
            return false;
        }
        st.append_item(PageItem::PartialParagraph {
            para_index: para_idx,
            start_line,
            end_line,
        });
        if start_line == 0 {
            st.record_float_pushed_line_spacing(para_idx, host_push.max(0.0));
        }
        st.advance_flow_by(host_h);
        true
    }

    /// [Task #1753] 지연 이월되는 visible-host 자리차지 표의 후속 문단 선행 채움.
    ///
    /// 한글은 자리차지(TopAndBottom·vert=Para) RowBreak 표가 현재 쪽 잔여 공간에 안
    /// 들어가 다음 쪽으로 이월될 때, 후속 텍스트를 현재 쪽 잔여 공간에 먼저 채운다
    /// (fill-before-deferred-float — 2814765 pi52/53, 한글 PDF·저장 LINE_SEG 정합).
    /// rhwp 순차 모델에서는 이월 직전에 후속 control-free 문단들을 현재 쪽에 선행
    /// 배치하고 `prefilled_paras` 로 메인 루프에서 스킵한다.
    ///
    /// 가드: 단일 단 + 현재 쪽에 항목 존재 + 텍스트 anchor + RowBreak 자리차지 표
    /// (v_off ≥ 0). 후보 문단은 저장 첫 실줄 vpos 가 (host vpos, 본문높이HU] 구간
    /// (같은 쪽 연속 인코딩 — 누적좌표 문서는 자연 배제)이고 누적높이 fit 일 때만.
    #[allow(clippy::too_many_arguments)]
    fn prefill_before_deferred_table(
        &self,
        st: &mut TypesetState,
        para_idx: usize,
        para: &Paragraph,
        table: &crate::model::table::Table,
        paragraphs_all: &[Paragraph],
        composed_all: &[ComposedParagraph],
        styles: &ResolvedStyleSet,
    ) {
        use table::deferred_float_flow::MAX_PREFILL;
        if st.col_count != 1 || st.current_items.is_empty() {
            return;
        }
        if !para_has_visible_text(para)
            || !crate::renderer::float_placement::is_para_topbottom_float(&table.common)
            || !matches!(
                table.layout_page_break(),
                crate::model::table::TablePageBreak::RowBreak
            )
        {
            return;
        }
        let Some(host_seg) = para.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)) else {
            return;
        };
        let host_vpos = host_seg.vertical_pos;
        let body_h_hu = crate::renderer::px_to_hwpunit(st.layout.body_area.height, self.dpi);
        // [#6184] 음수 세로 오프셋은 표를 host 줄 **위**로 들어올리므로 종전에는
        // pre-emit 자체를 막았다. 그러나 저장 사다리가 "이 줄은 이 쪽 본문 안에서
        // 끝난다"고 증언하면 한글은 그 줄을 이 쪽 마지막 줄로 두고 표만 넘긴다
        // (156489124 pi=324: host vpos 71604 + lh 1200 = 72804 ≤ 본문 72847,
        // 다음 문단 vpos 6863 으로 리셋 — 한글 실측도 그 줄이 12쪽 1031.2).
        // 막아 두면 줄이 표와 함께 넘어가 다음 쪽 흐름표 위에 겹쳐 그려진다.
        // 증거 없는 음수(줄이 본문을 넘거나 다음 문단이 이어지는 경우)는 종전대로.
        if signed_hwpunit(table.common.vertical_offset) < 0 {
            let line_ends_inside = host_vpos >= 0
                && i64::from(host_vpos) + i64::from(host_seg.line_height) <= i64::from(body_h_hu);
            let next_resets = paragraphs_all
                .get(para_idx + 1)
                .and_then(|next| next.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)))
                .is_some_and(|seg| seg.vertical_pos < host_vpos);
            if !(line_ends_inside && next_resets) {
                return;
            }
        }
        // [Task #1811] HWPX 의 누적좌표 RowBreak 문서는 host 줄 pre-emit 자체를
        // 저장 vpos 가드보다 먼저 수행한다. 쪽 내부 vpos 를 가진 HWP/HWP3/일반 HWPX
        // 경로는 기존처럼 같은 쪽 저장 flow 확인 뒤에만 pre-emit 한다.
        let pre_emit_before_vpos_check = st.profile.hwpx_stored_layout() && host_vpos > body_h_hu;
        if pre_emit_before_vpos_check
            && !self.pre_emit_visible_rowbreak_host_text(st, para_idx, para, composed_all, styles)
        {
            return;
        }
        if host_vpos < 0 || host_vpos > body_h_hu {
            return; // 누적좌표 등 — 저장 flow 로 같은 쪽 여부를 알 수 없음
        }
        if !pre_emit_before_vpos_check
            && !self.pre_emit_visible_rowbreak_host_text(st, para_idx, para, composed_all, styles)
        {
            return;
        }
        let end = paragraphs_all.len().min(para_idx + 1 + MAX_PREFILL);
        for next_idx in (para_idx + 1)..end {
            let next = &paragraphs_all[next_idx];
            if !next.controls.is_empty() {
                break;
            }
            let Some(seg) = next.line_segs.iter().find(|ls| !is_synthetic_line_seg(ls)) else {
                break;
            };
            // 저장 flow 가 host 와 같은 쪽 연속임을 인코딩한 경우만.
            if seg.vertical_pos <= host_vpos
                || seg.vertical_pos.saturating_add(seg.line_height) > body_h_hu
            {
                break;
            }
            if !self.try_append_prefilled_paragraph(
                st,
                next_idx,
                paragraphs_all,
                composed_all,
                styles,
            ) {
                break;
            }
        }
    }

    // ========================================================
    // 다단 나누기 처리
    // ========================================================

    // ========================================================
    // 머리말/꼬리말/쪽 번호 처리
    // ========================================================

    // ========================================================
    // 유틸리티
    // ========================================================

    /// 문단에 블록 표 컨트롤이 있는지 감지
    fn paragraph_has_table(&self, para: &Paragraph) -> bool {
        use crate::renderer::height_measurer::is_tac_table_inline_in_para;
        let seg_width = para.line_segs.first().map(|s| s.segment_width).unwrap_or(0);
        para.controls.iter().any(|c| {
            matches!(c, Control::Table(t) if t.attr & 0x01 == 0
                || (t.attr & 0x01 != 0 && !is_tac_table_inline_in_para(t, seg_width, para)))
        })
    }

    /// Text-flow predicate only. A matching row can still paint a declared cell
    /// height, border, fill, or table-level fallback, so it must not by itself
    /// authorize a fragment-height overflow.
    fn row_has_no_text_or_controls(table: &crate::model::table::Table, row: usize) -> bool {
        let mut row_cells = table
            .cells
            .iter()
            .filter(|cell| cell.row as usize == row && cell.row_span == 1)
            .peekable();
        if row_cells.peek().is_none() {
            return false;
        }
        row_cells.all(|cell| {
            cell.paragraphs.iter().all(|para| {
                let trimmed = para.text.replace(|c: char| c.is_control(), "");
                trimmed.trim().is_empty() && para.controls.is_empty()
            })
        })
    }

    /// 표의 흐름 오프셋. 원본 common 값과 캡션을 포함한 점유 상자의 계약을
    /// paint와 같은 producer로 해석한다. 원본 IR은 변경하지 않는다.
    fn get_table_vertical_offset(table: &crate::model::table::Table) -> u32 {
        crate::renderer::float_placement::captioned_table_flow_vertical_offset_hu(table) as u32
    }
}

/// Task #321: 단일 문단의 컨트롤에서 body-wide TopAndBottom 표/도형이 차지하는 높이 계산.
///
/// col 1+ advance 시 current_height 시작값으로 사용하여 layout의 `body_wide_reserved`
/// 와 동일한 가용 공간 축소를 적용한다.
///
/// **Paper(용지) 기준 도형 가드 (v3 정밀화 #326)**: vert_rel_to=Paper 인 도형 중
/// 본문 영역과 겹치지 않는(머리말 영역에만 위치하는) 도형만 제외. body 와 겹치는
/// Paper 도형은 col 1 시작에 영향 → reserve 대상으로 포함.
fn compute_body_wide_top_reserve_for_para(
    para: &Paragraph,
    layout: &PageLayoutInfo,
    dpi: f64,
) -> f64 {
    use crate::model::shape::{TextWrap, VertRelTo};
    let body_w = layout.body_area.width;
    let body_h = layout.available_body_height();
    let body_top = layout.body_area.y;
    let mut max_bottom: f64 = 0.0;
    for ctrl in &para.controls {
        let common = match ctrl {
            Control::Shape(s) => s.common(),
            Control::Table(t) if !t.common.treat_as_char => &t.common,
            Control::Picture(p) if !p.common.treat_as_char => &p.common,
            _ => continue,
        };
        if let Some(bottom) = crate::renderer::float_placement::stored_square_top_band(
            para,
            ctrl,
            &layout.body_area,
            dpi,
        ) {
            max_bottom = max_bottom.max(bottom - body_top);
            continue;
        }
        if !matches!(common.text_wrap, TextWrap::TopAndBottom) || common.treat_as_char {
            continue;
        }
        let shape_w = crate::renderer::hwpunit_to_px(common.width as i32, dpi);
        if shape_w < body_w * 0.8 {
            continue;
        }
        let shape_h = crate::renderer::hwpunit_to_px(common.height as i32, dpi);
        let raw_v_offset = crate::renderer::hwpunit_to_px(common.vertical_offset as i32, dpi);

        // body-rel 기준 시작/끝 y 계산.
        // - VertRelTo::Paper: vertical_offset 이 용지 상단(= 0) 기준 → body_top 차감.
        //   본문과 전혀 겹치지 않으면(머리말만 점유) 제외.
        //   본문 위쪽으로 일부 빠져나가면(shape_top_abs < body_top) 본문 침범 영역만 reserve.
        // - VertRelTo::Page / Para: vertical_offset 이 본문/단 top 기준 → body-rel 그대로.
        let (body_y, body_bottom) = if matches!(common.vert_rel_to, VertRelTo::Paper) {
            let shape_top_abs = raw_v_offset;
            let shape_bottom_abs = shape_top_abs + shape_h;
            if shape_bottom_abs <= body_top {
                continue;
            }
            (
                (shape_top_abs - body_top).max(0.0),
                shape_bottom_abs - body_top,
            )
        } else {
            (raw_v_offset, raw_v_offset + shape_h)
        };

        if body_y > body_h / 3.0 {
            continue;
        }
        let outer_bottom = crate::renderer::hwpunit_to_px(common.margin.bottom as i32, dpi);
        let bottom = body_bottom + outer_bottom;
        if bottom > max_bottom {
            max_bottom = bottom;
        }
    }
    max_bottom
}

#[cfg(test)]
mod issue_3820_saved_rowbreak_first_fragment_frame_contract {
    use super::{
        nearest_saved_rowbreak_frame_row_end, saved_rowbreak_first_fragment_flow_overflow_allowance,
    };

    #[test]
    fn rejects_missing_or_unowned_saved_frames() {
        assert_eq!(
            saved_rowbreak_first_fragment_flow_overflow_allowance(0, true, 959.0, 970.0),
            0.0,
            "height=0 is not a saved first-fragment frame"
        );
        assert_eq!(
            saved_rowbreak_first_fragment_flow_overflow_allowance(0x8000_0000, true, 959.0, 970.0,),
            0.0,
            "signed-wrap height is not a usable source frame"
        );
        assert_eq!(
            saved_rowbreak_first_fragment_flow_overflow_allowance(929, false, 959.0, 970.0,),
            0.0,
            "an outer wrapper frame cannot authorize an inner table row cut"
        );
    }

    #[test]
    fn uses_the_absolute_fragment_bottom_not_row_space() {
        assert_eq!(
            saved_rowbreak_first_fragment_flow_overflow_allowance(929, true, 972.0, 970.0,),
            0.0,
            "the source frame may not enter the fragment-reserved bottom lane"
        );
        assert!(
            (saved_rowbreak_first_fragment_flow_overflow_allowance(929, true, 959.0, 971.0,)
                - 12.0)
                .abs()
                < f64::EPSILON,
            "host-before flow spacing does not shrink the saved object's physical slack"
        );
    }

    #[test]
    fn frame_slack_stops_at_its_nearest_row_boundary() {
        assert_eq!(
            nearest_saved_rowbreak_frame_row_end(
                87.0,
                &[30.0, 55.0, 60.0],
                &[30.0, 56.0, 60.0],
                0.0
            ),
            Some(2),
            "saved-frame slack may absorb measurement drift at row 2, but not admit row 3"
        );

        // [#6123] 프레임이 행 경계에 **닿지 못하면** 그 행을 소유하지 않는다 —
        // 행 경계 신호가 아니라 행 안에서 끊으라는 신호다(3112461 7쪽: 프레임 388 이
        // 행 1(36~573)의 65% 지점인데 573 으로 스냅돼 행이 통째로 앞 쪽에 얹혔다).
        assert_eq!(
            nearest_saved_rowbreak_frame_row_end(388.0, &[36.0, 537.0], &[36.0, 472.0], 0.0),
            None,
            "모자란 몫(185.1)이 흡수 가능한 drift(65.0)를 넘으면 행 경계가 아니다"
        );

        // 경계를 **넘어서는** 프레임은 종전대로 그 행 끝을 소유한다 — 초과분은
        // 다음 행의 측정↔저장 drift 다(21298295 별표 5: 행 13 경계를 22.6px 초과).
        assert_eq!(
            nearest_saved_rowbreak_frame_row_end(112.6, &[30.0, 60.0], &[30.0, 60.0], 0.0),
            Some(2),
            "프레임이 경계를 지나면 그 행까지는 확실히 첫 조각 소유다"
        );

        // 조각이 될 수 없는 크기(25px)만큼 모자란 프레임은 그 행을 그대로 소유한다 —
        // 그 잔여는 어차피 다음 쪽으로 옮길 수 없다(1790387 PrEP 보고서: 16.8px).
        assert_eq!(
            nearest_saved_rowbreak_frame_row_end(
                405.8,
                &[28.4, 103.5, 163.5, 127.3],
                &[28.4, 103.5, 163.5, 127.3],
                0.0
            ),
            Some(4),
            "16.8px 잔여는 독립 조각이 될 수 없으므로 행을 통째로 둔다"
        );

        // 저장 행 높이를 못 읽는 표(전부 0)는 종전 최근접 스냅을 유지한다.
        assert_eq!(
            nearest_saved_rowbreak_frame_row_end(87.0, &[30.0, 55.0, 60.0], &[0.0, 0.0, 0.0], 0.0),
            Some(2),
            "저장 높이가 없으면 측정 최근접 스냅이 유일한 신호다"
        );
    }
}

#[cfg(test)]
mod issue_3780_line_advance_oob {
    use super::FormattedParagraph;

    fn fp(lines: usize) -> FormattedParagraph {
        FormattedParagraph {
            stored_ladder_is_filler: false,
            exact_reflow_text_box: false,
            computed_paragraph: None,
            tail_line_remaining_width: None,
            computed_host_lines: None,
            host_composition: None,
            square_host_plan: None,
            total_height: 0.0,
            line_heights: vec![10.0; lines],
            line_spacings: vec![2.0; lines],
            spacing_before: 0.0,
            spacing_after: 0.0,
            height_for_fit: 0.0,
            tac_outer_margin_v_px: 0.0,
        }
    }

    /// red→green: 클램프를 원복하면 이 두 테스트는 index out of bounds 로 패닉한다
    /// (len 31 / index 31 — 실측 사고와 동일한 상태).
    #[test]
    fn out_of_range_line_advance_is_zero_not_panic() {
        let p = fp(31);
        assert_eq!(p.line_advance(31), 0.0);
        assert_eq!(p.line_advance(30), 12.0, "경계 안 동작 불변");
    }

    #[test]
    fn out_of_range_advance_sum_clamps_to_existing_lines() {
        let p = fp(31);
        assert_eq!(p.line_advances_sum(29..33), 24.0, "29,30 두 줄만 합산");
        assert_eq!(p.line_advances_sum(0..31), 31.0 * 12.0, "전 범위 동작 불변");
        assert_eq!(p.line_advances_sum(40..50), 0.0);
    }
}

#[cfg(test)]
mod tests {
    use crate::renderer::float_placement::native_empty_host_rowbreak_line_advance_hu;

    #[test]
    fn fullpage_image_single_page_policy_requires_strict_majority() {
        assert!(!super::has_majority_fullpage_images(0, 0));
        assert!(!super::has_majority_fullpage_images(1, 1));
        assert!(!super::has_majority_fullpage_images(2, 4));
        assert!(super::has_majority_fullpage_images(2, 3));
        assert!(super::has_majority_fullpage_images(3, 5));
    }

    use super::*;
    use crate::model::page::{ColumnDef, PageDef};
    use crate::model::paragraph::{LineSeg, Paragraph};
    use crate::model::shape::{CommonObjAttr, TextWrap, VertRelTo};
    use crate::model::table::{Cell, Table, TablePageBreak};
    use crate::model::Padding;
    use crate::renderer::composer::ComposedParagraph;
    use crate::renderer::height_measurer::HeightMeasurer;
    use crate::renderer::layout::LayoutEngine;
    use crate::renderer::page_layout::PageLayoutInfo;
    use crate::renderer::pagination::Paginator;
    use crate::renderer::style_resolver::ResolvedStyleSet;

    fn a4_page_def() -> PageDef {
        PageDef {
            width: 59528,
            height: 84188,
            margin_left: 8504,
            margin_right: 8504,
            margin_top: 5669,
            margin_bottom: 4252,
            margin_header: 4252,
            margin_footer: 4252,
            margin_gutter: 0,
            ..Default::default()
        }
    }

    #[test]
    fn single_column_vpos_reset_gate_requires_exclusive_tac_picture_or_shape() {
        let tac_picture = || {
            let mut picture = crate::model::image::Picture::default();
            picture.common.treat_as_char = true;
            Control::Picture(Box::new(picture))
        };

        let picture_only = Paragraph {
            controls: vec![tac_picture()],
            ..Default::default()
        };
        assert!(para_has_only_treat_as_char_picture_or_shape(&picture_only));

        let mut table = Table::default();
        table.common.treat_as_char = true;
        let mixed_controls = Paragraph {
            controls: vec![tac_picture(), Control::Table(Box::new(table))],
            ..Default::default()
        };
        assert!(
            !para_has_only_treat_as_char_picture_or_shape(&mixed_controls),
            "TAC 그림과 표가 섞인 문단은 단일 단 vpos-reset 강제 분리 대상이 아니다"
        );

        let picture_with_text = Paragraph {
            text: "설명".to_string(),
            controls: vec![tac_picture()],
            ..Default::default()
        };
        assert!(!para_has_only_treat_as_char_picture_or_shape(
            &picture_with_text
        ));
    }

    /// [#4333] 인라인(글자처럼) 도형의 흐름 높이는 조판과 렌더가 같은 정의를 써야 한다.
    ///
    /// 조판은 저장 프레임(`common.height`)만, 렌더는 프레임과 개체 표시 높이
    /// (`shape_attr.current_height`) 중 큰 값을 썼다. samples/ 의 인라인 도형 868개
    /// 가운데 354개(38개 문서)가 둘이 다르므로, 두 정의가 갈리면 그 줄의 예약 높이가
    /// 조판과 렌더에서 달라진다. 두 경로가 `ShapeObject::flow_height_hu` 하나를 보는지
    /// 확인한다 — 매직 넘버가 아니라 **두 정의가 같다**를 단언한다.
    #[test]
    fn typeset_and_render_agree_on_inline_shape_flow_height() {
        use crate::model::shape::{RectangleShape, ShapeObject};

        let dpi = 96.0;
        let shape = ShapeObject::Rectangle(RectangleShape {
            common: CommonObjAttr {
                width: 20000,
                height: 2400,
                treat_as_char: true,
                ..Default::default()
            },
            ..Default::default()
        });
        let mut shape = shape;
        shape.shape_attr_mut().current_height = 4066;
        let expected = crate::renderer::hwpunit_to_px(shape.flow_height_hu(), dpi);
        assert!(
            expected > crate::renderer::hwpunit_to_px(shape.common().height as i32, dpi),
            "표본 전제: 개체 표시 높이가 저장 프레임보다 크다"
        );

        let para = Paragraph {
            text: "\u{FFFC}".to_string(),
            char_count: 1,
            controls: vec![Control::Shape(Box::new(shape))],
            ..Default::default()
        };
        let comp = ComposedParagraph {
            lines: vec![crate::renderer::composer::ComposedLine {
                runs: Vec::new(),
                line_height: 4066,
                baseline_distance: 0,
                segment_width: 20000,
                column_start: 0,
                line_spacing: 0,
                has_line_break: false,
                char_start: 0,
            }],
            para_style_id: 0,
            inline_controls: Vec::new(),
            numbering_text: None,
            tac_controls: vec![(0, 20000, 0)],
            footnote_positions: Vec::new(),
            tab_extended: Vec::new(),
            horizontal_shaping: None,
            frame_geometry: None,
        };

        // 조판(페이지네이션)이 이 줄에 예약하는 인라인 개체 높이.
        let typeset_reserved = line_tac_picture_or_shape_height(&para, &comp, 0, dpi)
            .expect("조판이 인라인 도형 줄을 인식해야 한다");
        // 렌더가 인라인 도형을 배치할 때 쓰는 높이(같은 단일 정의).
        let render_reserved = crate::renderer::tac_object_flow_height_px(&para.controls[0], dpi)
            .expect("렌더가 인라인 도형 높이를 산출해야 한다");

        assert_eq!(typeset_reserved, render_reserved);
        assert_eq!(typeset_reserved, expected);
    }

    fn make_paragraph_with_height(line_height: i32) -> Paragraph {
        Paragraph {
            line_segs: vec![LineSeg {
                line_height,
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn composed_footnote_height_separates_body_exact_metric_from_table_queue_floor() {
        let dpi = 96.0;
        let empty_footnote = Footnote::default();
        assert_eq!(composed_footnote_content_height(&empty_footnote, dpi), 0.0);
        assert_eq!(
            queued_table_footnote_content_height(&empty_footnote, dpi),
            hwpunit_to_px(400, dpi),
        );

        let short_line = Footnote {
            paragraphs: vec![Paragraph {
                text: "짧음".to_string(),
                char_count: 3,
                line_segs: vec![LineSeg {
                    line_height: 200,
                    ..Default::default()
                }],
                ..Default::default()
            }],
            ..Default::default()
        };
        assert_eq!(
            composed_footnote_content_height(&short_line, dpi),
            hwpunit_to_px(200, dpi),
        );
        assert_eq!(
            queued_table_footnote_content_height(&short_line, dpi),
            hwpunit_to_px(400, dpi),
        );

        let empty_paragraph = Footnote {
            paragraphs: vec![Paragraph::default()],
            ..Default::default()
        };
        assert_eq!(
            composed_footnote_content_height(&empty_paragraph, dpi),
            hwpunit_to_px(400, dpi),
        );
    }

    fn single_column_split_topology() -> Table {
        let mut heading = Cell::new_empty(0, 0, 20_000, 1_000, 1);
        heading.col_span = 2;
        heading.paragraphs[0].text = "머리".to_string();
        heading.paragraphs[0].char_count = 3;

        let mut body = Cell::new_empty(0, 1, 10_000, 2_000, 2);
        body.paragraphs[0].text = "긴 본문".to_string();
        body.paragraphs[0].char_count = 5;
        body.paragraphs[0].raw_header_extra = vec![0; 12];
        body.paragraphs[0].raw_header_extra[6..10].copy_from_slice(&42_u32.to_le_bytes());
        let peer = Cell::new_from_template(1, 1, 10_000, 2_000, &body);

        Table {
            row_count: 2,
            col_count: 2,
            cells: vec![heading, body, peer],
            page_break: TablePageBreak::RowBreak,
            ..Default::default()
        }
    }

    #[test]
    fn visible_host_caption_classifier_excludes_section_headings() {
        use crate::model::control::{AutoNumber, AutoNumberType, NewNumber};

        let mut para = Paragraph {
            text: "표 27. EU 미성년자 생존 장기기증 허용 국가 규정".to_string(),
            ..Default::default()
        };
        assert!(visible_host_is_numbered_table_caption(&para));

        para.text = "Table 27. Minor living donation rules".to_string();
        assert!(visible_host_is_numbered_table_caption(&para));

        para.text = "1. 편성기준".to_string();
        assert!(
            !visible_host_is_numbered_table_caption(&para),
            "#2097 section heading must not be pre-emitted as a table caption"
        );

        para.text = "표 작성 기준".to_string();
        assert!(
            !visible_host_is_numbered_table_caption(&para),
            "a word beginning with 표 is not a numbered caption"
        );

        para.text = "표  ".to_string();
        para.controls = vec![Control::AutoNumber(AutoNumber {
            number_type: AutoNumberType::Table,
            ..Default::default()
        })];
        assert!(
            visible_host_is_numbered_table_caption(&para),
            "literal이 아닌 표 AutoNumber도 visible-host 캡션이다"
        );

        para.text = "번호를 다시 시작하는 표".to_string();
        para.controls = vec![Control::NewNumber(NewNumber {
            number_type: AutoNumberType::Table,
            number: 27,
        })];
        assert!(visible_host_is_numbered_table_caption(&para));

        para.text = "표 작성 기준".to_string();
        para.controls = vec![Control::AutoNumber(AutoNumber {
            number_type: AutoNumberType::Picture,
            ..Default::default()
        })];
        assert!(!visible_host_is_numbered_table_caption(&para));

        para.text = "1. 편성기준".to_string();
        para.controls = vec![Control::NewNumber(NewNumber {
            number_type: AutoNumberType::Page,
            number: 1,
        })];
        assert!(!visible_host_is_numbered_table_caption(&para));
    }

    #[test]
    fn reparsed_single_column_split_topology_is_narrow() {
        let split = single_column_split_topology();
        assert!(
            is_reparsed_single_column_cell_split_row(&split, 1),
            "1열 표의 본문 셀을 1×2로 분할한 저장 구조는 식별한다"
        );
        assert!(
            !is_reparsed_single_column_cell_split_row(&split, 0),
            "전폭 행 자체는 분할 행이 아니다"
        );

        let mut original = split.clone();
        original.col_count = 1;
        original.cells.truncate(2);
        original.cells[0].col_span = 1;
        original.cells[1].width = 20_000;
        assert!(
            !is_reparsed_single_column_cell_split_row(&original, 1),
            "원본 1열 giant-cell에는 strict cut을 적용하지 않는다"
        );

        let mut ordinary_two_column = split.clone();
        ordinary_two_column.cells[2].paragraphs[0].text = "일반 우측 본문".to_string();
        ordinary_two_column.cells[2].paragraphs[0].char_count = 8;
        assert!(
            !is_reparsed_single_column_cell_split_row(&ordinary_two_column, 1),
            "병합 제목행과 일반 2열 데이터행 조합은 #2097 bottom squeeze를 보존한다"
        );

        let mut authored_blank = split.clone();
        authored_blank.cells[2].paragraphs[0].has_para_text = true;
        assert!(
            !is_reparsed_single_column_cell_split_row(&authored_blank, 1),
            "빈 문자열이어도 PARA_TEXT를 가진 자연 작성 셀은 분할 템플릿 빈 셀이 아니다"
        );

        let mut natural_blank = split.clone();
        natural_blank.cells[2].paragraphs[0].raw_header_extra[6..10]
            .copy_from_slice(&7_u32.to_le_bytes());
        assert!(
            !is_reparsed_single_column_cell_split_row(&natural_blank, 1),
            "독립 instanceId를 가진 자연 작성 빈 셀은 zeroed template clone이 아니다"
        );

        let mut blank_left = split.clone();
        blank_left.cells[1].col = 1;
        blank_left.cells[2].col = 0;
        assert!(
            !is_reparsed_single_column_cell_split_row(&blank_left, 1),
            "빈 왼쪽/본문 오른쪽의 자연 2열 행은 split_cell_into(1×2) 형상이 아니다"
        );

        let mut mixed_grid = split;
        mixed_grid
            .cells
            .push(Cell::new_empty(1, 0, 10_000, 1_000, 1));
        mixed_grid.cells[0].col_span = 1;
        assert!(
            !is_reparsed_single_column_cell_split_row(&mixed_grid, 1),
            "다른 행이 원래부터 다열이면 1열→2열 분할 저장 구조가 아니다"
        );
    }

    #[test]
    fn saved_tail_fit_chain_stops_on_third_applicable_line() {
        assert_eq!(
            saved_tail_fit_chain_decision(0, true, false, false),
            SavedTailFitChainDecision::Advance,
            "첫 저장 꼬리줄은 허용한다"
        );
        assert_eq!(
            saved_tail_fit_chain_decision(1, true, false, false),
            SavedTailFitChainDecision::Advance,
            "둘째 저장 꼬리줄은 허용한다"
        );
        assert_eq!(
            saved_tail_fit_chain_decision(2, true, false, false),
            SavedTailFitChainDecision::Break,
            "셋째 저장 꼬리줄에서 예산 초과 연쇄를 끊는다"
        );
    }

    #[test]
    fn saved_tail_fit_chain_keeps_authoritative_boundary_exceptions() {
        assert_eq!(
            saved_tail_fit_chain_decision(2, true, true, false),
            SavedTailFitChainDecision::NoChange,
            "HWP 권위 경계는 저장 꼬리줄 상한으로 중단하지 않는다"
        );
        assert_eq!(
            saved_tail_fit_chain_decision(2, true, false, true),
            SavedTailFitChainDecision::NoChange,
            "native HWP5 실제 각주 경계 예외는 저장 꼬리줄 상한으로 중단하지 않는다"
        );
        assert_eq!(
            saved_tail_fit_chain_decision(2, false, false, false),
            SavedTailFitChainDecision::NoChange,
            "저장 꼬리줄 판정이 아니면 연쇄 상태를 바꾸지 않는다"
        );
    }

    #[test]
    fn saved_line_clears_footnote_area_requires_every_boundary() {
        let allows = |footnote_height, is_single_column, overflow, bounds, current_height| {
            saved_line_clears_footnote_area(
                footnote_height,
                is_single_column,
                overflow,
                bounds,
                1_000.0,
                current_height,
                current_height,
            )
        };
        // [#7695] 조각 시작 200px, 판정 줄의 흐름 위치 250px: 저장 줄이 그 사이면 받는다.
        let allows_in_fragment = |bounds, fragment_top, line_top| {
            saved_line_clears_footnote_area(
                300.0,
                true,
                0.0,
                bounds,
                1_000.0,
                fragment_top,
                line_top,
            )
        };
        assert!(
            allows_in_fragment(Some((230.0, 245.0)), 200.0, 250.0),
            "조각 둘째 줄 이후의 저장 줄은 그 줄의 흐름 위치까지 받는다"
        );
        assert!(
            !allows_in_fragment(Some((250.1, 265.0)), 200.0, 250.0),
            "저장 줄이 그 줄의 흐름 위치보다 낮으면 받지 않는다"
        );
        assert!(
            !allows_in_fragment(Some((183.9, 198.0)), 200.0, 250.0),
            "조각 시작보다 허용오차 넘게 위인 저장 줄은 받지 않는다"
        );

        assert!(
            allows(300.0, true, 0.0, Some((200.0, 700.0)), 216.0),
            "각주 위 저장 좌표, 넘침 없음, 16px 흐름 허용오차의 경계값은 허용한다"
        );
        assert!(
            !allows(0.0, true, 0.0, Some((200.0, 700.0)), 216.0),
            "각주가 없으면 예외를 적용하지 않는다"
        );
        assert!(
            !allows(300.0, false, 0.0, Some((200.0, 700.0)), 216.0),
            "다단에는 적용하지 않는다"
        );
        assert!(
            !allows(300.0, true, 0.1, Some((200.0, 700.0)), 216.0),
            "각주 위 저장 좌표라도 본문 끝을 넘는 줄은 허용하지 않는다"
        );
        assert!(
            !allows(300.0, true, 0.0, Some((200.0, 700.1)), 216.0),
            "저장 줄 하단이 각주 영역에 닿으면 허용하지 않는다"
        );
        assert!(
            !allows(300.0, true, 0.0, Some((-0.1, 700.0)), 0.0),
            "쪽 밖 음수 저장 좌표는 허용하지 않는다"
        );
        assert!(
            !allows(300.0, true, 0.0, Some((1_000.1, 700.0)), 0.0),
            "본문 높이를 넘는 저장 좌표는 허용하지 않는다"
        );
        assert!(
            !allows(300.0, true, 0.0, Some((200.0, 700.0)), 216.1),
            "흐름 커서가 저장 좌표보다 낮으면 허용하지 않는다"
        );
    }

    /// [#3925] HWPX empty-host 그림 표의 raw anchor는 다음 저장 사다리가 개체 높이를
    /// 실제로 비운 경우에만 쓸 수 있다. 작은 일반 줄의 vpos를 그대로 쓰면
    /// 36324768처럼 표 높이를 이중 소비해 뒤 본문을 다음 쪽으로 민다.
    #[test]
    fn stored_host_anchor_requires_next_ladder_room() {
        let table = Table {
            common: CommonObjAttr {
                height: 18_000,
                ..Default::default()
            },
            outer_margin_top: 500,
            outer_margin_bottom: 300,
            ..Default::default()
        };
        let host = Paragraph {
            line_segs: vec![LineSeg {
                vertical_pos: 1_000,
                line_height: 1_100,
                ..Default::default()
            }],
            ..Default::default()
        };
        let short_ladder = Paragraph {
            line_segs: vec![LineSeg {
                vertical_pos: 2_500,
                ..Default::default()
            }],
            ..Default::default()
        };

        assert!(
            !stored_ladder_leaves_object_room(&host, Some(&short_ladder), &table),
            "짧은 다음-vpos 간격은 raw anchor의 저장 증거가 아니다"
        );

        let full_ladder = Paragraph {
            line_segs: vec![LineSeg {
                vertical_pos: 19_800,
                ..Default::default()
            }],
            ..Default::default()
        };
        assert!(
            stored_ladder_leaves_object_room(&host, Some(&full_ladder), &table),
            "다음 저장 vpos가 표 높이와 바깥 여백을 모두 비우면 사다리 증거다"
        );

        let covered_host = Paragraph {
            line_segs: vec![LineSeg {
                vertical_pos: 1_000,
                line_height: 18_800,
                ..Default::default()
            }],
            ..Default::default()
        };
        assert!(
            !stored_ladder_leaves_object_room(&covered_host, None, &table),
            "host 줄 높이는 #3738 표적을 되살릴 수 있어 다음-vpos 사다리 없이 raw anchor의 증거가 아니다"
        );
    }

    /// [#3900] 합성 LineSeg는 serializer가 만든 placeholder라 물리 페이지 경계의
    /// 저장 증거가 아니다. 앞·뒤 양쪽 모두 실제 저장 줄만 보아야 한다.
    #[test]
    fn stored_vpos_rewind_ignores_synthetic_line_segments() {
        let previous = Paragraph {
            line_segs: vec![
                LineSeg {
                    vertical_pos: 41_645,
                    ..Default::default()
                },
                LineSeg {
                    vertical_pos: 0,
                    tag: LineSeg::TAG_IMPLEMENTATION_PROPERTY,
                    ..Default::default()
                },
            ],
            ..Default::default()
        };
        let current = Paragraph {
            line_segs: vec![
                LineSeg {
                    vertical_pos: 0,
                    tag: LineSeg::TAG_IMPLEMENTATION_PROPERTY,
                    ..Default::default()
                },
                LineSeg {
                    vertical_pos: 1_000,
                    ..Default::default()
                },
            ],
            ..Default::default()
        };
        let paragraphs = vec![previous, current.clone()];

        let previous_vpos = preceding_stored_vpos(&paragraphs, 1);
        assert_eq!(previous_vpos, Some(41_645));
        assert!(stored_vpos_rewinds(previous_vpos, &current));
    }

    fn hwpx_tail_page_break_candidate(break_type: ColumnBreakType) -> (Paragraph, Paragraph) {
        let paragraph = Paragraph {
            text: "앞 줄\n마지막 줄".to_string(),
            line_segs: vec![
                LineSeg {
                    vertical_pos: 6_000,
                    line_height: 1_000,
                    ..Default::default()
                },
                LineSeg {
                    vertical_pos: 0,
                    line_height: 1_000,
                    ..Default::default()
                },
            ],
            ..Default::default()
        };
        let next = Paragraph {
            column_type: break_type,
            ..Default::default()
        };
        (paragraph, next)
    }

    #[test]
    fn hwpx_explicit_page_break_tail_splits_only_last_stored_line() {
        for break_type in [ColumnBreakType::Page, ColumnBreakType::Section] {
            let (paragraph, next) = hwpx_tail_page_break_candidate(break_type);
            assert_eq!(
                hwpx_explicit_page_break_tail_line(&paragraph, Some(&next), 2, 100.0, DEFAULT_DPI,),
                Some(1),
                "{break_type:?} 명시 나눔 앞의 vpos=0 tail만 분리해야 한다"
            );
        }
    }

    #[test]
    fn hwpx_explicit_page_break_tail_requires_all_stored_layout_evidence() {
        let rejects = |paragraph: Paragraph, next: Paragraph, line_count| {
            assert_eq!(
                hwpx_explicit_page_break_tail_line(
                    &paragraph,
                    Some(&next),
                    line_count,
                    100.0,
                    DEFAULT_DPI,
                ),
                None,
                "불완전한 저장 증거는 일반 문단 쪽 경계로 승격하면 안 된다"
            );
        };

        let (paragraph, _) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
        rejects(paragraph, Paragraph::default(), 2);

        let (paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Column);
        rejects(paragraph, next, 2);

        let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
        paragraph.line_segs[1].vertical_pos = 1;
        rejects(paragraph, next, 2);

        let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
        paragraph.line_segs.push(LineSeg::default());
        rejects(paragraph, next, 2);

        let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
        paragraph.line_segs[0].vertical_pos = 3_000;
        rejects(paragraph, next, 2);

        let (mut paragraph, next) = hwpx_tail_page_break_candidate(ColumnBreakType::Page);
        paragraph.line_segs[0].vertical_pos = 7_000;
        rejects(paragraph, next, 2);
    }

    #[test]
    fn issue2439_native_empty_host_rowbreak_evidence_is_narrow() {
        let table = Table {
            page_break: TablePageBreak::RowBreak,
            common: CommonObjAttr {
                treat_as_char: false,
                text_wrap: TextWrap::TopAndBottom,
                vert_rel_to: VertRelTo::Para,
                vertical_offset: 350,
                ..Default::default()
            },
            ..Default::default()
        };
        let anchor = Paragraph {
            line_segs: vec![LineSeg {
                line_height: 1200,
                line_spacing: 240,
                ..Default::default()
            }],
            controls: vec![Control::Table(Box::new(table.clone()))],
            ..Default::default()
        };
        // [#2808] 접힌 ladder 증거: next.vpos - anchor.vpos == anchor 줄 advance 일 때만
        // 한컴이 host 줄을 실 흐름에 계상한 것으로 본다 (#2439 재현 문서 서명).
        let signature = Paragraph {
            text: "signature".to_string(),
            line_segs: vec![LineSeg {
                line_height: 1000,
                vertical_pos: 1440,
                ..Default::default()
            }],
            ..Default::default()
        };
        let line_advance =
            native_empty_host_rowbreak_line_advance_hu(true, &anchor, &table, Some(&signature))
                .expect("native evidence line advance");
        assert_eq!(line_advance, 1440);
        let tail = hwpunit_to_px(line_advance + 350, DEFAULT_DPI);
        assert!(
            (tail - hwpunit_to_px(1790, DEFAULT_DPI)).abs() < 0.01,
            "tail must be stored line advance + positive vertical_offset"
        );

        assert!(native_empty_host_rowbreak_line_advance_hu(
            false,
            &anchor,
            &table,
            Some(&signature),
        )
        .is_none());
        assert!(native_empty_host_rowbreak_line_advance_hu(
            true,
            &anchor,
            &table,
            Some(&Paragraph::new_empty()),
        )
        .is_none());

        let mut two_tables = anchor.clone();
        two_tables
            .controls
            .push(Control::Table(Box::new(table.clone())));
        assert!(native_empty_host_rowbreak_line_advance_hu(
            true,
            &two_tables,
            &table,
            Some(&signature),
        )
        .is_none());

        // [#2808] 물리 ladder(다음 문단 vpos 가 표 높이를 이미 포함) 문서는 tail 을
        // 더하면 이중 계상 — 증거 불일치로 억제되어야 한다 (10k r19 회귀 4건).
        let mut physical_ladder_signature = signature.clone();
        physical_ladder_signature.line_segs[0].vertical_pos = 11202;
        assert!(native_empty_host_rowbreak_line_advance_hu(
            true,
            &anchor,
            &table,
            Some(&physical_ladder_signature),
        )
        .is_none());
    }

    fn issue2814_half_page_picture(height_hu: u32) -> Control {
        use crate::model::shape::{TextWrap, VertRelTo};
        let mut pic = crate::model::image::Picture::default();
        pic.common.treat_as_char = false;
        pic.common.text_wrap = TextWrap::TopAndBottom;
        pic.common.vert_rel_to = VertRelTo::Para;
        pic.common.width = 40000;
        pic.common.height = height_hu;
        Control::Picture(Box::new(pic))
    }

    fn issue2814_typeset_pages(host: Paragraph) -> Vec<usize> {
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let paras = vec![host];
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let (_, measured) = paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );
        result
            .pages
            .iter()
            .map(|page| {
                page.column_contents
                    .iter()
                    .flat_map(|col| col.items.iter())
                    .filter(|item| matches!(item, PageItem::Shape { .. }))
                    .count()
            })
            .collect()
    }

    /// [#2814] 한 문단에 co-anchored 절반쪽 그림이 여럿(≥3)이면 쪽 용량 기반으로
    /// 분배한다 — 한컴은 흐름처럼 쪽을 채우며 넘긴다(창조경제 보고서: 37장 = 2장/쪽).
    #[test]
    fn issue2814_multi_coanchored_half_page_pictures_distribute_across_pages() {
        let mut host = make_paragraph_with_height(900);
        host.controls = (0..6).map(|_| issue2814_half_page_picture(30000)).collect();
        let shapes_per_page = issue2814_typeset_pages(host);
        assert_eq!(
            shapes_per_page,
            vec![2, 2, 2],
            "절반쪽 그림 6장은 쪽당 2장씩 3쪽으로 분배되어야 한다",
        );
    }

    /// [#2814] 2장 스택은 발동하지 않는다 — 한컴이 razor-full 쪽에 압축 유지하는
    /// 실측 반례(1051000-201800093 p60) 보호. 초과분은 기존 overflow 관용에 맡긴다.
    #[test]
    fn issue2814_two_picture_stack_keeps_current_page() {
        let mut host = make_paragraph_with_height(900);
        host.controls = (0..2).map(|_| issue2814_half_page_picture(35000)).collect();
        let shapes_per_page = issue2814_typeset_pages(host);
        assert_eq!(
            shapes_per_page,
            vec![2],
            "2장 스택은 쪽 이월 없이 현재 쪽을 유지해야 한다",
        );
    }

    #[test]
    fn issue2439_strict_following_plain_text_fit_is_consumed_once() {
        let plain = Paragraph {
            text: "signature".to_string(),
            ..Default::default()
        };
        let mut pending = true;
        assert!(take_strict_plain_text_fit_after_empty_host_float_once(
            &mut pending,
            &plain
        ));
        assert!(!pending);
        assert!(!take_strict_plain_text_fit_after_empty_host_float_once(
            &mut pending,
            &plain
        ));

        let mut pending = true;
        assert!(!take_strict_plain_text_fit_after_empty_host_float_once(
            &mut pending,
            &Paragraph::new_empty(),
        ));
        assert!(
            pending,
            "an ineligible paragraph must not consume the one-shot"
        );
        assert!(take_strict_plain_text_fit_after_empty_host_float_once(
            &mut pending,
            &plain,
        ));

        assert_eq!(paragraph_page_end_fit_height(21.3, 13.3, false), 13.3);
        assert_eq!(paragraph_page_end_fit_height(21.3, 13.3, true), 21.3);
    }

    fn issue2439_cut_paragraph(line_count: usize, line_height: i32) -> Paragraph {
        Paragraph {
            text: "가".repeat(line_count),
            char_count: line_count as u32,
            line_segs: (0..line_count)
                .map(|line| LineSeg {
                    vertical_pos: line as i32 * line_height,
                    line_height,
                    text_height: line_height,
                    line_spacing: 0,
                    ..Default::default()
                })
                .collect(),
            ..Default::default()
        }
    }

    #[test]
    fn issue2439_row_orphan_guard_uses_padded_visible_fragment_height() {
        // Reproduction row contract: columns 0..31 each finish their one line, while the remarks
        // cell consumes two of three 900-HU lines.  Content-only progress is 24px, just below the
        // 25px orphan threshold, but the painted fragment includes 141-HU top/bottom padding.
        let cells = (0..33u16)
            .map(|col| Cell {
                row: 0,
                col,
                row_span: 1,
                col_span: 1,
                width: if col == 32 { 5421 } else { 1940 },
                height: 2693,
                paragraphs: vec![if col == 32 {
                    issue2439_cut_paragraph(3, 900)
                } else {
                    issue2439_cut_paragraph(1, 1000)
                }],
                ..Default::default()
            })
            .collect();
        let table = Table {
            row_count: 1,
            col_count: 33,
            padding: Padding {
                left: 510,
                right: 510,
                top: 141,
                bottom: 141,
            },
            page_break: TablePageBreak::RowBreak,
            cells,
            ..Default::default()
        };
        let engine = LayoutEngine::new(DEFAULT_DPI);
        let styles = ResolvedStyleSet::default();
        let cut = engine.advance_row_cut(&table, 0, &[], 35.6, &styles);

        let mut expected_cut = vec![1usize; 33];
        expected_cut[32] = 2;
        assert_eq!(
            cut.end_cut, expected_cut,
            "remarks must retain its third line"
        );
        assert!(!cut.fully_consumed);
        assert!(
            cut.consumed_height < MIN_TOP_KEEP_PX,
            "fixture must exercise the former content-only orphan rejection: {}",
            cut.consumed_height,
        );

        let visible_height = engine.row_cut_content_height(&table, 0, &[], &cut.end_cut, &styles);
        assert!(
            visible_height > cut.consumed_height,
            "visible fragment must include vertical padding: content={}, visible={visible_height}",
            cut.consumed_height,
        );
        assert!(
            !row_split_meets_min_top_keep(cut.consumed_height, visible_height, false),
            "ordinary RowBreak tables must keep the content-only orphan guard",
        );
        assert!(
            row_split_meets_min_top_keep(cut.consumed_height, visible_height, true),
            "the strict #2439 padded cut must remain on the current page: {visible_height}",
        );
    }

    #[test]
    fn issue2439_partial_rowbreak_repeats_outer_margins_without_repeating_vertical_offset() {
        let table = Table {
            page_break: TablePageBreak::RowBreak,
            outer_margin_top: 283,
            outer_margin_bottom: 283,
            common: CommonObjAttr {
                treat_as_char: false,
                text_wrap: TextWrap::TopAndBottom,
                vert_rel_to: VertRelTo::Para,
                vertical_offset: 399,
                ..Default::default()
            },
            ..Default::default()
        };
        let outer = hwpunit_to_px(283, DEFAULT_DPI);
        let first_host_before = outer + 2.0;
        let first = partial_rowbreak_fragment_spacing_px(
            &table,
            first_host_before,
            false,
            true,
            false,
            DEFAULT_DPI,
        );
        let continuation = partial_rowbreak_fragment_spacing_px(
            &table,
            first_host_before,
            true,
            true,
            false,
            DEFAULT_DPI,
        );

        assert!((first.0 - first_host_before).abs() < 0.01);
        assert!((first.1 - outer).abs() < 0.01);
        assert!((continuation.0 - outer).abs() < 0.01);
        assert!((continuation.1 - outer).abs() < 0.01);
        assert_eq!(table.common.vertical_offset, 399);
        // The helper deliberately excludes vertical_offset; the caller applies it only when
        // `is_continuation == false`, preventing it from being repeated on later pages.

        let ungated = partial_rowbreak_fragment_spacing_px(
            &table,
            first_host_before,
            true,
            false,
            false,
            DEFAULT_DPI,
        );
        assert_eq!(ungated, (0.0, 0.0));
    }

    fn para_at_vpos(vpos: i32) -> Paragraph {
        Paragraph {
            line_segs: vec![LineSeg {
                vertical_pos: vpos,
                line_height: 1300,
                text_height: 1300,
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    #[test]
    fn issue2424_table_continuation_cursor_preserves_break_state() {
        let mut cursor = TableContinuationCursor::default();
        assert_eq!(cursor.row, 0);
        assert!(!cursor.is_continuation);
        assert_eq!(cursor.fragments_emitted, 0);

        cursor.advance(3, None, vec![4, 7], true);
        assert_eq!(
            cursor.row, 2,
            "ordinary intra-row split resumes at end_row-1"
        );
        assert_eq!(cursor.start_cut, vec![4, 7]);
        assert!(!cursor.start_cut_is_block);
        assert!(cursor.is_continuation);
        assert_eq!(cursor.fragments_emitted, 1);

        cursor.advance(3, Some(1), vec![8], true);
        assert_eq!(cursor.row, 1, "rowspan block split resumes at block start");
        assert_eq!(cursor.start_cut, vec![8]);
        assert!(cursor.start_cut_is_block);
        assert_eq!(cursor.fragments_emitted, 2);

        cursor.advance(3, None, vec![99], false);
        assert_eq!(cursor.row, 3, "whole-row consumption resumes at end_row");
        assert!(cursor.start_cut.is_empty());
        assert!(!cursor.start_cut_is_block);
        assert_eq!(cursor.fragments_emitted, 3);

        cursor.skip_consumed_row();
        assert_eq!(cursor.row, 4);
        assert_eq!(cursor.fragments_emitted, 3, "skipping emits no fragment");
        cursor.finish(9, true);
        assert_eq!(cursor.row, 9);
        assert!(cursor.start_cut.is_empty());
        assert_eq!(cursor.fragments_emitted, 4);
    }

    #[test]
    fn issue2424_block_table_context_owns_step_lifecycle() {
        let prepared = BlockTableContinuationPreparedState {
            computed_host_tail: None,
            first_anchor_offset_consumed: false,
            opening_rowspan_block_cuts_after_first_row: false,
            host_placement: None,
            empty_opening_row_frame: None,
            source_text_first_frame_height: None,
            source_terminal_suffix_start: None,
            source_single_cell_row_frames: None,
            host_frame: (0, 0, 0.0_f64.to_bits()),
            row_count: 3,
            cell_spacing: 0.0,
            can_intra_split: true,
            base_available: 100.0,
            table_available: 100.0,
            layout_engine: crate::renderer::layout::LayoutEngine::new(DEFAULT_DPI),
            rowspan_touched: vec![false; 3],
            cut_row_heights: vec![10.0; 3],
            whole_row_fit_heights: vec![10.0; 3],
            stored_rewinding_rowbreak_uses_painted_row_footprint: false,
            first_fragment_painted_row_footer_guard: 0.0,
            caption_is_top: false,
            caption_overhead: 0.0,
            total_rows_height: 30.0,
            total_footnote_height: 0.0,
            queue_table_footnotes: false,
            table_footnotes: Vec::new(),
            host_spacing_total: 0.0,
            host_spacing_before: 0.0,
            host_spacing_after_only: 0.0,
            terminal_outer_bottom_flow: 0.0,
            terminal_host_spacing: 0.0,
            strict_following_plain_text_fit: false,
            budget_para_start_height: 0.0,
            first_fragment_actual_footnote_boundary: None,
            source_next_positive_rewind: false,
            first_fragment_saved_offset: None,
            source_cellbreak_row_end: None,
            next_para_stored_top: None,
            relax_terminal_table_footnote_fit: false,
            host_line_trails_table: false,
        };
        let flow_layout =
            PageLayoutInfo::from_page_def(&a4_page_def(), &ColumnDef::default(), DEFAULT_DPI);
        let flow_state = TypesetState::new(flow_layout, 1, 0, 0.0, 0.0, Default::default());
        let mut context = BlockTableContinuationContext::new(0, prepared, flow_state);
        assert_eq!(context.fragment_budget, 1, "zero budget clamps to one");
        assert_eq!(context.steps_completed, 0);
        assert!(!context.is_complete());

        context.step(|_, _, cursor| {
            cursor.advance(2, None, vec![4], true);
            TableContinuationIteration::Emitted
        });
        assert_eq!(context.steps_completed, 1);
        assert_eq!(context.cursor.fragments_emitted, 1);
        assert!(!context.is_complete());

        context.step(|_, _, cursor| {
            cursor.finish(3, true);
            TableContinuationIteration::Complete
        });
        assert!(context.is_complete());
        assert_eq!(context.steps_completed, 2);
        assert_eq!(context.cursor.fragments_emitted, 2);
        let flow_state = context.into_flow_state();
        assert_eq!(flow_state.section_index, 0);
    }

    /// [Task #1749] 저장 flow 페이지-마지막 인코딩 판정
    #[test]
    fn test_saved_flow_marks_page_last() {
        // (a) 다음 실줄 없음(문서 끝) — 신뢰 (fe6de3ef 합성 테스트 보호 케이스)
        let doc_end = vec![para_at_vpos(0), para_at_vpos(72626)];
        assert!(saved_flow_marks_page_last(&doc_end, 1));

        // (b) 다음 줄 vpos 리셋(새 쪽) — 신뢰
        let reset = vec![para_at_vpos(72626), para_at_vpos(700)];
        assert!(saved_flow_marks_page_last(&reset, 0));

        // (c) 누적좌표(다음 vpos 증가 지속) — 불신 (36371084 pi18→pi19)
        let cumulative = vec![para_at_vpos(72626), para_at_vpos(74902)];
        assert!(!saved_flow_marks_page_last(&cumulative, 0));

        // (d) 빈 line_segs 문단 건너뛰고 다음 실줄로 판정
        let with_empty = vec![
            para_at_vpos(72626),
            Paragraph::default(),
            para_at_vpos(74902),
        ];
        assert!(!saved_flow_marks_page_last(&with_empty, 0));

        // (e) 누적좌표라도 다음 문단이 명시적 쪽나누기면 페이지-마지막 증거로 신뢰
        //     (36375752 pi26→pi27 [쪽나누기]: vpos 137484→140204 리셋 없음)
        let mut page_break_next = para_at_vpos(140204);
        page_break_next.column_type = ColumnBreakType::Page;
        let cumulative_with_break = vec![para_at_vpos(137484), page_break_next];
        assert!(saved_flow_marks_page_last(&cumulative_with_break, 0));
    }

    fn page_with_items(items: Vec<PageItem>) -> PageContent {
        PageContent {
            page_index: 0,
            page_number: 0,
            page_number_restarted: false,
            section_index: 0,
            layout: PageLayoutInfo::from_page_def(
                &a4_page_def(),
                &ColumnDef::default(),
                DEFAULT_DPI,
            ),
            column_contents: vec![ColumnContent {
                paragraph_origins: Default::default(),
                computed_paragraphs: Default::default(),
                column_index: 0,
                start_height: 0.0,
                endnote_flow: false,
                items,
                zone_layout: None,
                zone_y_offset: 0.0,
                wrap_around_paras: Vec::new(),
                used_height: 0.0,
                wrap_anchors: std::collections::HashMap::new(),
                overlay_continuations: Vec::new(),
                overlay_cuts: Vec::new(),
                inline_placements: Default::default(),
                inline_flow_plans: Default::default(),
                stored_paragraph_flow_ends: Default::default(),
                host_compositions: Default::default(),
                stored_column_top_spacings: Default::default(),
                paragraph_float_placements: Default::default(),
                float_pushed_line_spacings: Default::default(),
                page_band_flow_starts: Default::default(),
            }],
            active_header: None,
            active_footer: None,
            page_number_pos: None,
            page_hide: None,
            footnotes: Vec::new(),
            active_master_page: None,
            extra_master_pages: Vec::new(),
            ladder_band_tables: Vec::new(),
        }
    }

    /// 두 PaginationResult의 페이지 수와 각 페이지의 항목 수가 동일한지 비교
    fn assert_pagination_match(old: &PaginationResult, new: &PaginationResult, label: &str) {
        assert_eq!(
            old.pages.len(),
            new.pages.len(),
            "{}: 페이지 수 불일치 (old={}, new={})",
            label,
            old.pages.len(),
            new.pages.len(),
        );

        for (pi, (old_page, new_page)) in old.pages.iter().zip(new.pages.iter()).enumerate() {
            assert_eq!(
                old_page.column_contents.len(),
                new_page.column_contents.len(),
                "{}: p{} 단 수 불일치",
                label,
                pi,
            );

            for (ci, (old_col, new_col)) in old_page
                .column_contents
                .iter()
                .zip(new_page.column_contents.iter())
                .enumerate()
            {
                assert_eq!(
                    old_col.items.len(),
                    new_col.items.len(),
                    "{}: p{} col{} 항목 수 불일치 (old={}, new={})",
                    label,
                    pi,
                    ci,
                    old_col.items.len(),
                    new_col.items.len(),
                );
            }
        }
    }

    #[test]
    fn test_typeset_engine_creation() {
        let engine = TypesetEngine::new(96.0);
        assert_eq!(engine.dpi, 96.0);
    }

    #[test]
    fn test_typeset_empty_paragraphs() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &[],
            &composed,
            &styles,
            &a4_page_def(),
            &ColumnDef::default(),
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 1, "빈 문서도 최소 1페이지");
    }

    #[test]
    fn table_continuation_does_not_reapply_page_hide() {
        let hide = crate::model::control::PageHide {
            hide_master_page: true,
            hide_page_num: true,
            ..Default::default()
        };
        let mut pages = vec![
            page_with_items(vec![PageItem::PartialTable {
                para_index: 7,
                control_index: 0,
                start_row: 0,
                end_row: 2,
                is_continuation: false,
                start_cut: Vec::new(),
                end_cut: Vec::new(),
                is_block_split: false,
                start_cut_is_block: false,
                row_cursor_is_nested: false,
                end_row_height_override: None,
                start_row_height_override: None,
                straddle_row_relief: Vec::new(),
                straddle_page_bands: Vec::new(),
                fragment_row_heights: None,
                fragment_block_frames: Vec::new(),
                end_row_owns_stored_frame: false,
            }]),
            page_with_items(vec![PageItem::PartialTable {
                para_index: 7,
                control_index: 0,
                start_row: 2,
                end_row: 4,
                is_continuation: true,
                start_cut: Vec::new(),
                end_cut: Vec::new(),
                is_block_split: false,
                start_cut_is_block: false,
                row_cursor_is_nested: false,
                end_row_height_override: None,
                start_row_height_override: None,
                straddle_row_relief: Vec::new(),
                straddle_page_bands: Vec::new(),
                fragment_row_heights: None,
                fragment_block_frames: Vec::new(),
                end_row_owns_stored_frame: false,
            }]),
        ];

        let mut paragraphs = vec![Paragraph::default(); 8];
        paragraphs[7].controls = vec![Control::Table(Box::default()), Control::PageHide(hide)];
        state::finalize::finalize_pages(&mut pages, &[], &None, &paragraphs);

        assert!(pages[0].page_hide.is_some());
        assert!(pages[1].page_hide.is_none());
    }

    #[test]
    fn footnote_area_reserve_uses_section_shape_metrics() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let shape = FootnoteShape {
            separator_margin_top: 1000,
            note_spacing: 700,
            raw_unknown: 900,
            separator_line_width: 4,
            ..Default::default()
        };
        let note1 = Paragraph {
            text: "첫 각주".to_string(),
            line_segs: vec![LineSeg {
                line_height: 400,
                ..Default::default()
            }],
            ..Default::default()
        };
        let note2 = Paragraph {
            text: "둘째 각주".to_string(),
            line_segs: vec![LineSeg {
                line_height: 600,
                ..Default::default()
            }],
            ..Default::default()
        };
        let paras = vec![Paragraph {
            text: "본문".to_string(),
            line_segs: vec![LineSeg {
                line_height: 400,
                ..Default::default()
            }],
            controls: vec![
                Control::Footnote(Box::new(crate::model::footnote::Footnote {
                    number: 1,
                    paragraphs: vec![note1],
                    ..Default::default()
                })),
                Control::Footnote(Box::new(crate::model::footnote::Footnote {
                    number: 2,
                    paragraphs: vec![note2],
                    ..Default::default()
                })),
            ],
            ..Default::default()
        }];
        let composed: Vec<ComposedParagraph> = paras
            .iter()
            .map(crate::renderer::composer::compose_paragraph)
            .collect();

        let run_with_shape = |shape: &FootnoteShape| {
            engine.typeset_section_with_variant(
                &paras,
                &composed,
                &styles,
                &a4_page_def(),
                &ColumnDef::default(),
                0,
                &[],
                false,
                Default::default(),
                false,
                false,
                Some(shape),
                None,
                &std::collections::HashSet::new(),
                EndnoteDeferral::None,
            )
        };

        let result = run_with_shape(&shape);
        let without_margins = run_with_shape(&FootnoteShape {
            separator_margin_top: 0,
            note_spacing: 0,
            raw_unknown: 0,
            ..shape.clone()
        });
        // 폭 0인 합성 줄은 재조판된다. LH 400/600을 실제 텍스트 높이로
        // 고정하지 않고 같은 두 각주의 예약 높이에서 구역 여백의 몫을 확인한다.
        // 구분선 위·아래 여백과 각주 사이 여백(두 각주 사이 한 번)만 달라야 한다.
        let expected_delta = hwpunit_to_px(1000 + 700 + 900, DEFAULT_DPI);
        let page = result.pages.first().expect("page");
        let control = without_margins.pages.first().expect("대조군 page");
        assert_eq!(page.footnotes.len(), 2);
        assert_eq!(control.footnotes.len(), 2);
        assert_eq!(result.pages.len(), without_margins.pages.len());
        assert!(
            (page.layout.footnote_area.height
                - control.layout.footnote_area.height
                - expected_delta)
                .abs()
                < 0.01
        );
    }

    #[test]
    fn test_typeset_single_paragraph() {
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let paras = vec![make_paragraph_with_height(400)];
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        let (old_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let new_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        assert_pagination_match(&old_result, &new_result, "single_paragraph");
    }

    #[test]
    fn test_typeset_page_overflow() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        // 빈 문단만으로는 마지막 blank-only page 제거 경로를 검증하게 된다. 이
        // 테스트의 계약은 overflow 중 가시 문단의 배치이므로, 실제 내용도 넣는다.
        let mut paras: Vec<Paragraph> =
            (0..100).map(|_| make_paragraph_with_height(2000)).collect();
        for (idx, para) in paras.iter_mut().enumerate() {
            para.text = format!("paragraph {idx}");
        }
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        let new_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        // `Paginator`의 옛 measured-height 근사는 독립적인 oracle이 아니다. 이
        // synthetic case는 가시 문단 100개의 전량 보존과 body-fit(4쪽)을 직접
        // 고정한다.
        assert_eq!(
            new_result.pages.len(),
            4,
            "100개 2000-HWPUNIT 문단은 A4 4쪽"
        );
        let placed: Vec<_> = new_result
            .pages
            .iter()
            .flat_map(|page| page.column_contents.iter())
            .flat_map(|column| column.items.iter())
            .map(PageItem::para_index)
            .collect();
        assert_eq!(
            placed,
            (0..100).collect::<Vec<_>>(),
            "문단 손실·중복 없이 배치"
        );
    }

    #[test]
    fn saved_single_line_at_body_bottom_stays_on_current_page() {
        let engine = TypesetEngine::with_default_dpi();
        let mut styles = ResolvedStyleSet::default();
        styles
            .para_styles
            .push(crate::renderer::style_resolver::ResolvedParaStyle {
                spacing_before: 9.3,
                ..Default::default()
            });
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let line_height = 1200;
        let line_spacing = 840;
        let spacing_before_hu = crate::renderer::px_to_hwpunit(9.3, DEFAULT_DPI);
        let lead_height = body_height_hu - line_height;
        let lead_measured_height = lead_height - spacing_before_hu + 600;
        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: lead_measured_height,
                    text_height: lead_measured_height,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                para_shape_id: 0,
                text: "tail".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: lead_height,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 1);
        assert_eq!(result.pages[0].column_contents[0].items.len(), 2);
    }

    #[test]
    fn two_line_tail_before_vpos_reset_stays_on_current_page_when_visible_bottom_fits() {
        let engine = TypesetEngine::with_default_dpi();
        let mut styles = ResolvedStyleSet::default();
        styles
            .para_styles
            .push(crate::renderer::style_resolver::ResolvedParaStyle::default());
        styles
            .para_styles
            .push(crate::renderer::style_resolver::ResolvedParaStyle {
                spacing_before: hwpunit_to_px(2400, DEFAULT_DPI),
                spacing_after: hwpunit_to_px(1400, DEFAULT_DPI),
                ..Default::default()
            });

        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let line_height = 1200;
        let line_spacing = 840;
        let first_vpos = body_height_hu - 3740;
        let lead_height = first_vpos - 2400;

        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: lead_height,
                    text_height: lead_height,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                para_shape_id: 1,
                text: "line one\nline two".to_string(),
                line_segs: vec![
                    LineSeg {
                        vertical_pos: first_vpos,
                        line_height,
                        text_height: line_height,
                        line_spacing,
                        ..Default::default()
                    },
                    LineSeg {
                        vertical_pos: first_vpos + line_height + line_spacing,
                        line_height,
                        text_height: line_height,
                        line_spacing,
                        text_start: 9,
                        ..Default::default()
                    },
                ],
                ..Default::default()
            },
            Paragraph {
                text: "next page".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height,
                    text_height: line_height,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 2);
        assert!(matches!(
            result.pages[0].column_contents[0].items.as_slice(),
            [
                PageItem::FullParagraph { para_index: 0 },
                PageItem::FullParagraph { para_index: 1 }
            ]
        ));
        assert!(matches!(
            result.pages[1].column_contents[0].items.as_slice(),
            [PageItem::FullParagraph { para_index: 2 }]
        ));
    }

    #[test]
    fn multiline_saved_vpos_tail_does_not_split_to_near_empty_page() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let line_height = 1200;
        let line_spacing = 720;
        let first_vpos = body_height_hu - (line_height + line_spacing) * 3 - line_height;
        let lead_height = first_vpos + line_height;

        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: lead_height,
                    text_height: lead_height,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                text: "tail one\ntail two\ntail three\ntail four".to_string(),
                line_segs: (0..4)
                    .map(|line_idx| LineSeg {
                        vertical_pos: first_vpos + (line_height + line_spacing) * line_idx,
                        line_height,
                        text_height: line_height,
                        line_spacing,
                        text_start: line_idx as u32 * 9,
                        ..Default::default()
                    })
                    .collect(),
                ..Default::default()
            },
            Paragraph {
                text: "next page".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 2);
        assert!(matches!(
            result.pages[0].column_contents[0].items.as_slice(),
            [
                PageItem::FullParagraph { para_index: 0 },
                PageItem::FullParagraph { para_index: 1 }
            ]
        ));
        assert!(matches!(
            result.pages[1].column_contents[0].items.as_slice(),
            [PageItem::FullParagraph { para_index: 2 }]
        ));
    }

    #[test]
    fn page_bottom_empty_paragraph_before_vpos_reset_does_not_create_blank_page() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let line_height = 1000;
        let line_spacing = 400;

        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: body_height_hu - 100,
                    text_height: body_height_hu - 100,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                line_segs: vec![LineSeg {
                    vertical_pos: body_height_hu - 1200,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                text: "next page".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 2);
        assert!(result.hidden_empty_paras.contains(&1));
        let has_empty_only_page = result.pages.iter().any(|page| {
            page.column_contents.iter().any(|col| {
                matches!(
                    col.items.as_slice(),
                    [PageItem::FullParagraph { para_index: 1 }]
                )
            })
        });
        assert!(!has_empty_only_page);
        assert!(matches!(
            result.pages[1].column_contents[0].items.as_slice(),
            [PageItem::FullParagraph { para_index: 2 }]
        ));
    }

    #[test]
    fn page_bottom_empty_run_before_vpos_reset_does_not_create_blank_page() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let line_height = 1200;
        let line_spacing = 720;

        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: body_height_hu - 5000,
                    text_height: body_height_hu - 5000,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                line_segs: vec![LineSeg {
                    vertical_pos: body_height_hu - 3800,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                line_segs: vec![LineSeg {
                    vertical_pos: body_height_hu - 1880,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                text: "next page".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height,
                    text_height: line_height,
                    line_spacing,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 2);
        assert!(result.hidden_empty_paras.contains(&1));
        assert!(result.hidden_empty_paras.contains(&2));
        let has_empty_only_page = result.pages.iter().any(|page| {
            page.column_contents.iter().any(|col| {
                matches!(
                    col.items.as_slice(),
                    [PageItem::FullParagraph { para_index: 1 }]
                        | [PageItem::FullParagraph { para_index: 2 }]
                        | [
                            PageItem::FullParagraph { para_index: 1 },
                            PageItem::FullParagraph { para_index: 2 }
                        ]
                )
            })
        });
        assert!(!has_empty_only_page);
        assert!(matches!(
            result.pages[1].column_contents[0].items.as_slice(),
            [PageItem::FullParagraph { para_index: 3 }]
        ));
    }

    #[test]
    fn saved_tac_table_line_at_body_bottom_stays_on_current_page() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let layout = PageLayoutInfo::from_page_def(&page_def, &col_def, DEFAULT_DPI);
        let body_height_hu =
            crate::renderer::px_to_hwpunit(layout.available_body_height(), DEFAULT_DPI);
        let table_height = 10_072;
        let table_vpos = body_height_hu - table_height;
        let lead_height = table_vpos + 900;
        let paras = vec![
            Paragraph {
                text: "lead".to_string(),
                line_segs: vec![LineSeg {
                    vertical_pos: 0,
                    line_height: lead_height,
                    text_height: lead_height,
                    ..Default::default()
                }],
                ..Default::default()
            },
            Paragraph {
                controls: vec![Control::Table(Box::new(crate::model::table::Table {
                    attr: 1,
                    row_count: 3,
                    col_count: 3,
                    common: crate::model::shape::CommonObjAttr {
                        treat_as_char: true,
                        text_wrap: crate::model::shape::TextWrap::TopAndBottom,
                        height: table_height as u32,
                        ..Default::default()
                    },
                    ..Default::default()
                }))],
                line_segs: vec![LineSeg {
                    vertical_pos: table_vpos,
                    line_height: table_height,
                    text_height: table_height,
                    line_spacing: 120,
                    ..Default::default()
                }],
                ..Default::default()
            },
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();

        let result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(result.pages.len(), 1);
        assert!(matches!(
            result.pages[0].column_contents[0].items.as_slice(),
            [
                PageItem::FullParagraph { para_index: 0 },
                PageItem::Table { para_index: 1, .. }
            ]
        ));
    }

    /// [Task #1363 v3 Stage 2] scratch 측정 부작용 격리 회귀 가드.
    ///
    /// `measure_endnote_para_advance` 는 매 호출 `LayoutEngine::new()` 로 독립 인스턴스를
    /// 쓰므로 (a) 양수·유한, (b) 동일 엔진 반복 호출에 결정적(호출 간 상태 무누적),
    /// (c) 독립 `TypesetEngine` 인스턴스 간 동일(전역/공유 가변 상태 누수 없음)이어야 한다.
    /// scratch 의 numbering/overflow/last_item_content_bottom 변이가 측정에만 머무름을 실증.
    #[test]
    fn test_measure_endnote_advance_side_effect_free() {
        use crate::renderer::composer::compose_paragraph;

        let para = Paragraph {
            text: "각주 측정 격리 회귀 가드 문장".to_string(),
            line_segs: vec![LineSeg {
                line_height: 1000,
                baseline_distance: 850,
                ..Default::default()
            }],
            ..Default::default()
        };
        let composed = compose_paragraph(&para);
        let styles = ResolvedStyleSet::default();
        let item = PageItem::FullParagraph { para_index: 900 };
        let (en_col_w, available, y_start) = (280.0_f64, 900.0_f64, 100.0_f64);

        let engine = TypesetEngine::new(96.0);
        let first = engine.measure_endnote_para_advance(
            &para, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
        );

        // (a) 양수·유한 — 실제 텍스트 para 는 advance 를 만든다.
        assert!(
            first.is_finite() && first > 0.0,
            "advance must be positive finite: {first}",
        );

        // (b) 동일 엔진 반복 호출 → 결정적 (scratch 호출 간 상태 무누적).
        for _ in 0..5 {
            let v = engine.measure_endnote_para_advance(
                &para, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
            );
            assert_eq!(v, first, "repeat call drifted — scratch 상태 누적 누수");
        }

        // (c) 독립 TypesetEngine 인스턴스 → 동일 (전역 가변 상태 누수 없음).
        let engine2 = TypesetEngine::new(96.0);
        let other = engine2.measure_endnote_para_advance(
            &para, &composed, &styles, en_col_w, available, y_start, &item, 0, 900,
        );
        assert_eq!(other, first, "independent engine differs — 전역 상태 누수");
    }

    #[test]
    fn test_typeset_line_split() {
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();

        // 여러 줄이 있는 큰 문단 (페이지 경계에서 줄 단위 분할)
        let paras = vec![Paragraph {
            line_segs: (0..50)
                .map(|_| LineSeg {
                    line_height: 1800,
                    line_spacing: 200,
                    ..Default::default()
                })
                .collect(),
            ..Default::default()
        }];
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        let (old_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let new_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        assert_pagination_match(&old_result, &new_result, "line_split");
    }

    #[test]
    fn test_typeset_mixed_paragraphs() {
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();

        // 다양한 높이의 문단 혼합
        let paras: Vec<Paragraph> = vec![
            make_paragraph_with_height(400),
            make_paragraph_with_height(10000), // 큰 문단
            make_paragraph_with_height(400),
            make_paragraph_with_height(800),
            make_paragraph_with_height(20000), // 매우 큰 문단
            make_paragraph_with_height(400),
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        let (old_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let new_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        assert_pagination_match(&old_result, &new_result, "mixed_paragraphs");
    }

    #[test]
    fn test_typeset_page_break() {
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();

        // 강제 쪽 나누기가 있는 문단
        let paras = vec![
            make_paragraph_with_height(400),
            {
                let mut p = make_paragraph_with_height(400);
                p.column_type = ColumnBreakType::Page;
                p
            },
            make_paragraph_with_height(400),
        ];
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        let (old_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let new_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        assert_pagination_match(&old_result, &new_result, "page_break");
        assert_eq!(new_result.pages.len(), 2, "쪽 나누기로 2페이지");
    }

    // [Task #1046] 사후 reflow force-break hint 메커니즘 검증.
    #[test]
    fn test_typeset_force_break_before_hint() {
        let engine = TypesetEngine::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        // 한 페이지에 충분히 들어가는 3개 문단
        let mut paras = vec![
            make_paragraph_with_height(400),
            make_paragraph_with_height(400),
            make_paragraph_with_height(400),
        ];
        for (idx, para) in paras.iter_mut().enumerate() {
            para.text = format!("paragraph {idx}");
        }
        let composed: Vec<ComposedParagraph> = Vec::new();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();

        // hint 없음 → 1페이지
        let baseline = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &std::collections::HashSet::new(),
        );
        assert_eq!(baseline.pages.len(), 1, "hint 없으면 3문단 모두 1페이지");

        // para_idx=1 에 force-break hint → para 1 이 2페이지에서 시작
        let mut hint = std::collections::HashSet::new();
        hint.insert(1usize);
        let reflowed = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &[],
            false,
            &hint,
        );
        assert_eq!(reflowed.pages.len(), 2, "para1 force-break 로 2페이지");
        let page0_paras: Vec<usize> = reflowed.pages[0]
            .column_contents
            .iter()
            .flat_map(|cc| cc.items.iter().map(|it| it.para_index()))
            .collect();
        let page1_paras: Vec<usize> = reflowed.pages[1]
            .column_contents
            .iter()
            .flat_map(|cc| cc.items.iter().map(|it| it.para_index()))
            .collect();
        assert_eq!(page0_paras, vec![0], "1페이지엔 para0 만");
        assert_eq!(page1_paras, vec![1, 2], "2페이지엔 para1,2");
    }

    // ========================================================
    // 실제 HWP 파일 비교 테스트
    // ========================================================

    /// 실제 HWP 파일로 기존 Paginator와 TypesetEngine 결과 비교
    fn compare_with_hwp_file(path: &str) {
        let data = match std::fs::read(path) {
            Ok(d) => d,
            Err(_) => {
                eprintln!("skip: {} not found", path);
                return;
            }
        };
        let doc = match crate::document_core::DocumentCore::from_bytes(&data) {
            Ok(d) => d,
            Err(e) => {
                eprintln!("skip: {} parse error: {}", path, e);
                return;
            }
        };

        let engine = TypesetEngine::with_default_dpi();

        for (sec_idx, section) in doc.document.sections.iter().enumerate() {
            let composed = &doc.composed[sec_idx];
            let measured_tables = &doc.measured_tables[sec_idx];
            let column_def =
                crate::document_core::DocumentCore::find_initial_column_def(&section.paragraphs);

            // 구역에 표가 포함되어 있는지 확인
            let has_tables = section
                .paragraphs
                .iter()
                .any(|p| p.controls.iter().any(|c| matches!(c, Control::Table(_))));

            let new_result = engine.typeset_section(
                &section.paragraphs,
                composed,
                &doc.styles,
                &section.section_def.page_def,
                &column_def,
                sec_idx,
                measured_tables,
                section.section_def.hide_empty_line,
                &std::collections::HashSet::new(),
            );

            let old_result = &doc.pagination[sec_idx];
            let label = format!("{} sec{}", path, sec_idx);

            if has_tables {
                // 표가 포함된 구역: Phase 2 전환 전까지 차이 허용 (경고만 출력)
                if old_result.pages.len() != new_result.pages.len() {
                    eprintln!(
                        "WARN {}: 표 포함 구역 페이지 수 차이 (old={}, new={}) — Phase 2에서 해결",
                        label,
                        old_result.pages.len(),
                        new_result.pages.len(),
                    );
                }
            } else {
                // 비-표 구역: 완전 일치 필수
                assert_eq!(
                    old_result.pages.len(),
                    new_result.pages.len(),
                    "{}: 페이지 수 불일치 (old={}, new={})",
                    label,
                    old_result.pages.len(),
                    new_result.pages.len(),
                );

                for (pi, (old_page, new_page)) in old_result
                    .pages
                    .iter()
                    .zip(new_result.pages.iter())
                    .enumerate()
                {
                    assert_eq!(
                        old_page.column_contents.len(),
                        new_page.column_contents.len(),
                        "{}: p{} 단 수 불일치",
                        label,
                        pi,
                    );
                }
            }
        }
    }

    #[test]
    fn test_typeset_vs_paginator_p222() {
        // p222.hwp sec2는 표가 많아 Phase 2 전환 전까지 차이 발생 가능
        // Phase 1에서는 비-표 문단만 검증
        compare_with_hwp_file("samples/p222.hwp");
    }

    #[test]
    fn test_typeset_vs_paginator_hongbo() {
        compare_with_hwp_file("samples/20250130-hongbo.hwp");
    }

    #[test]
    fn test_typeset_vs_paginator_biz_plan() {
        compare_with_hwp_file("samples/biz_plan.hwp");
    }

    /// Issue #703: BehindText/InFrontOfText 표는 본문 흐름에서 제외되어야 한다.
    ///
    /// 글뒤로 (BehindText) / 글앞으로 (InFrontOfText) 표는 시각적으로 본문 텍스트 뒤/앞에
    /// 절대 좌표로 배치되는 데코레이션 (워터마크/배경 등) 이며, 본문 흐름의 vertical advance 에
    /// 영향을 주지 않는다. `pagination/engine.rs:976-981` 와 동일 시멘틱.
    ///
    /// 결함 메커니즘: typeset_block_table → place_table_with_text → `cur_h += table_total_height`
    /// (line 1594) 가 BehindText/InFrontOfText 표에 대해서도 적용되어 본문 흐름 누적이 발생.
    ///
    /// 본 테스트는 BIG BehindText 표 (≈300 mm 높이) 를 1 페이지 본문 안에 넣어두고 후속
    /// paragraph 가 동일 페이지에 들어감을 검증한다. 결함 시 BehindText 표의 거대 height 가
    /// cur_h 에 가산되어 후속 paragraph 가 다음 페이지로 밀림.
    #[test]
    fn test_typeset_703_behind_text_table_no_flow_advance() {
        use crate::model::shape::TextWrap;
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let composed: Vec<ComposedParagraph> = Vec::new();

        // BehindText 1×1 표: 본문 높이의 약 80% 차지 (60000 HU ≈ 800 px @96dpi).
        // BehindText 는 데코레이션이므로 본문 흐름 누적 0 이어야 정상.
        // 결함 시 cur_h 에 800 px 가산 → 후속 1 단락도 fit 실패 → 페이지 분할.
        let mut table = crate::model::table::Table {
            row_count: 1,
            col_count: 1,
            cells: vec![crate::model::table::Cell {
                col: 0,
                row: 0,
                col_span: 1,
                row_span: 1,
                width: 51974,
                height: 60000,
                paragraphs: vec![Paragraph::default()],
                ..Default::default()
            }],
            ..Default::default()
        };
        table.common.text_wrap = TextWrap::BehindText;
        table.common.treat_as_char = false;
        table.common.width = 51974;
        table.common.height = 60000; // ≈800 px @96dpi — 본문 80% 점유 (결함 시 가산되는 양)

        let host_para = Paragraph {
            line_segs: vec![LineSeg {
                line_height: 1000,
                line_spacing: 600,
                ..Default::default()
            }],
            controls: vec![crate::model::control::Control::Table(Box::new(table))],
            ..Default::default()
        };

        // 후속 5 단락 — 본문 정상 흐름이면 호스트(21px) + 5 × 13px = 86 px (1 페이지 여유)
        // 결함 시 호스트(21+800=821px) + 첫 단락(13px) = 834 px 도 fit, 더 추가 시 결국 분할
        // → 단순히 페이지 수 정확히 비교 필요.
        let mut paras = vec![host_para];
        for _ in 0..5 {
            paras.push(make_paragraph_with_height(1000));
        }

        let (paginator_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let typeset_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        // 검증 1: paginator (engine.rs reference) 는 1 페이지에 모두 배치
        assert_eq!(
            paginator_result.pages.len(),
            1,
            "[reference] BehindText 표 + 5 후속 paragraph 는 paginator 에서 1 페이지에 들어가야 함",
        );

        // 검증 2: typeset 결과도 1 페이지 (현재 결함 시 RED — typeset 이 BehindText 표 height 를 누적)
        assert_eq!(
            typeset_result.pages.len(),
            1,
            "[BUG #703] typeset 도 1 페이지여야 함. 결함 시 BehindText 표 height ≈800 px 가 \
             cur_h 에 가산되어 후속 paragraph 가 다음 페이지로 밀림 (RED)",
        );
    }

    /// Issue #1995: 한 문단에 근접-전면(near-full-page) non-TAC 이미지가 여러 장이면
    /// 각 이미지는 공존 불가하므로 각각 한 페이지에 단독 배치되어야 한다.
    ///
    /// 결함(수정 전): 임베드 매뉴얼을 페이지 이미지로 삽입한 문서(한 문단에 전면 이미지
    /// 수십~백장)에서 rhwp 가 전부 한 앵커에 스택 → 문서가 과소 페이지(예: rhwp 174 vs
    /// 한글 268). 수정: typeset 인라인 컨트롤 방출 시 각 전면 이미지를 force_new_page 로
    /// 개별 페이지에 배치.
    #[test]
    fn test_typeset_1995_multi_fullpage_images_split_pages() {
        use crate::model::shape::TextWrap;
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let composed: Vec<ComposedParagraph> = Vec::new();

        // 전면 non-TAC 이미지 3장 (각 60000 HU ≈ 800px, 본문 60%+ 점유, wrap=Square)
        let make_pic = || {
            let mut pic = crate::model::image::Picture::default();
            pic.common.treat_as_char = false;
            pic.common.text_wrap = TextWrap::Square;
            pic.common.width = 51974;
            pic.common.height = 60000;
            crate::model::control::Control::Picture(Box::new(pic))
        };
        let host_para = Paragraph {
            line_segs: vec![LineSeg {
                line_height: 1000,
                line_spacing: 600,
                ..Default::default()
            }],
            controls: vec![make_pic(), make_pic(), make_pic()],
            ..Default::default()
        };
        let paras = vec![host_para];

        let (_paginator_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let typeset_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        // 전면 이미지 3장 → 각각 한 페이지 (>= 3). 결함 시 1 페이지에 스택(RED).
        assert!(
            typeset_result.pages.len() >= 3,
            "[#1995] 전면 non-TAC 이미지 3장은 각각 한 페이지에 단독 배치되어야 함(>= 3 페이지). \
             실제 {} 페이지 — 미수정 시 한 앵커에 스택",
            typeset_result.pages.len(),
        );
    }

    /// #4770: 같은 앵커에 겹친 Square 전면 그림 무리라도, 저장 첫 줄이 그림 폭 이상
    /// 오른쪽에서 시작하면(cs ≥ 그림 폭 — 한글이 빈 줄을 그림 옆에 끼운 저장 흔적)
    /// 한글은 스택을 앵커 쪽에 남긴다. 낱장 분산(#1995)을 걸면 안 된다.
    ///
    /// HPV 코호트 s2/pi=1007 실측: 그림 24장(150×212mm) cs=42520=그림 폭·sw=3480,
    /// 한글 1쪽 ↔ 분산 시 24쪽(+24) — 이슈 #4770.
    #[test]
    fn test_typeset_4770_stored_line_beside_pile_keeps_stack_on_anchor_page() {
        use crate::model::shape::TextWrap;
        let engine = TypesetEngine::with_default_dpi();
        let paginator = Paginator::with_default_dpi();
        let styles = ResolvedStyleSet::default();
        let page_def = a4_page_def();
        let col_def = ColumnDef::default();
        let composed: Vec<ComposedParagraph> = Vec::new();

        // #1995 테스트와 같은 전면 그림 3장 — 유일한 차이는 저장 첫 줄의
        // column_start 가 그림 폭 이상(= 줄이 그림 옆에 끼임)이라는 것.
        let make_pic = || {
            let mut pic = crate::model::image::Picture::default();
            pic.common.treat_as_char = false;
            pic.common.text_wrap = TextWrap::Square;
            pic.common.width = 51974;
            pic.common.height = 60000;
            crate::model::control::Control::Picture(Box::new(pic))
        };
        let host_para = Paragraph {
            line_segs: vec![LineSeg {
                line_height: 1000,
                line_spacing: 600,
                column_start: 51974,
                segment_width: 3480,
                ..Default::default()
            }],
            controls: vec![make_pic(), make_pic(), make_pic()],
            ..Default::default()
        };
        let paras = vec![host_para];

        let (_paginator_result, measured) =
            paginator.paginate(&paras, &composed, &styles, &page_def, &col_def, 0);
        let typeset_result = engine.typeset_section(
            &paras,
            &composed,
            &styles,
            &page_def,
            &col_def,
            0,
            &measured.tables,
            false,
            &std::collections::HashSet::new(),
        );

        assert_eq!(
            typeset_result.pages.len(),
            1,
            "[#4770] 저장 줄이 그림 옆에 끼인(cs ≥ 그림 폭) 스택은 앵커 쪽 1 페이지에 \
             남아야 함. 실제 {} 페이지 — 낱장 분산이 오발동",
            typeset_result.pages.len(),
        );
    }

    #[test]
    fn test_4770_anchor_pile_contract_requires_square_stack_and_page_bottom() {
        use crate::document_core::queries::rendering::body_pile_stays_on_anchor_page;
        use crate::model::page::PageAreas;
        use crate::model::shape::TextWrap;

        let page_def = a4_page_def();
        let body_area = PageAreas::from_page_def(&page_def).body_area;
        let make_para = |text_wrap| {
            let make_pic = || {
                let mut pic = crate::model::image::Picture::default();
                pic.common.treat_as_char = false;
                pic.common.text_wrap = text_wrap;
                pic.common.allow_overlap = false;
                pic.common.width = 51974;
                pic.common.height = 60000;
                crate::model::control::Control::Picture(Box::new(pic))
            };
            Paragraph {
                line_segs: vec![LineSeg {
                    vertical_pos: body_area.bottom - 60000,
                    column_start: 51974,
                    segment_width: 3480,
                    ..Default::default()
                }],
                controls: vec![make_pic(), make_pic(), make_pic()],
                ..Default::default()
            }
        };

        assert!(
            body_pile_stays_on_anchor_page(&make_para(TextWrap::Square), 30000, body_area.bottom),
            "페이지 상단 기준 vpos가 본문 하단에 정확히 닿는 Square 스택은 앵커 쪽에 남아야 함"
        );
        assert!(
            !body_pile_stays_on_anchor_page(
                &make_para(TextWrap::TopAndBottom),
                30000,
                body_area.bottom,
            ),
            "TopAndBottom 전면 그림은 cs/vpos가 같아도 #1995 낱장 배치를 억제하면 안 됨"
        );
    }

    /// #3821: page-tail Square 그림은 첫 reset 문단뿐 아니라 그림 높이 안의 연속
    /// guide/visible 문단까지 같은 narrow band를 유지해야 한다. 범위 밖 첫 문단은
    /// 즉시 끊어 다음 일반 본문으로 anchor가 새지 않아야 한다.
    #[test]
    fn issue_3821_square_picture_wrap_band_is_bounded_and_contiguous() {
        let seg = |vertical_pos, column_start, segment_width| LineSeg {
            vertical_pos,
            column_start,
            segment_width,
            ..Default::default()
        };
        let paragraphs = vec![
            // p1693 형상: 앞쪽 full-width tail 뒤에 vpos reset narrow line가 공존.
            Paragraph {
                line_segs: vec![seg(-2000, 0, 45352), seg(0, 0, 25139), seg(2000, 0, 25139)],
                ..Default::default()
            },
            // p1694..1696 형상: 빈 guide 문단도 이후 visible text까지 contract를 잇는다.
            Paragraph {
                line_segs: vec![seg(4000, 0, 25139)],
                ..Default::default()
            },
            Paragraph {
                line_segs: vec![seg(4600, 0, 25139)],
                ..Default::default()
            },
            Paragraph {
                line_segs: vec![seg(5200, 0, 25139)],
                ..Default::default()
            },
            // p1697 visible text의 마지막 줄 시작점.
            Paragraph {
                line_segs: vec![seg(21800, 0, 25139)],
                ..Default::default()
            },
            // p1698: 그림 실제 bottom(23231 HU) 밖 — 반드시 제외.
            Paragraph {
                line_segs: vec![seg(23800, 0, 25139)],
                ..Default::default()
            },
        ];

        assert_eq!(
            controls::deferred_picture::square_picture_wrap_band_target_paragraphs(
                &paragraphs,
                0,
                0,
                23231,
                0,
                25139,
            ),
            vec![0, 1, 2, 3, 4],
            "actual image band must include p1693..p1697 and stop before p1698",
        );
    }
}

/// [#9016] 글자 없는 문단에서 제목 차례 표시 줄이 표 소유 줄 앞에 저장돼 있으면 그 저장 전진(px).
///
/// 제목 차례 표시는 CTRL_HEADER 없이 8유닛 슬롯을 차지하는 인라인 제어라 `controls[]` 에 없고,
/// 한/글은 그 슬롯을 자기 줄(글자 높이 줄)로 쌓는다. 소유 줄까지의 저장 vpos 가 되감김 없이
/// 증가할 때만 같은 조각의 앞 줄로 본다. 재조판·편집된 줄은 저장 원점을 근거로 쓰지 않는다.
fn title_mark_prefix_advance(para: &Paragraph, ctrl_idx: usize, dpi: f64) -> Option<f64> {
    if !para.text.is_empty()
        || !para.title_marks.iter().any(|mark| mark.char_idx == 0)
        || para.stored_text_partition_is_dirty()
        || para.cell_format_vpos_dirty
    {
        return None;
    }
    let owner = crate::renderer::composer::control_slot_line_index(para, ctrl_idx)
        .filter(|&line| line > 0)?;
    let rows = para.line_segs.get(..=owner)?;
    if rows.iter().any(|seg| {
        is_synthetic_line_seg(seg)
            || seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
    }) || !rows
        .windows(2)
        .all(|pair| pair[1].vertical_pos > pair[0].vertical_pos)
    {
        return None;
    }
    Some(hwpunit_to_px(
        rows[owner].vertical_pos - rows[0].vertical_pos,
        dpi,
    ))
}