rhwp 0.9.0

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
//! [Task #1027 Stage C] 공유 측정 커서 (페이지네이터 ↔ 렌더러 y-advance 정합).
//!
//! 렌더러(`layout.rs build_single_column`)의 컬럼 단위 inter-item VPOS_CORR
//! 상태머신을 캡슐화한다. 한 컬럼을 흐르는 동안의 vpos 기준점(page_base/
//! lazy_base)과 직전 항목 추적 상태를 보유하며, 항목 사이의 vpos 보정(Stage A
//! `vpos_corrected_end_y` + Stage B `para_has_overlay_shape` 결합)을 적용한다.
//!
//! Stage C: 렌더러가 이 커서에 위임(무동작). Stage D 에서 페이지네이터(typeset)
//! 가 동일 커서로 height-only 패스를 수행하여 두 측정 공간을 일치시킨다.
//!
//! 보유 상태(렌더러 build_single_column 로컬과 1:1):
//! - `vpos_page_base` / `vpos_lazy_base`: vpos→y 변환 기준점 (#412).
//! - `prev_layout_para`: 직전에 배치한 문단 인덱스.
//! - `prev_item_was_partial_table`: 직전 항목이 분할 표였는지 (#991).
//!
//! 기하 상수: `dpi`, `col_area_y/height`, `col_anchor_y`.

#[path = "height_cursor_origin.rs"]
mod origin;
pub(crate) use origin::FlowOrigin;

use super::layout::{para_has_overlay_shape, vpos_corrected_end_y};
use super::style_resolver::ResolvedStyleSet;
use crate::model::control::Control;
use crate::model::paragraph::{LineSeg, Paragraph};
use crate::model::shape::{TextWrap, VertRelTo};
use crate::renderer::hwpunit_to_px;

/// A lower saved origin starts a different local ladder. Once its owner has
/// been placed, the preceding ladder cannot anchor the following paragraph.
pub(crate) fn paragraph_origin_rewinds(previous: &Paragraph, current: &Paragraph) -> bool {
    // 문단이 여러 쪽을 소유하면 첫 줄은 이미 지난 프레임에 속한다.
    // 실제로 끝낸 마지막 저장 프레임의 원점과 후속 문단을 비교한다.
    let previous_origin = previous
        .line_segs
        .windows(2)
        .rev()
        .find(|pair| pair[1].vertical_pos < pair[0].vertical_pos)
        .map(|pair| &pair[1])
        .or_else(|| previous.line_segs.first());
    previous_origin
        .zip(current.line_segs.first())
        .is_some_and(|(before, after)| after.vertical_pos < before.vertical_pos)
}

/// A rebuilt continuous ladder omits a source paragraph-before band. Such a
/// boundary cannot restore spacing removed from its predecessor's flow advance.
/// Pagination and paint must both keep the accepted flow origin at this boundary.
pub(crate) fn rebuilt_ladder_omits_spacing_before(
    previous: &Paragraph,
    current: &Paragraph,
    spacing_before: f64,
    dpi: f64,
) -> bool {
    let Some(last) = previous.line_segs.last() else {
        return false;
    };
    let Some(first) = current.line_segs.first() else {
        return false;
    };
    spacing_before > 0.0
        && last.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && first.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && i64::from(first.vertical_pos)
            == i64::from(last.vertical_pos)
                + i64::from(last.line_height)
                + i64::from(last.line_spacing)
        && !previous.stored_text_partition_is_dirty()
        && !previous.cell_format_vpos_dirty
        && !current.stored_text_partition_is_dirty()
        && !current.cell_format_vpos_dirty
        && previous
            .source_line_seg_vertical_pos
            .as_ref()
            .and_then(|v| v.last())
            .zip(
                current
                    .source_line_seg_vertical_pos
                    .as_ref()
                    .and_then(|v| v.first()),
            )
            .is_some_and(|(previous, next)| {
                i64::from(*next)
                    - i64::from(*previous)
                    - i64::from(last.line_height)
                    - i64::from(last.line_spacing)
                    == (spacing_before * 7200.0 / dpi).round() as i64
            })
}

/// [#7874] 저장 사다리가 앞 문단의 아래 간격만 담지 않은 경계.
///
/// 한/글 저장 사다리의 문단 경계는 `다음 첫 줄 = 앞 마지막 줄 끝 + 앞 아래 간격 + 뒤 위
/// 간격` 이다. 이 중 아래 간격 항만 빠진 경계(`다음 첫 줄 = 앞 끝 + 뒤 위 간격`)에서도 한/글은
/// 앞 문단의 아래 간격을 둔다(합성 `samples/issue7874` 한/글 2024 Print: 1600 + 568HU 피치).
/// 이 경계의 저장 위치는 아래 간격만큼 낡았으므로, 앞 문단 흐름에서 깎은 간격을 복원하지
/// 못하고 그 간격만큼 앞선 흐름을 되감을 근거도 아니다. 조판(트림 복원 판정)과 배치(후방
/// 스냅)가 같은 판정을 쓴다. 위 간격까지 빠진 경계는 이 등식의 사례가 아니다 — 위 간격
/// 누락의 계약(`rebuilt_ladder_omits_spacing_before`·`#6031`)을 따른다.
pub(crate) fn stored_ladder_omits_spacing_after(
    previous: &Paragraph,
    current: &Paragraph,
    spacing_after: f64,
    spacing_before: f64,
    dpi: f64,
) -> bool {
    let Some(last) = previous.line_segs.last() else {
        return false;
    };
    let Some(first) = current.line_segs.first() else {
        return false;
    };
    spacing_after > 0.5
        && last.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
        && i64::from(first.vertical_pos)
            == i64::from(last.vertical_pos)
                + i64::from(last.line_height)
                + i64::from(last.line_spacing)
                + (spacing_before.max(0.0) * 7200.0 / dpi).round() as i64
        && !previous.stored_text_partition_is_dirty()
        && !previous.cell_format_vpos_dirty
        && !current.stored_text_partition_is_dirty()
        && !current.cell_format_vpos_dirty
}

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

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

fn para_has_equation_only(para: &Paragraph) -> bool {
    !para_has_visible_text(para)
        && para
            .controls
            .iter()
            .any(|ctrl| matches!(ctrl, Control::Equation(_)))
}

/// [#4626] 빈 텍스트 판정은 `para_has_visible_text` 하나로 통일한다.
///
/// 종전의 `text.trim().is_empty()` 는 개체 대체 문자(`\u{FFFC}`)를 공백으로 보지
/// 않아, **도형만 있는 문단의 표준형(`text == "\u{FFFC}"`)** 에서 `typeset.rs` 의
/// 동명 술어와 반대 답을 냈다. 바로 위 형제 술어
/// (`para_is_treat_as_char_equation_only`)는 이미 `para_has_visible_text` 를 쓴다 —
/// 이 함수만 예외였다.
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,
        })
}

fn para_has_treat_as_char_table(para: &Paragraph) -> bool {
    para.controls
        .iter()
        .any(|ctrl| matches!(ctrl, Control::Table(table) if table.common.treat_as_char))
}

fn compact_between_notes_gap_px(raw_gap_hu: i32, dpi: f64, use_pagination_gap: bool) -> f64 {
    if raw_gap_hu <= 0 {
        return 10.0;
    }
    let effective_hu = if use_pagination_gap {
        let extra = (raw_gap_hu - 1984).max(0);
        if extra > 0 {
            extra * 3 / 4
        } else {
            raw_gap_hu
        }
    } else {
        raw_gap_hu
    };
    hwpunit_to_px(effective_hu, dpi)
}

pub(crate) struct HeightCursor {
    /// DPI (px/inch).
    pub dpi: f64,
    /// 단 영역 top y (px). lazy_path anchor.
    pub col_area_y: f64,
    /// 단 영역 높이 (px). 본문내 클램프 상한 산출.
    pub col_area_height: f64,
    /// body_wide_reserved 푸시 적용 후 첫 항목 y (px). page_path anchor (#412).
    pub col_anchor_y: f64,
    /// 페이지 기준 vpos. 첫 PageItem 이 명확한 vpos 를 가질 때 (#412).
    pub vpos_page_base: Option<i32>,
    /// 지연 기준 vpos. 첫 PageItem 이 신뢰 불가할 때 sequential y 에서 역산 (#412).
    pub vpos_lazy_base: Option<i32>,
    /// 처음 확정한 저장 단 원점. TAC 뒤 활성 기준이 지워져도 독립 대조에 보존한다.
    pub stored_column_origin: Option<(i32, f64)>,
    /// native HWP5 의 저장 vpos 는 쪽 상대 절대 좌표 —
    /// page_base 가 소거된 상황에서도 lazy 역산(부정확 기준) 대신 base=0 페이지
    /// 경로를 쓴다 (재현 문서 C pi4: lazy 2748 로 저장 958 대신 921 에 그려져
    /// 꽃 장식과 겹치던 실측).
    /// 직전 배치 문단 인덱스.
    pub prev_layout_para: Option<usize>,
    /// 직전 항목이 분할 표(PartialTable)였는지 (#991).
    pub prev_item_was_partial_table: bool,
    /// HWP3-origin 흐름에서는 vpos 보정에서 spacing_before 사전 차감을 생략한다(#1116).
    pub skip_spacing_before_prededuct: bool,
    /// 미주 흐름에서는 LINE_SEG vpos 가 같은 단 안에서 크게 되감길 수 있다.
    pub allow_vpos_rewind: bool,
    /// 미주 단은 하단부에서 뒤로 크게 되감을 수 있다.
    pub allow_start_height_backtrack: bool,
    /// 미주 흐름의 큰 forward vpos 점프는 단/쪽 재배치 흔적일 수 있어 순차 배치를 유지한다.
    pub suppress_large_forward_jump: bool,
    /// HWPX 원본의 일부 LINE_SEG vpos 는 이전 쪽/단 조판 좌표가 남아 페이지 상단 본문을
    /// 과도하게 아래로 밀 수 있다. 원본 IR은 보존하고 조판 커서에서만 제한적으로 접는다.
    pub suppress_hwpx_stale_forward: bool,
    /// 현재 문단의 저장 forward 원점을 거절했다. 뒤 개체의 저장 줄 단축도
    /// 이 결정을 소비하며 첫 원점의 인증만으로 같은 좌표를 되살리지 않는다.
    pub rejected_stored_forward_origin: Option<i32>,
    /// HWP5 컨테이너의 변환 계보도 유효 저장 줄을 가질 수 있다. 재측정된
    /// 수식 줄의 실제 전진은 다음 저장 원점에서 낡은 높이로 되돌리지 않는다.
    pub stored_equation_reflow: bool,
    /// 실제 구성 결과가 직전 문단의 저장 수식 줄 전진을 갱신했다는 소비 기록.
    pub prev_reissued_equation_rows: bool,
    /// [#5854] 저장 LINE_SEG 사다리가 통짜 합성값인 문서 — `vertical_pos` 가 실측
    /// 조판 좌표가 아니므로 앵커 스냅 자체를 끈다. 켜 두면 글꼴로 다시 뽑은 줄
    /// 진행을 매 항목마다 그 상수 사다리로 되돌려 놓는다.
    pub uniform_filler_ladder: bool,
    /// [Task #1246] 현재 섹션 미주의 between-notes 마진(HU, 0=미적용). 새 미주 제목이 forward
    /// 흐름에서 이 마진보다 작은 간격을 가지면(다줄 풀이 끝 trailing 누락=문22) 끌어올린다.
    /// 생성자는 0 으로 두고 호출자(build_single_column)가 미주 흐름 컬럼에서만 설정한다.
    pub endnote_between_notes_hu: i32,
    /// 렌더러가 기록한 직전 항목의 실제 콘텐츠 하단(px). trailing 줄간격을 실제
    /// 콘텐츠 하단으로 오인하는 compact 미주 경계에서 공통 gap 기준으로 사용한다.
    pub prev_item_content_bottom_y: Option<f64>,
    /// 직전 실제 흐름 줄 상자의 끝. 빈 줄도 포함하며 trailing 간격은 제외한다.
    pub prev_item_flow_line_bottom_y: Option<f64>,
    /// 같은 단의 실제 점유·간격 또는 확정 개체 프레임이 소유한 후속 문단 원점.
    /// 측정과 배치의 공통 결과이며 낡은 저장 사다리보다 우선한다.
    pub(crate) owned_origin: Option<FlowOrigin>,
    /// 직전 `vpos_adjust`에서 새 미주 제목 gap을 저장 end_y보다 위로 compact했는지.
    pub(crate) last_compacted_endnote_title_gap: bool,
    /// [#5699 H1] 저장 사다리가 자리차지 표 밴드를 계상하지 않은 문서에서, 흐름이
    /// 페인트된 표 밴드 위로 되감기지 못하게 하는 바닥(절대 y px). 기본 `f64::MIN`
    /// = 비활성. 표 아이템 배치 후 자기모순 판별이 참일 때만 호출자가 올린다.
    pub min_flow_floor: f64,
    /// 현재 저장 경계가 이미 소유한 문단 위 간격. 표 바닥 보호는 논리 문단
    /// 시작에 이 값을 더한 실제 글줄 시작을 대조한다. 매 경계에서 초기화한다.
    pub stored_boundary_spacing_before: f64,
    /// [#6753] 직전 문단이 `#2279 ①` 트림으로 흐름에서 **빼고 전진한 `spacing_before`**(px).
    ///
    /// lazy 기준 역산은 sequential `y_offset` 을 사다리 좌표에 맞대어 기준점을 구하는데,
    /// 그 `y_offset` 에는 트림분이 빠져 있다. 그대로 역산하면 **트림된 `sb` 가 기준점에
    /// 그대로 실려** 그 쪽 전체 좌표계가 그만큼 어긋난다.
    ///
    /// `27469` 5쪽 실측 — `pi=26` 이 `sb 40.00px`(3000 HU)을 트림당한 뒤 `pi=27` 에서 역산:
    ///
    /// ```text
    ///   현행   16560 − (11962 + 1600) = 2998 HU   ← 트림된 sb 그 자체
    ///   되돌림 16560 − (14962 + 1600) =   −2 HU   → 0 (페인트가 실제로 쓰는 기준)
    /// ```
    ///
    /// 0 이면 종전과 완전히 같은 경로다(트림이 없었거나 sb 몫이 아닐 때).
    pub trimmed_prev_spacing_before_px: f64,
    /// [편집 세션] 저장 사다리의 전방 점프가 쪽 말미(하단 15%)로 향하면 기각한다.
    /// 편집으로 앞 내용이 밀린 뒤의 저장 좌표는 이 쪽의 물리 상태와 무관해,
    /// 점프하면 후속 분할 조각이 쪽 밖으로 밀린다(셀 Enter 재현).
    pub session_edited: bool,
    /// [#7351] 이번 항목이 **표 조각**(`PageItem::PartialTable`)인가. 조각은 host 문단의 앞
    /// 간격을 그리는 문단 경로를 타지 않으므로 `vpos_corrected_end_y` 의 `sb_N` 사전 차감
    /// 대상이 아니다. layout 만 세운다.
    pub curr_item_is_table_fragment: bool,
    /// [#7665] 미주 흐름에서 **미주의 첫 문단**(렌더가 번호 장식을 붙이는 문단, 조판 `ep_idx == 0`)
    /// 인 전역 문단 번호. 새 문항 제목 판정은 이 소유 경계로 한다 — 첫 문단이 「문」 으로
    /// 시작하는지(번호 장식 `문1)` 의 대리값)로 읽으면 같은 미주 안 `문서…` 본문도 제목이 된다.
    /// 미주 흐름 단에서만 호출자가 채운다.
    pub endnote_note_first_paras: std::sync::Arc<std::collections::HashSet<usize>>,
    pub endnote_tail_leading_hu: std::sync::Arc<std::collections::HashMap<usize, i32>>,
    /// [#7702] 쪽/단 첫 항목인 이어지는 부분 문단의 연속 줄이 합성 줄이라 #5820 의 기준을
    /// 그 줄에서 세우지 못했다. 다음 저장 문단이 자기 실제 흐름 위치로 기준을 세운다.
    pub seed_lazy_base_from_next_stored: bool,
}

#[path = "height_cursor_lazy_base.rs"]
mod lazy_base_rounding;
#[path = "height_cursor_saved_boundary.rs"]
mod saved_boundary;

impl HeightCursor {
    /// fit이 발행한 내용 합집합은 그대로 두고 이미 소비한 빈 간격만 제외한다.
    pub(crate) fn remaining_endnote_gap_px(&self, gap: f64) -> f64 {
        let consumed = self
            .prev_layout_para
            .and_then(|index| self.endnote_tail_leading_hu.get(&index))
            .copied()
            .unwrap_or(0);
        (gap - hwpunit_to_px(consumed, self.dpi)).max(0.0)
    }
    /// [#7665] 미주 흐름 문단이 미주의 첫 문단(새 문항 제목)인가 — 소유 경계.
    fn starts_endnote(&self, para_index: usize) -> bool {
        self.endnote_note_first_paras.contains(&para_index)
    }

    /// 컬럼 진입 시 생성. `vpos_page_base` 초기값은 호출자가 첫 PageItem 에서 산출.
    pub(crate) fn new(
        dpi: f64,
        col_area_y: f64,
        col_area_height: f64,
        col_anchor_y: f64,
        vpos_page_base: Option<i32>,
        skip_spacing_before_prededuct: bool,
        allow_vpos_rewind: bool,
        allow_start_height_backtrack: bool,
        suppress_large_forward_jump: bool,
    ) -> Self {
        HeightCursor {
            dpi,
            col_area_y,
            col_area_height,
            col_anchor_y,
            vpos_page_base,
            vpos_lazy_base: None,
            stored_column_origin: vpos_page_base.map(|base| (base, col_anchor_y)),
            prev_layout_para: None,
            prev_item_was_partial_table: false,
            skip_spacing_before_prededuct,
            allow_vpos_rewind,
            allow_start_height_backtrack,
            suppress_large_forward_jump,
            suppress_hwpx_stale_forward: false,
            rejected_stored_forward_origin: None,
            stored_equation_reflow: false,
            prev_reissued_equation_rows: false,
            uniform_filler_ladder: false,
            endnote_between_notes_hu: 0,
            prev_item_content_bottom_y: None,
            prev_item_flow_line_bottom_y: None,
            owned_origin: None,
            last_compacted_endnote_title_gap: false,
            min_flow_floor: f64::MIN,
            stored_boundary_spacing_before: 0.0,
            trimmed_prev_spacing_before_px: 0.0,
            session_edited: false,
            curr_item_is_table_fragment: false,
            endnote_note_first_paras: Default::default(),
            endnote_tail_leading_hu: Default::default(),
            seed_lazy_base_from_next_stored: false,
        }
    }

    /// 유효한 저장 글줄을 실제로 수용한 원점에서 뒤 사다리를 재시작한다.
    /// 줄간격을 이미 소비한 흐름을 lazy 역산으로 다시 전진시키지 않는다.
    pub(crate) fn seed_stored_flow_origin(&mut self, vertical_pos: i32, line_origin: f64) {
        let base =
            vertical_pos - crate::renderer::px_to_hwpunit(line_origin - self.col_area_y, self.dpi);
        self.vpos_page_base = None;
        self.vpos_lazy_base = Some(base);
        self.stored_column_origin = Some((base, self.col_area_y));
    }

    /// 완전 개체 프레임이 확정한 뒤 저장 줄을 현재 좌표축에 연결한다.
    /// 원본·정규화 줄 좌표는 각 입력의 값으로 변환하되 같은 실제 종료량을
    /// 소비한다. 이전 호스트의 줄간격이나 lazy 역산을 이 경계에 반복하지 않는다.
    pub(crate) fn bind_stored_frame_successor(
        &mut self,
        y_offset: f64,
        item_para: usize,
        paragraphs: &[Paragraph],
        placements: &std::collections::HashMap<
            (usize, usize),
            super::float_placement::ParagraphFloatPlacement,
        >,
    ) -> bool {
        if self.session_edited
            || self.uniform_filler_ladder
            || !self.dpi.is_finite()
            || self.dpi <= 0.0
        {
            return false;
        }
        let Some(para) = paragraphs.get(item_para) else {
            return false;
        };
        let Some(line) = para.line_segs.first() else {
            return false;
        };
        if para.stored_text_partition_is_dirty()
            || para.cell_format_vpos_dirty
            || para.column_type != crate::model::paragraph::ColumnBreakType::None
            || line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
            || line.line_height <= 0
        {
            return false;
        }
        let unit = self.dpi / 7200.0;
        let origin = placements.iter().find_map(|(&(owner, _), placement)| {
            let origin = placement.stored_successor_line_origin?;
            (owner.checked_add(1) == Some(item_para)
                && placement.flow == super::float_placement::ParagraphFloatFlow::NextLine
                && origin.is_finite()
                && (origin - placement.occupied_bottom).abs() <= unit
                && (y_offset - self.col_area_y - origin).abs() <= unit)
                .then_some(origin)
        });
        let Some(origin) = origin else {
            return false;
        };
        let base = line.vertical_pos - (origin * 7200.0 / self.dpi).round() as i32;
        self.col_anchor_y = self.col_area_y;
        self.vpos_page_base = Some(base);
        self.vpos_lazy_base = None;
        self.stored_column_origin = Some((base, self.col_area_y));
        self.stored_boundary_spacing_before = 0.0;
        true
    }

    /// 후속 원본 줄이 확인한 재조판 소비 끝을 같은 단의 저장 축으로 잇는다.
    /// 논리 문단 시작과 앞 간격 뒤 글줄 원점을 혼동해 새 base를 만들지 않는다.
    pub(crate) fn bind_computed_paragraph_successor(
        &mut self,
        y_offset: f64,
        item_para: usize,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
        origins: &std::collections::HashMap<usize, super::pagination::ParagraphOrigin>,
    ) -> bool {
        if self.session_edited
            || self.uniform_filler_ladder
            || self.curr_item_is_table_fragment
            || self.prev_item_was_partial_table
        {
            return false;
        }
        let Some(previous) = self.prev_layout_para else {
            return false;
        };
        if previous.checked_add(1) != Some(item_para) {
            return false;
        }
        let Some(origin) = origins.get(&previous) else {
            return false;
        };
        let Some(para) = paragraphs.get(item_para) else {
            return false;
        };
        let Some(line) = para.line_segs.first() else {
            return false;
        };
        let Some(style) = styles.para_styles.get(para.para_shape_id as usize) else {
            return false;
        };
        let source = para
            .source_line_seg_vertical_pos
            .as_ref()
            .and_then(|positions| positions.first())
            .copied()
            .unwrap_or(line.vertical_pos);
        let unit = self.dpi / 7200.0;
        let flow_end_y = self.col_area_y + origin.flow_end;
        let source_y = self.col_area_y + hwpunit_to_px(source, self.dpi);
        if para.stored_text_partition_is_dirty()
            || para.cell_format_vpos_dirty
            || para.column_type != crate::model::paragraph::ColumnBreakType::None
            || line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
            || line.line_height <= 0
            || !unit.is_finite()
            || unit <= 0.0
            || !y_offset.is_finite()
            || !flow_end_y.is_finite()
            || origin.paragraph_index != previous
            || !style.spacing_before.is_finite()
            || style.spacing_before < 0.0
            || (y_offset - flow_end_y).abs() > unit
            || (source_y - flow_end_y - style.spacing_before).abs() > unit
            || line.vertical_pos.checked_sub(source) != Some(origin.source_vpos_base)
        {
            return false;
        }
        self.vpos_page_base = Some(origin.source_vpos_base);
        self.vpos_lazy_base = None;
        self.col_anchor_y = self.col_area_y;
        self.stored_column_origin = Some((origin.source_vpos_base, self.col_area_y));
        self.stored_boundary_spacing_before = style.spacing_before;
        true
    }

    /// 항목 배치 직전, vpos 기반 y_offset 보정을 적용한다.
    ///
    /// 렌더러 `build_single_column` 의 inter-item VPOS_CORR 블록과 동작 동일.
    /// 보정이 적용되면 보정된 y, 아니면 입력 `y_offset` 을 그대로 반환한다.
    /// `vpos_lazy_base` 는 지연 산출 시 갱신된다.
    ///
    /// 호출자는 `!shape_jumped && !prev_tac_seg_applied` 가드 안에서 호출한다.
    pub(crate) fn vpos_adjust(
        &mut self,
        y_offset: f64,
        item_para: usize,
        paragraphs: &[Paragraph],
        styles: &ResolvedStyleSet,
    ) -> f64 {
        self.last_compacted_endnote_title_gap = false;
        self.stored_boundary_spacing_before = 0.0;
        self.rejected_stored_forward_origin = None;
        if let Some(owned) = self.owned_origin.take() {
            let origin = owned.y();
            // 측정과 배치가 확인한 점유 경계에는 임의 완충을 추가하지 않는다.
            // 뒤 문단도 이 실제 원점을 이어받도록 현재 저장 기준을 함께 연결한다.
            if let Some(first) = paragraphs.get(item_para).and_then(|p| p.line_segs.first()) {
                let spacing_before = paragraphs
                    .get(item_para)
                    .and_then(|p| styles.para_styles.get(p.para_shape_id as usize))
                    .map_or(0.0, |s| s.spacing_before);
                let anchor = if self.vpos_page_base.is_some() {
                    self.col_anchor_y
                } else {
                    self.col_area_y
                };
                let base = first.vertical_pos
                    - crate::renderer::px_to_hwpunit(
                        owned.first_line_y(spacing_before) - anchor,
                        self.dpi,
                    );
                if self.vpos_page_base.is_some() {
                    self.vpos_page_base = Some(base);
                } else {
                    self.vpos_lazy_base = Some(base);
                }
            }
            return origin;
        }
        // [#5854] 통짜 합성 사다리는 조판 좌표가 아니다 — 스냅 근거로 쓰지 않는다.
        if self.uniform_filler_ladder {
            return y_offset;
        }
        let Some(prev_pi) = self.prev_layout_para else {
            // [#7702] #5820 확장 — 연속 줄이 합성이면 첫 저장 문단에서 기준을 세운다. 세우지
            // 않으면 다음 문단이 이 문단 끝에서 기준을 거꾸로 재는데, 그 역산식은 끝 줄간격·
            // 아래 간격을 트림한 조판 흐름을 전제해 그리기 흐름에서는 그만큼 아래로 밀린다
            // (HWP5-nopassword 15쪽 pi=215: 1168 HU = 15.6px). 조판은 같은 자리에서 앞 합성
            // 문단의 연속 사다리로 같은 기준을 얻는다.
            if self.seed_lazy_base_from_next_stored {
                if let Some(seg) = paragraphs
                    .get(item_para)
                    .and_then(|para| para.line_segs.first())
                    .filter(|seg| {
                        seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                    })
                {
                    self.seed_lazy_base_from_next_stored = false;
                    let delta_hu =
                        ((y_offset - self.col_area_y) / self.dpi * 7200.0).round() as i32;
                    let base = seg.vertical_pos - delta_hu;
                    if base >= 0 {
                        self.vpos_lazy_base = Some(base);
                    }
                }
            }
            return y_offset;
        };
        // 표시는 리셋 바로 뒤 한 문단에만 유효하다.
        self.seed_lazy_base_from_next_stored = false;
        if item_para == prev_pi {
            return y_offset;
        }
        // 같은 프레임에 이미 수용한 빈 줄 뒤의 저장 reset은 새 쪽이 아니다.
        // 원래 빈 줄을 단 원점으로 삼았다는 증거가 있을 때만, 뒤 저장 사다리를
        // 실제로 이어받은 원점에서 다시 시작한다. 측정과 paint가 같은 조회를 쓴다.
        if self.rebase_after_empty_prefix(y_offset, item_para, prev_pi, paragraphs) {
            return y_offset;
        }
        // 글앞으로/글뒤로/위아래 Shape·Picture 가 있는 문단: vpos 에 개체 높이 포함 → bypass
        // (#409, #1027 Stage B). 분할 표 직후 첫 문단도 sequential 신뢰 (#991).
        let prev_has_overlay_shape = paragraphs
            .get(prev_pi)
            .map(para_has_overlay_shape)
            .unwrap_or(false);
        if prev_has_overlay_shape || self.prev_item_was_partial_table {
            // 분할 자리차지 표의 이어지는 조각 뒤 첫 문단은 저장 첫 줄이 조각 점유 끝(앞 간격을
            // 조각 안에서 소비한 자리)이다. 그 줄로 단의 사다리 기준을 세워, 빈 문단 뒤
            // trailing 줄간격 bridge 가 다음 문단을 한 줄간격 더 내리지 않게 한다.
            if self.prev_item_was_partial_table
                && self.vpos_page_base.is_none()
                && !self.session_edited
            {
                if let (Some(host), Some(para)) =
                    (paragraphs.get(prev_pi), paragraphs.get(item_para))
                {
                    let spacing_before = styles
                        .para_styles
                        .get(para.para_shape_id as usize)
                        .map_or(0.0, |style| style.spacing_before);
                    if let (Some(first), Some(spacing)) = (
                        para.line_segs.first().filter(|seg| {
                            seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                                && !para.stored_text_partition_is_dirty()
                                && !para.cell_format_vpos_dirty
                        }),
                        crate::renderer::float_placement::split_float_successor_spacing_before(
                            host,
                            para,
                            self.col_area_y,
                            spacing_before,
                            y_offset,
                        ),
                    ) {
                        let line_top = y_offset + spacing;
                        self.vpos_lazy_base = Some(
                            first.vertical_pos
                                - crate::renderer::px_to_hwpunit(
                                    line_top - self.col_area_y,
                                    self.dpi,
                                ),
                        );
                    }
                }
            }
            return y_offset;
        }
        let Some(prev_para) = paragraphs.get(prev_pi) else {
            return y_offset;
        };
        // A floating picture does not consume the host's text advance. The
        // saved successor can nevertheless certify that its line is below the
        // complete picture. Reconstructing a new lazy origin from that empty
        // host's cursor loses the original column frame (and lifts captions
        // into the picture). Pagination and paint retain the same source frame.
        if !self.session_edited {
            if let (Some((base, origin)), Some(current)) =
                (self.stored_column_origin, paragraphs.get(item_para))
            {
                let authored = |p: &Paragraph| {
                    !p.stored_text_partition_is_dirty()
                        && !p.cell_format_vpos_dirty
                        && p.source_line_seg_vertical_pos
                            .as_ref()
                            .is_none_or(|source| {
                                source
                                    .iter()
                                    .copied()
                                    .eq(p.line_segs.iter().map(|s| s.vertical_pos))
                            })
                        && p.line_segs.iter().all(|s| {
                            s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0 && s.line_height > 0
                        })
                };
                if let ([host], Some(next), [Control::Picture(picture)]) = (
                    prev_para.line_segs.as_slice(),
                    current.line_segs.first(),
                    prev_para.controls.as_slice(),
                ) {
                    let common = &picture.common;
                    let (_, height) = super::layout::picture_flow_frame_size_hu(picture);
                    let picture_end = i64::from(host.vertical_pos)
                        + i64::from(common.vertical_offset as i32)
                        + i64::from(height);
                    if !para_has_visible_text(prev_para)
                        && authored(prev_para)
                        && authored(current)
                        && host.segment_width == 0
                        && next.segment_width > 0
                        && !common.treat_as_char
                        && common.text_wrap == TextWrap::Square
                        && common.vert_rel_to == VertRelTo::Para
                        && common.vert_align == crate::model::shape::VertAlign::Top
                        && common.flow_with_text
                        && !common.allow_overlap
                        && height > 0
                        && host.vertical_pos >= base
                        && i64::from(next.vertical_pos) >= picture_end
                        && current.column_type == crate::model::paragraph::ColumnBreakType::None
                        && origin + hwpunit_to_px(next.vertical_pos - base, self.dpi)
                            <= self.col_area_y + self.col_area_height
                    {
                        self.vpos_page_base = Some(base);
                        self.vpos_lazy_base = None;
                        self.col_anchor_y = origin;
                    }
                }
            }
        }
        // An empty explicit page-break paragraph consumes its real line box,
        // but its zero stored cursor does not locate the successor's saved
        // coordinate frame. Establish that frame from the first text line's
        // accepted origin, including its paragraph-before band. This also
        // handles stored text coordinates which include the paper top margin.
        if self.suppress_hwpx_stale_forward
            && !self.session_edited
            && (matches!(
                prev_para.column_type,
                crate::model::paragraph::ColumnBreakType::Page
                    | crate::model::paragraph::ColumnBreakType::Column
            ) || matches!(prev_para.line_segs.as_slice(), [line] if line.line_height <= 0))
            && prev_para.text.trim().is_empty()
            && prev_para
                .controls
                .iter()
                .all(|control| matches!(control, Control::ColumnDef(_) | Control::Bookmark(_)))
            && !prev_para.stored_text_partition_is_dirty()
            && !prev_para.cell_format_vpos_dirty
        {
            if let ([previous], Some(current)) =
                (prev_para.line_segs.as_slice(), paragraphs.get(item_para))
            {
                if let Some(first) = current.line_segs.first() {
                    let previous_style = styles.para_styles.get(prev_para.para_shape_id as usize);
                    let font_size = prev_para
                        .char_shape_id_at(0)
                        .and_then(|id| styles.char_styles.get(id as usize))
                        .map_or(0.0, |style| style.font_size);
                    let (previous_height, previous_spacing) =
                        crate::renderer::corrected_line_metrics(
                            hwpunit_to_px(previous.line_height, self.dpi),
                            hwpunit_to_px(previous.line_spacing, self.dpi),
                            font_size,
                            previous_style
                                .map_or(crate::model::style::LineSpacingType::Percent, |s| {
                                    s.line_spacing_type
                                }),
                            previous_style.map_or(160.0, |s| s.line_spacing),
                        );
                    let previous_advance = previous_height
                        + previous_spacing
                        + previous_style.map_or(0.0, |s| s.spacing_before + s.spacing_after);
                    if previous.vertical_pos == 0
                        && previous_height > 0.0
                        && previous.line_spacing >= 0
                        && previous.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                        && first.vertical_pos > 0
                        && first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                        && current.controls.is_empty()
                        && para_has_visible_text(current)
                        && !current.stored_text_partition_is_dirty()
                        && !current.cell_format_vpos_dirty
                        && current
                            .source_line_seg_vertical_pos
                            .as_ref()
                            .is_none_or(|source| source.first() == Some(&first.vertical_pos))
                        && y_offset >= self.col_area_y
                        && (prev_para
                            .controls
                            .iter()
                            .any(|control| matches!(control, Control::ColumnDef(_)))
                            || (y_offset - self.col_area_y - previous_advance).abs()
                                <= self.dpi / 7200.0)
                    {
                        let before = styles
                            .para_styles
                            .get(current.para_shape_id as usize)
                            .map_or(0.0, |s| s.spacing_before);
                        self.vpos_page_base = Some(
                            first.vertical_pos
                                - crate::renderer::px_to_hwpunit(
                                    y_offset + before - self.col_area_y,
                                    self.dpi,
                                ),
                        );
                        self.vpos_lazy_base = None;
                        return y_offset;
                    }
                }
            }
        }
        // 이월 첫 줄의 이전 축과 후속 본문의 새 축을 같은 저장 간격 등식으로 잇는다.
        // 현재 커서도 그 첫 줄의 실제 전진량과 같아야 새 쪽의 경계다.
        if !self.session_edited && !self.allow_vpos_rewind && !self.allow_start_height_backtrack {
            if let Some(current) = paragraphs.get(item_para) {
                if let Some(before) = super::layout::stored_carried_first_line_margin(
                    prev_para,
                    Some(current),
                    styles,
                    self.dpi,
                    self.col_area_height,
                ) {
                    let previous_row = &prev_para.line_segs[0];
                    let after = styles
                        .para_styles
                        .get(prev_para.para_shape_id as usize)
                        .map_or(0.0, |style| style.spacing_after);
                    let consumed = before
                        + hwpunit_to_px(
                            previous_row
                                .line_height
                                .saturating_add(previous_row.line_spacing),
                            self.dpi,
                        )
                        + after;
                    if (y_offset - self.col_area_y - consumed).abs() <= self.dpi / 7200.0 {
                        let first = &current.line_segs[0];
                        let source = current
                            .source_line_seg_vertical_pos
                            .as_ref()
                            .and_then(|positions| positions.first())
                            .copied()
                            .unwrap_or(first.vertical_pos);
                        let before = styles
                            .para_styles
                            .get(current.para_shape_id as usize)
                            .map_or(0.0, |style| style.spacing_before);
                        let base = first.vertical_pos.saturating_sub(source);
                        self.vpos_page_base = Some(base);
                        self.vpos_lazy_base = None;
                        self.col_anchor_y = self.col_area_y;
                        self.stored_column_origin = Some((base, self.col_area_y));
                        self.stored_boundary_spacing_before = before;
                        return self.col_area_y + hwpunit_to_px(source, self.dpi) - before;
                    }
                }
            }
        }
        // 수식 부분 재조판으로 바뀐 높이를 연속된 옛 저장 사다리가 복원하지 않게 한다.
        // 단/쪽 리셋이나 실제 저장 gap은 아래 기존 경로가 소유한다.
        if !self.session_edited
            && (((self.suppress_hwpx_stale_forward || self.stored_equation_reflow)
                && self.prev_reissued_equation_rows)
                || (self.suppress_hwpx_stale_forward
                    && crate::renderer::composer::uses_remeasured_equation_frame(prev_para)))
        {
            if let Some((previous, current)) = prev_para.line_segs.last().zip(
                paragraphs
                    .get(item_para)
                    .and_then(|para| para.line_segs.first()),
            ) {
                let previous_end = previous
                    .vertical_pos
                    .saturating_add(previous.line_height)
                    .saturating_add(previous.line_spacing);
                if current.vertical_pos > previous.vertical_pos
                    && current.vertical_pos == previous_end
                {
                    let anchor = if self.vpos_page_base.is_some() {
                        self.col_anchor_y
                    } else {
                        self.col_area_y
                    };
                    let base = current.vertical_pos
                        - crate::renderer::px_to_hwpunit(y_offset - anchor, self.dpi);
                    if self.vpos_page_base.is_some() {
                        self.vpos_page_base = Some(base);
                    } else {
                        self.vpos_lazy_base = Some(base);
                    }
                    return y_offset;
                }
            }
        }
        // 재조판한 일반 본문은 이미 소비한 실제 줄 끝에서 이어진다.
        // 합성 vpos에는 문단 앞 간격이나 이전 재조판의 높이가 반영되지 않을 수
        // 있으므로 저장 절대 원점처럼 다시 적용하지 않는다. 그 뒤의 저장 빈 줄도
        // 자체 줄 높이·간격만 소비하며, 옛 절대 위치를 빈 공간으로 추가하지 않는다.
        if let Some(para) = paragraphs
            .get(item_para)
            .filter(|para| para.controls.is_empty())
        {
            if crate::renderer::para_has_no_stored_line_segs(para) {
                return y_offset;
            }
            if para.text.is_empty()
                && prev_para.controls.is_empty()
                && crate::renderer::para_has_no_stored_line_segs(prev_para)
            {
                if let Some(seg) = para.line_segs.first() {
                    // 앞 본문은 새 줄 수를 소비했다. 저장 vpos는 빈 줄 상자의
                    // 시작이며, 호출자가 이 뒤에 소비하는 문단 앞 간격도 포함한다.
                    // 간격 적용 전의 y에 연결하면 뒤 저장 줄이 그 간격만큼 되감긴다.
                    let spacing_before = crate::renderer::hwp3_variant_flow_spacing_before(
                        styles
                            .para_styles
                            .get(para.para_shape_id as usize)
                            .map_or(0.0, |style| style.spacing_before),
                        self.skip_spacing_before_prededuct,
                    );
                    let anchor = if self.vpos_page_base.is_some() {
                        self.col_anchor_y
                    } else {
                        self.col_area_y
                    };
                    let base = seg.vertical_pos
                        - crate::renderer::px_to_hwpunit(
                            y_offset + spacing_before - anchor,
                            self.dpi,
                        );
                    if self.vpos_page_base.is_some() {
                        self.vpos_page_base = Some(base);
                    } else {
                        self.vpos_lazy_base = Some(base);
                    }
                }
                return y_offset;
            }
        }
        // Task #332 Stage 5: width 검증을 가드 조건으로 약화, 마지막 유효 segment 사용.
        let prev_seg = prev_para
            .line_segs
            .iter()
            .rev()
            .find(|ls| ls.segment_width > 0)
            .or_else(|| prev_para.line_segs.last());
        let Some(seg) = prev_seg else {
            return y_offset;
        };
        // [Task #1811] 합성 seg(원본 linesegarray 부재 — reflow/컨버터 생성,
        // TAG_IMPLEMENTATION_PROPERTY)는 저장 증거가 아니다. **전방(forward)** 보정
        // 근거로 쓰면 구세션 저장 flow 위치로 과대 전진해(+9.6px) 후속 분할 표 예산이
        // 부족해진다 (saved_bounds_cumulative_page_break p4 컷 [2]→[3] 결손).
        // 단, 되감기는 허용한다(sequential 이 앞서 나갔을 때의 재동기화). 판정은 최종
        // result 산출 후 방향으로 한다 (함수 끝 합성 전방 차단).
        let synthetic_prev_seg =
            seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0;
        // 분할 표 뒤 빈 줄의 저장 위치는 이전 본문 프레임 밖에 남을 수 있다.
        // 그 줄의 높이·간격은 이미 소비했으므로, 다음 본문이 원래 프레임 안으로
        // 돌아오면 옛 빈 줄 위치로 지연 기준을 역산하지 않는다. 현재 원본 위치와
        // 누적 위치의 차이로 같은 프레임을 예약·배치 커서에 함께 확정한다.
        let returned_body_origin = (|| {
            let current = paragraphs.get(item_para)?;
            let first = current.line_segs.first()?;
            let previous_source = prev_para
                .source_line_seg_vertical_pos
                .as_ref()
                .and_then(|positions| positions.last())
                .copied()
                .unwrap_or(seg.vertical_pos);
            let current_source = current
                .source_line_seg_vertical_pos
                .as_ref()
                .and_then(|positions| positions.first())
                .copied()
                .unwrap_or(first.vertical_pos);
            let body_height = crate::renderer::px_to_hwpunit(self.col_area_height, self.dpi);
            let spacing_before = if self.skip_spacing_before_prededuct {
                0.0
            } else {
                styles
                    .para_styles
                    .get(current.para_shape_id as usize)?
                    .spacing_before
            };
            let body_y = self.col_area_y + hwpunit_to_px(current_source, self.dpi);
            let valid = !self.session_edited
                && !self.allow_vpos_rewind
                && !self.allow_start_height_backtrack
                && !self.suppress_large_forward_jump
                && !synthetic_prev_seg
                && !prev_para.stored_text_partition_dirty
                && !current.stored_text_partition_dirty
                && prev_para.controls.is_empty()
                && prev_para.text.trim().is_empty()
                && prev_para.line_segs.len() == 1
                && seg.line_height > 0
                && current.controls.is_empty()
                && !current.text.trim().is_empty()
                && current.column_type == crate::model::paragraph::ColumnBreakType::None
                && current.line_segs.iter().all(|line| {
                    line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                        && line.line_height > 0
                })
                && previous_source > body_height
                && current_source > first.line_height
                && current_source < previous_source
                && current_source.saturating_add(first.line_height) <= body_height
                // 원본 위치가 이미 소비한 흐름을 침범하면 저장 원점으로 복구하지 않는다.
                && body_y - spacing_before >= y_offset;
            valid.then(|| {
                first
                    .vertical_pos
                    .checked_sub(current_source)
                    .map(|base| (base, body_y - spacing_before, spacing_before))
            })?
        })();
        if let Some((base, body_y, spacing_before)) = returned_body_origin {
            self.vpos_page_base = Some(base);
            self.vpos_lazy_base = None;
            self.col_anchor_y = self.col_area_y;
            self.stored_column_origin = Some((base, self.col_area_y));
            self.stored_boundary_spacing_before = spacing_before;
            return body_y;
        }
        if seg.vertical_pos == 0 && prev_pi > 0 {
            // 중간 문단의 로컬 0은 쪽 원점이 아니다. 다만 현재 저장 원점과
            // 한 줄의 실제 소비 범위가 같은 프레임을 확인하면 그 줄의
            // 후행 간격을 다음 원본 글줄에서 복원할 수 있다.
            let follows_stored_zero_origin = (|| {
                let (base, anchor) = self
                    .vpos_page_base
                    .map(|base| (base, self.col_anchor_y))
                    .or_else(|| self.vpos_lazy_base.map(|base| (base, self.col_area_y)))?;
                let current = paragraphs.get(item_para)?;
                let first = current.line_segs.first()?;
                let previous_style = styles.para_styles.get(prev_para.para_shape_id as usize)?;
                let current_style = styles.para_styles.get(current.para_shape_id as usize)?;
                let ink_end = anchor + hwpunit_to_px(seg.line_height, self.dpi);
                let stored_next = anchor + hwpunit_to_px(first.vertical_pos, self.dpi);
                let previous_end =
                    hwpunit_to_px(seg.line_height.saturating_add(seg.line_spacing), self.dpi)
                        + previous_style.spacing_after
                        + current_style.spacing_before;
                Some(
                    base == 0
                        && !self.session_edited
                        && !synthetic_prev_seg
                        && prev_para.line_segs.len() == 1
                        && prev_para.controls.is_empty()
                        && current.controls.is_empty()
                        && current.column_type == crate::model::paragraph::ColumnBreakType::None
                        && first.tag
                            & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                            == 0
                        && seg.line_height > 0
                        && previous_style.spacing_before.abs() < 0.1
                        && first.vertical_pos > 0
                        && (stored_next - anchor - previous_end).abs() < 0.1
                        && stored_next <= self.col_area_y + self.col_area_height
                        && y_offset + 0.1 >= ink_end
                        && y_offset <= stored_next - current_style.spacing_before + 0.1,
                )
            })()
            .unwrap_or(false);
            // 명시적 새 쪽의 절대 위치 Square 앵커는 중간 문단의 로컬 0이
            // 아니다. 쪽 원점이 이미 0으로 인증됐으면 옆 차선의 앵커 줄 뒤
            // 저장 줄도 그 축을 소비한다. 측정과 paint가 같은 판정을 쓴다.
            let follows_page_square_origin = self.vpos_page_base == Some(0)
                && matches!(prev_para.column_type,
                    crate::model::paragraph::ColumnBreakType::Page
                        | crate::model::paragraph::ColumnBreakType::Column)
                && !synthetic_prev_seg
                && !prev_para.stored_text_partition_is_dirty()
                && !prev_para.cell_format_vpos_dirty
                && prev_para.controls.iter().any(|control| {
                    matches!(control, Control::Table(table)
                        if !table.common.treat_as_char
                            && table.common.text_wrap == TextWrap::Square
                            && matches!(table.common.vert_rel_to, VertRelTo::Page | VertRelTo::Paper))
                })
                && paragraphs.get(item_para).is_some_and(|current| {
                    current.column_type == crate::model::paragraph::ColumnBreakType::None
                        && !current.stored_text_partition_is_dirty()
                        && !current.cell_format_vpos_dirty
                        && current.line_segs.first().is_some_and(|first| {
                            first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                                && first.line_height > 0
                                && first.vertical_pos > 0
                                && self.col_anchor_y + hwpunit_to_px(first.vertical_pos, self.dpi)
                                    <= self.col_area_y + self.col_area_height
                        })
                });
            if !follows_stored_zero_origin && !follows_page_square_origin {
                return y_offset;
            }
        }
        let prev_vpos_end = seg
            .vertical_pos
            .saturating_add(seg.line_height)
            .saturating_add(seg.line_spacing);
        let curr_first_vpos = paragraphs
            .get(item_para)
            .and_then(|p| p.line_segs.first())
            .map(|ls| ls.vertical_pos);
        // 앞 문단의 저장 좌표가 이 단 높이 밖이면 그 줄은 앞 쪽 좌표계에 남은 값이다
        // (분할 표 뒤 빈 문단이 표 시작 쪽의 vpos 를 갖는 경우). 되감긴 현재 문단의
        // 기준을 그 값에서 역산하지 않고 순차 흐름을 따른다(1480000 44쪽: pi=264
        // vpos 72003 > 단 높이 71153HU, pi=265 를 trailing 간격만큼 더 내리지 않는다).
        let col_height_hu = (self.col_area_height * 7200.0 / self.dpi).round() as i32;
        if !self.session_edited
            && prev_para.controls.is_empty()
            && !para_has_visible_text(prev_para)
            && seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
            && seg.vertical_pos > col_height_hu
            && curr_first_vpos.is_some_and(|curr| curr < seg.vertical_pos)
        {
            return y_offset;
        }
        if !self.session_edited
            && self.stored_column_origin.is_some_and(|(base, _)| {
                paragraphs
                    .get(item_para)
                    .and_then(|para| para.line_segs.first())
                    .is_some_and(|first| {
                        first.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                            && first.vertical_pos < base
                    })
            })
        {
            // This owner starts a new source axis inside the accepted physical
            // column. The preceding axis must not restore a stale tail here.
            self.vpos_page_base = None;
            self.vpos_lazy_base = None;
            self.stored_column_origin = None;
            return y_offset;
        }
        // 합성 줄 뒤의 수용 위치가 원본 첫 줄과 이미 일치하면, 재구성 vpos를
        // 옛 단 축으로 읽어 되당기지 않는다. 측정과 배치는 같은 기준을 이어받는다.
        if synthetic_prev_seg && !self.session_edited && !self.skip_spacing_before_prededuct {
            if let Some(base) = paragraphs.get(item_para).and_then(|current| {
                origin::source_aligned_rebuilt_base(
                    prev_para,
                    current,
                    styles,
                    self.stored_column_origin?,
                    y_offset,
                    self.dpi,
                )
            }) {
                if self.vpos_page_base.is_some() {
                    self.vpos_page_base = Some(base);
                } else {
                    self.vpos_lazy_base = Some(base);
                }
                return y_offset;
            }
        }
        // 저장 줄이 없는 글자취급 그림의 합성 시작이 앞 저장 글줄 끝과 같으면
        // 그 합성 좌표에는 그림 문단의 위 간격이 아직 담겨 있지 않다.
        // 이 경우 간격을 미리 빼면 실제 배치가 더하는 같은 간격과 상쇄된다.
        let inline_host_without_stored_anchor = !synthetic_prev_seg
            && curr_first_vpos == Some(prev_vpos_end)
            && paragraphs.get(item_para).is_some_and(|para| {
                para.line_segs.first().is_none_or(|line| {
                    line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0
                }) && !para.controls.is_empty()
                    && para.controls.iter().all(|control| {
                        matches!(control, Control::Picture(picture) if picture.common.treat_as_char)
                    })
            });
        let prev_has_text = prev_para
            .text
            .chars()
            .any(|c| c > '\u{001F}' && c != '\u{FFFC}');
        let prev_is_empty_float_table_host = !prev_has_text
            && prev_para.controls.iter().any(|c| {
                matches!(c, Control::Table(t)
                    if !t.common.treat_as_char
                        && matches!(t.common.text_wrap, TextWrap::TopAndBottom))
            });
        let stored_gap_exists = matches!(curr_first_vpos, Some(v) if v > prev_vpos_end);
        // 쪽 기준과 지연 기준이 같은 저장 경계를 먼저 생산한다.
        if prev_is_empty_float_table_host && stored_gap_exists {
            // 표가 이미 소비한 끝과 원본 글줄 시작이 같으면 이 글줄의
            // 위 간격은 저장 시작에 포함돼 있다. 뒤의 연속 저장 사다리도
            // 확인하여 실제 배치가 다시 더하는 간격을 한 번만 소비한다.
            let stored_margin_origin = paragraphs.get(item_para).and_then(|para| {
                let first = para.line_segs.first()?;
                let last = para.line_segs.last()?;
                let next = paragraphs.get(item_para + 1)?;
                let next_first = next.line_segs.first()?;
                let style = styles.para_styles.get(para.para_shape_id as usize)?;
                let next_style = styles.para_styles.get(next.para_shape_id as usize)?;
                let (base, anchor) = self
                    .vpos_page_base
                    .map(|base| (base, self.col_anchor_y))
                    .or_else(|| self.vpos_lazy_base.map(|base| (base, self.col_area_y)))
                    .unwrap_or((0, self.col_area_y));
                let stored_start_y = anchor + hwpunit_to_px(first.vertical_pos - base, self.dpi);
                let stored_step = hwpunit_to_px(
                    next_first.vertical_pos
                        - last.vertical_pos
                        - last.line_height
                        - last.line_spacing,
                    self.dpi,
                );
                (!self.session_edited
                    && !self.skip_spacing_before_prededuct
                    && !synthetic_prev_seg
                    && para.controls.is_empty()
                    && next.controls.is_empty()
                    && next.column_type == crate::model::paragraph::ColumnBreakType::None
                    && [first, last, next_first].iter().all(|line| {
                        line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                            == 0
                    })
                    && style.spacing_before > 0.0
                    && y_offset - style.spacing_before >= self.col_area_y
                    && stored_start_y <= self.col_area_y + self.col_area_height
                    && (stored_start_y - y_offset).abs() < 0.1
                    && (stored_step - style.spacing_after - next_style.spacing_before).abs() < 0.1)
                    .then_some(style.spacing_before)
            });
            if let Some(spacing_before) = stored_margin_origin {
                if self.vpos_page_base.is_none() && self.vpos_lazy_base.is_none() {
                    self.vpos_lazy_base = Some(0);
                }
                self.stored_boundary_spacing_before = spacing_before;
                return y_offset - spacing_before;
            }
        }
        // [Task #412] page_base / lazy_base 경로 분리.
        let (base, is_page_path) = if let Some(b) = self.vpos_page_base {
            (b, true)
        } else if let Some(b) = self.vpos_lazy_base {
            (b, false)
        } else {
            // [Task #1022 v2] trailing-ls 보정의 조건부 복원 (upstream stream/devel 정합).
            // 컬럼이 vpos 0 에서 시작해 sequential 이 IR 을 정확히 추적(drift 0)하면
            // +trailing_ls 는 over-correction(lazy_base 음수 → 표 overflow, exam_kor p5).
            // 그러나 컬럼이 vpos 0 이 아닌 곳에서 시작(상단 박스/도형 뒤 본문, footnote-01 p1)
            // 하면 trailing_ls bridge 가 필요. 게이트: 보정 lazy_base ≥ 0 이면 보정 적용.
            // [Task #1049] 직전이 실텍스트 본문 문단이고 vpos 가 연속
            // (curr_first_vpos == prev_vpos_end)이면, 그 문단의 trailing 줄간격이 이미
            // 연속 vpos 흐름·sequential y 에 포함되어 있으므로 trailing-ls bridge 를 끈다
            // (인라인 TAC 리셋 직후 +trailing_ls 가 12.8px 과대 전진을 일으키는 회귀 차단).
            // - curr_first_vpos 가 prev_vpos_end 초과(gap: top-box 후 본문·footnote-01 p1)
            //   또는 미상이면 종전대로 bridge 적용(#1022 v2).
            // - 직전이 빈 문단이면 렌더러의 빈줄 높이 억제로 trailing_ls 가 sequential y 에
            //   반영되지 않을 수 있어 bridge 유지(복학원서 page1: 빈 문단 뒤 폼 표).
            // [#2243] 직전 문단이 **빈 앵커 자리차지(TopAndBottom, 비-TAC) 표 host** 면
            // prev_end→curr 저장 vpos 갭은 표의 흐름 공간 인코딩이다. sequential y 는
            // 표 소비를 이미 포함하므로 lazy 역산이 이 갭을 재가산하면 표 높이만큼
            // 이중 계상된다 (36382819 pi=31: lazy_base 역산 +12971HU → 페이지3
            // +184.9px → 4쪽 sliver, 한글 3쪽). 보정 없이 sequential 을 신뢰한다.
            // page_base 경로(절대 좌표)는 정상 동작하므로 lazy 역산 한정.
            // 전방 재가산 형상(저장 갭 존재 = curr_v0 > prev_end)만 차단 — 갭이
            // 없으면 정상 lazy 역산을 유지해 sequential 과대의 역방향 보정을
            // 살린다 (156631374: 무차별 차단 시 1→2쪽 회귀).
            if prev_is_empty_float_table_host && stored_gap_exists {
                return y_offset;
            }
            // [Issue #1898] 직전 문단이 "실텍스트 + 인라인(tac) 그림 호스트" 이면, 저장
            // vpos gap 이 현재 문단 spacing_before 이하일 때 연속으로 본다. 이 gap 은 sb
            // 인코딩이며 sb 는 vpos_corrected_end_y 가 별도로 사전 차감하므로 이미 계상된
            // 정상 전진이다. tac 그림 PageItem 이 vpos base 를 리셋한 직후 이 gap 을
            // 불연속으로 오판해 +trailing_ls bridge 를 더하면 그림 문단 뒤 줄 전진이
            // gap 1회분(+11.7px) 과대해진다 (36388711 p9 참고자료: 렌더 44.8px vs
            // layout/한컴 33.1px — 기전 1). 시그니처를 tac 그림 텍스트 호스트 직후로
            // 한정해 일반 lazy 재역산의 bridge 는 종전 유지 (rowbreak-problem-pages
            // 쪽나눔 무회귀). HWP3-origin 변환본(sb 사전 차감 생략 경로)도 종전 유지.
            let prev_has_tac_picture = prev_para
                .controls
                .iter()
                .any(|c| matches!(c, Control::Picture(p) if p.common.treat_as_char));
            let prev_is_tac_picture_text_host = prev_has_text && prev_has_tac_picture;
            let prev_is_tac_picture_only =
                prev_has_tac_picture && para_is_treat_as_char_picture_only(prev_para);
            // 재구성 전의 두 저장 글줄이 같은 본문 프레임 안에 있고 경계
            // 차이가 현재 문단 위 간격과 정확히 같으면, 앞줄 trailing 은 이미
            // 순차 커서에 소비됐다. 재구성한 누적 vpos만으로 판단하지 않는다.
            let curr_is_plain_stored = self.suppress_hwpx_stale_forward
                && !self.session_edited
                && !synthetic_prev_seg
                && prev_para.controls.is_empty()
                && paragraphs.get(item_para).is_some_and(|para| {
                    para.controls.is_empty()
                        && para.line_segs.first().is_some_and(|line| {
                            line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                                == 0
                        })
                        && prev_para
                            .source_line_seg_vertical_pos
                            .as_ref()
                            .and_then(|positions| positions.last())
                            .zip(
                                para.source_line_seg_vertical_pos
                                    .as_ref()
                                    .and_then(|positions| positions.first()),
                            )
                            .is_some_and(|(prev_source, curr_source)| {
                                let prev_end = prev_source
                                    .saturating_add(seg.line_height)
                                    .saturating_add(seg.line_spacing);
                                let before = styles
                                    .para_styles
                                    .get(para.para_shape_id as usize)
                                    .map(|ps| {
                                        (ps.spacing_before * 7200.0 / self.dpi).round() as i32
                                    })
                                    .unwrap_or(0);
                                let body_hu =
                                    (self.col_area_height * 7200.0 / self.dpi).round() as i32;
                                before > 0
                                    && prev_end > 0
                                    && *curr_source <= body_hu
                                    && *curr_source == prev_end.saturating_add(before)
                            })
                });
            let curr_sb_hu = if self.skip_spacing_before_prededuct
                || !(prev_is_tac_picture_text_host
                    || prev_is_tac_picture_only
                    || curr_is_plain_stored)
            {
                0
            } else {
                paragraphs
                    .get(item_para)
                    .and_then(|p| styles.para_styles.get(p.para_shape_id as usize))
                    .map(|ps| ((ps.spacing_before * 7200.0 / self.dpi).round() as i32).max(0))
                    .unwrap_or(0)
            };
            let vpos_continuous =
                matches!(curr_first_vpos, Some(v) if v <= prev_vpos_end + curr_sb_hu);
            // 저장 HWPX의 글자취급 그림만 든 문단도 그림 높이와 trailing
            // 줄간격을 순차 커서가 이미 소비한다. 다음 저장 시작이 그 끝 또는
            // 다음 문단 앞 간격까지 이어지면 같은 간격을 lazy 기준에 재가산하지 않는다.
            // 앞 간격은 아래 저장 원점 조회가 사전 차감하고 실제 문단 배치가 한 번 더한다.
            let picture_spent_trailing = self.suppress_hwpx_stale_forward
                && !synthetic_prev_seg
                && prev_is_tac_picture_only
                && matches!(curr_first_vpos,
                    Some(v) if v >= prev_vpos_end && v <= prev_vpos_end.saturating_add(curr_sb_hu));
            // 실제 직전 점유 끝과 순차 커서가 저장 줄간격만큼 떨어져 있으면
            // 그 간격은 이미 소비됐다. 빈 글줄도 공간을 소유하므로 텍스트 유무로
            // 이 소비를 부정하지 않는다. 비연속·합성·편집 경로는 기존 bridge를 쓴다.
            let rendered_spent_trailing = !self.session_edited
                && !synthetic_prev_seg
                && curr_first_vpos == Some(prev_vpos_end)
                && paragraphs
                    .get(item_para)
                    .and_then(|p| p.line_segs.first())
                    .is_some_and(|s| {
                        s.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                    })
                // 줄간격 소비는 원점 확정의 증거가 아니다. 분할 표로 시작한 단처럼
                // 원점이 아직 없으면 기존 bridge를 유지한다. 이미 수용한 저장 원점의
                // 다음 줄 위치와 실제 순차 위치가 일치할 때만 재가산을 제거한다.
                && self.stored_column_origin.is_some_and(|(base, anchor)| {
                    let expected = anchor + hwpunit_to_px(prev_vpos_end - base, self.dpi);
                    (y_offset - expected).abs() < 0.1
                })
                && self.prev_item_flow_line_bottom_y.is_some_and(|bottom| {
                    let gap = y_offset - bottom;
                    let stored_gap = hwpunit_to_px(seg.line_spacing.max(0), self.dpi);
                    stored_gap > 0.0 && (gap - stored_gap).abs() < 0.1
                });
            let trailing_ls_hu = if (vpos_continuous && prev_has_text)
                || picture_spent_trailing
                || rendered_spent_trailing
            {
                0
            } else {
                paragraphs
                    .get(prev_pi)
                    .and_then(|p| p.line_segs.last())
                    .map(|s| s.line_spacing.max(0))
                    .unwrap_or(0)
            };
            // [#6753] 역산 기준을 **트림 이전의 흐름 위치**로 맞춘다.
            //
            // `y_offset` 은 직전 문단이 `#2279 ①` 트림으로 `sb` 를 빼고 전진한 결과다.
            // 그대로 역산하면 그 `sb` 가 기준점에 실려 쪽 전체가 그만큼 위로 쏠린다
            // (`27469` 5쪽: 기준 2998 HU = 트림된 40.00px, 이후 모든 문단이
            // `px(vpos − 2998) − sb` 로 놓여 페인트보다 40px 위에서 적합 판정된다).
            //
            // 트림이 없었으면 `trimmed_prev_spacing_before_px == 0.0` 이라 종전과 같은 식이다.
            let untrimmed_y_offset = y_offset + self.trimmed_prev_spacing_before_px;
            let y_delta_hu =
                ((untrimmed_y_offset - self.col_area_y) / self.dpi * 7200.0).round() as i32;
            let lazy_base_corrected = prev_vpos_end - (y_delta_hu + trailing_ls_hu);
            // 누적 HWPX 좌표와 원본의 쪽 내부 좌표가 동일한 차이로
            // 이어지고 현재 흐름도 원본 시작점에 도착했다면, 빈 줄의
            // 후행 간격을 역산 기준에서 다시 빼지 않는다.
            let source_continuous_base = (self.suppress_hwpx_stale_forward
                && !self.session_edited
                && !synthetic_prev_seg
                && !prev_has_text
                && !prev_para.stored_text_partition_is_dirty()
                && !prev_para.cell_format_vpos_dirty
                && vpos_continuous)
                .then(|| {
                    let curr_para = paragraphs.get(item_para)?;
                    if curr_para.stored_text_partition_is_dirty() || curr_para.cell_format_vpos_dirty {
                        return None;
                    }
                    let curr_model = curr_para.line_segs.first()?;
                    // 스냅샷은 구역의 vpos를 재계산할 때만 생긴다. 재계산하지
                    // 않은 정상 저장 줄은 현재 좌표가 원본 좌표다. 합성 줄은
                    // 위/아래 tag 검사로, 편집 좌표는 dirty 검사로 제외한다.
                    // 비어 있는 스냅샷을 정상 원본으로 대체하지 않는다.
                    let prev_source = match &prev_para.source_line_seg_vertical_pos {
                        Some(source) => *source.last()?,
                        None => seg.vertical_pos,
                    };
                    let curr_source = match &curr_para.source_line_seg_vertical_pos {
                        Some(source) => *source.first()?,
                        None => curr_model.vertical_pos,
                    };
                    let base = curr_model.vertical_pos.checked_sub(curr_source)?;
                    // Zero is a valid unchanged source coordinate transform,
                    // including the plain line after a continued table. Its
                    // already consumed spacing does not need a second bridge.
                    let source_is_continuous = base >= 0
                        && prev_source
                            .saturating_add(seg.line_height)
                            .saturating_add(seg.line_spacing)
                            == curr_source
                        && seg.vertical_pos.checked_sub(prev_source) == Some(base)
                        && curr_model.tag
                            & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                            == 0;
                    if !source_is_continuous {
                        return None;
                    }
                    // 개체 없는 유효한 빈 글줄은 높이와 후행 간격을 이미 소비했다.
                    // 분할 표 뒤의 상대 원점도 실제 수용한 끝에 연결하며, 원본의
                    // 절대 쪽 위치로 강제 이동하거나 간격을 다시 더하지 않는다.
                    // Ownership of this plain line's advance is independent
                    // of whether the successor anchors an object.
                    let plain_line_consumed = prev_para.controls.is_empty()
                        && prev_para.line_segs.len() == 1
                        && seg.line_height > 0
                        // 저장 좌표의 연속성은 실제 간격 소비의 증거가 아니다.
                        // 측정/배치가 수용한 줄 상자 끝과 확정 원점이 모두 같은
                        // 간격을 증언할 때만 후행 bridge를 제거한다.
                        && rendered_spent_trailing;
                    if std::env::var("RHWP_VPOS_DEBUG").is_ok() {
                        eprintln!(
                            "VPOS_SOURCE_CONTINUOUS: pi={} prev_pi={} prev_snapshot={} curr_snapshot={} source_base={} plain_line_consumed={}",
                            item_para, prev_pi,
                            prev_para.source_line_seg_vertical_pos.is_some(),
                            curr_para.source_line_seg_vertical_pos.is_some(),
                            base, plain_line_consumed,
                        );
                    }
                    if plain_line_consumed {
                        Some(prev_vpos_end - y_delta_hu)
                    } else {
                        ((y_offset - self.col_area_y - hwpunit_to_px(curr_source, self.dpi)).abs()
                            < 0.1)
                            .then_some(base)
                    }
                })
                .flatten();
            // [#7702] 그리기 흐름이 앞 문단 마지막 줄 뒤에서 «끝 줄간격 + 아래 간격» 을 실제로
            // 소비했으면(흐름 위치 − 줄 바닥이 그 합과 같으면), 그 바닥을 사다리의 같은 자리
            // (그 줄의 `vpos + 줄 높이`)에 맞대 기준을 세운다. 아래 역산식은 그 간격을 트림한
            // 조판 흐름을 전제해, 간격이 든 그리기에서는 기준이 낮아져 다음 문단이 내려간다
            // (HWP5-nopassword 3쪽 표 뒤 빈 문단 → 제목: 1168 HU = 15.6px). 끝 줄간격만 소비한
            // 경우는 위 `rendered_spent_trailing` 이, 소비 증거가 없으면 종전 식이 맡는다.
            let prev_spacing_after_px = styles
                .para_styles
                .get(prev_para.para_shape_id as usize)
                .map(|style| style.spacing_after)
                .unwrap_or(0.0);
            let flow_bottom_base = self
                .prev_item_flow_line_bottom_y
                // 음수 줄간격(줄이 겹치는 문단)은 흐름이 그 간격을 어떻게 소비했는지 이 등식으로
                // 판독할 수 없다 — 종전 식에 맡긴다(issue7333 aaaaaa 35쪽).
                .filter(|_| {
                    // 앞 문단의 사다리가 rhwp 가 다시 세운 좌표일 때만 쓴다(합성 줄이거나, 로드
                    // 재구성이 원본 vpos 를 옮겨 적은 저장 줄). 한/글 원본 사다리를 그대로 쓰는
                    // 문단은 옛 줄 나눔을 담을 수 있어 흐름과 맞대지 않는다(1790387 67쪽: 저장
                    // 5줄, 한/글 출력 4줄 그림 문단 뒤 문단이 26.4px 밀림).
                    let rebuilt_ladder = synthetic_prev_seg
                        || prev_para
                            .source_line_seg_vertical_pos
                            .as_ref()
                            .and_then(|source| source.first())
                            .zip(prev_para.line_segs.first())
                            .is_some_and(|(source, model)| *source != model.vertical_pos);
                    rebuilt_ladder
                        && prev_para.controls.is_empty()
                        && prev_spacing_after_px > 0.5
                        && seg.line_spacing >= 0
                })
                .filter(|bottom| {
                    let spent = y_offset - bottom;
                    let stored =
                        hwpunit_to_px(seg.line_spacing.max(0), self.dpi) + prev_spacing_after_px;
                    (spent - stored).abs() < 0.1
                })
                .map(|bottom| {
                    seg.vertical_pos.saturating_add(seg.line_height)
                        - ((bottom - self.col_area_y) / self.dpi * 7200.0).round() as i32
                });
            let lazy_base = source_continuous_base
                .or(flow_bottom_base)
                .unwrap_or_else(|| {
                    lazy_base_rounding::resolve_lazy_base(
                        prev_vpos_end,
                        y_delta_hu,
                        trailing_ls_hu,
                        self.trimmed_prev_spacing_before_px,
                    )
                });
            if lazy_base < 0 {
                // 역산 무효(자리차지 표 등): 이전 개체 높이가 sequential y 에 이미
                // 반영된 상태다. 여기서 vpos 보정을 적용하면 단 상단으로 되감겨
                // 본문 표와 뒤따르는 미주가 겹친다.
                if std::env::var("RHWP_VPOS_DEBUG").is_ok() {
                    eprintln!(
                        "VPOS_CORR_SKIP: pi={} prev_pi={} y_in={:.2} prev_vpos_end={} lazy_base_corrected={} lazy_base={}",
                        item_para, prev_pi, y_offset, prev_vpos_end, lazy_base_corrected, lazy_base,
                    );
                }
                let compact_endnote_question_title = self.suppress_large_forward_jump
                    && self.starts_endnote(item_para)
                    && seg.line_spacing > 1000;
                let compact_zero_gap_endnote_title_boundary = self.suppress_large_forward_jump
                    && self.endnote_between_notes_hu == 0
                    && self.starts_endnote(item_para)
                    && seg.line_spacing > 0
                    && seg.line_spacing <= 800;
                if compact_zero_gap_endnote_title_boundary {
                    // 0/0/0 미주에서 lazy_base 역산이 무효가 되는 페이지/단 시작부는
                    // 순차 y가 직전 문단 trailing line_spacing까지 포함한다. 한컴은
                    // 미주 사이 0mm 경계에서는 그 trailing gap을 다음 제목 앞 간격으로
                    // 쓰지 않으므로 한 줄 gap만 접어 문항별 +6px 누적 drift를 막는다.
                    let prev_line_spacing_px = (seg.line_spacing.max(0) as f64) / 7200.0 * self.dpi;
                    let compacted_y = y_offset - prev_line_spacing_px;
                    if compacted_y >= self.col_area_y && y_offset - compacted_y <= 12.0 {
                        return compacted_y;
                    }
                }
                if compact_endnote_question_title
                    && y_offset > self.col_area_y + self.col_area_height * 0.85
                {
                    let prev_line_spacing_px = (seg.line_spacing.max(0) as f64) / 7200.0 * self.dpi;
                    let prev_content_bottom_y = y_offset - prev_line_spacing_px;
                    let capped_y = prev_content_bottom_y + 10.0;
                    if capped_y < y_offset
                        && y_offset - capped_y <= 24.0
                        && capped_y >= self.col_area_y
                    {
                        return capped_y;
                    }
                }
                return y_offset;
            } else {
                self.vpos_lazy_base = Some(lazy_base);
                (lazy_base, false)
            }
        };
        // [Task #874 #8] stale table-host(TopAndBottom+vert=Para) 판정.
        let curr_has_topbottom_para_table = paragraphs
            .get(item_para)
            .map(|p| {
                p.controls.iter().any(|c| {
                    matches!(c, Control::Table(t)
                        if !t.common.treat_as_char
                        && matches!(t.common.text_wrap, TextWrap::TopAndBottom)
                        && matches!(t.common.vert_rel_to, VertRelTo::Para))
                })
            })
            .unwrap_or(false);
        // 표 host spacing과 본문 글줄의 앞 간격은 같은 소비가 아니다.
        // TAC 표 host도 본문 앞 간격이 재적용된다는 증거로 쓰지 않는다.
        let spacing_before_is_line_flow = paragraphs.get(item_para).is_some_and(|para| {
            !para
                .controls
                .iter()
                .any(|control| matches!(control, Control::Table(_)))
        });
        // [#7351] 표 조각은 host 문단의 앞 간격을 그리지 않는다 — 사전 차감하면 조각이 그 앞
        // 간격만큼 위로 붙는다(issue2004_cell_image_stack 4쪽: 정본 표 위 괘선 127.84,
        // 쪽 저장 기준점(#7345)을 고친 뒤 차감 스냅이 수용되면 121.1).
        let curr_sb = if self.curr_item_is_table_fragment {
            0.0
        } else {
            paragraphs
                .get(item_para)
                .and_then(|p| styles.para_styles.get(p.para_shape_id as usize))
                .map(|ps| ps.spacing_before)
                .unwrap_or(0.0)
        };
        // 이전 축의 기준보다 작은 저장 좌표는 그 기준으로 외삽하지 않는다.
        // 이미 소비한 흐름과 현재 앞 간격에서 새 첫 줄 원점을 확정한다.
        // 미주의 의도된 되감김과 편집/개체 경로는 이 일반 본문 계약과 다르다.
        if !self.allow_vpos_rewind && !self.session_edited {
            if let Some(current) = paragraphs.get(item_para) {
                if let Some(first) = saved_boundary::restart_below_origin(prev_para, current, base)
                {
                    self.seed_stored_flow_origin(first, y_offset + curr_sb);
                    return y_offset;
                }
            }
        }
        // 단일 셀 그림 프레임의 호스트 vpos는 앞 글줄 끝에서 정확히
        // 문단 앞 간격만큼 전진한 값으로 저장될 수 있다. 여기에는 표 높이가 없다.
        // 앞 글줄 끝을 기준으로 잡고 간격을 다시 빼면 첫 조각이
        // 흐름 원점 위로 올라간다(issue2004, 4쪽).
        // 같은 수치 간격을 가진 텍스트 표는 기존의 보수적인 호스트 규칙을 사용한다.
        // 그렇지 않으면 issue1853의 10쪽 마지막 글줄이 본문 아래로 내려간다.
        let one_cell_picture_frame = paragraphs.get(item_para).is_some_and(|para| {
            para.controls.iter().any(|control| match control {
                Control::Table(table) => {
                    table.row_count == 1
                        && table.col_count == 1
                        && table.cells.len() == 1
                        && table.cells[0].paragraphs.iter().any(|cell_para| {
                            cell_para
                                .controls
                                .iter()
                                .any(|control| matches!(control, Control::Picture(_)))
                        })
                }
                _ => false,
            })
        });
        let table_host_only_before_gap = self.suppress_hwpx_stale_forward
            && !self.session_edited
            && curr_has_topbottom_para_table
            && one_cell_picture_frame
            && curr_sb > 0.0
            && curr_first_vpos.is_some_and(|v| {
                v == prev_vpos_end.saturating_add((curr_sb * 7200.0 / self.dpi).round() as i32)
            });
        // 가시 본문 뒤 빈 표 호스트의 좌표가 앞 줄 끝과 두 문단 간격의 합이면
        // 그 좌표에는 표 높이가 들어 있지 않다. 표라는 이유로 앞 줄 끝을 쓰면
        // 앞 문단 뒤 간격과 현재 앞 간격을 함께 버린다. 저장 줄이 편집되었거나
        // 직전 개체가 높이를 소비하는 경우에는 이 등식을 배치 근거로 쓰지 않는다.
        let table_host_only_paragraph_gap = self.suppress_hwpx_stale_forward
            && !self.session_edited
            && curr_has_topbottom_para_table
            && !synthetic_prev_seg
            && curr_sb > 0.0
            && para_has_visible_text(prev_para)
            && prev_para.controls.is_empty()
            && !prev_para.stored_text_partition_dirty
            && prev_para.line_segs.iter().all(|line| {
                line.line_height > 0
                    && line.line_spacing >= 0
                    && line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
            })
            && prev_para.line_segs.windows(2).all(|pair| {
                pair[1].vertical_pos
                    == pair[0].vertical_pos + pair[0].line_height + pair[0].line_spacing
            })
            && paragraphs.get(item_para).is_some_and(|para| {
                !para_has_visible_text(para)
                    && !para.stored_text_partition_dirty
                    && para.line_segs.len() == 1
                    && para.line_segs[0].tag
                        & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                        == 0
                    && para.controls.len() == 1
                    && matches!(&para.controls[0], Control::Table(table)
                        if !table.common.treat_as_char
                            && table.common.vertical_offset == 0
                            && matches!(table.common.text_wrap, TextWrap::TopAndBottom)
                            && matches!(table.common.vert_rel_to, VertRelTo::Para))
            })
            && styles
                .para_styles
                .get(prev_para.para_shape_id as usize)
                .is_some_and(|style| {
                    style.spacing_after > 0.0
                        && curr_first_vpos.is_some_and(|v| {
                            v == prev_vpos_end.saturating_add(
                                ((style.spacing_after + curr_sb) * 7200.0 / self.dpi).round()
                                    as i32,
                            )
                        })
                });
        // [#7552] 앞 문단도 빈 자리차지 표 host 면 그 host 줄 끝은 앞 표의 내용 끝이 아니다.
        // 이때 저장 사다리는 현재 host 줄을 **문단 상단**에 두고 표 바깥 상자를 그 뒤에
        // 예약한다(다음 문단 vpos − 현재 vpos ≥ 바깥 상자). 앞 간격은 앞 표의 아래 여백·캡션
        // 띠에 흡수되어 사다리에 들어 있지 않다 — 정본 괘선 = 줄 vpos + 바깥 위 여백
        // (hwpspec 28쪽 pi=168 447.4, 50쪽 pi=328 858.2). 줄이 표 아래에 저장된 host
        // (PR #1088 hwp-multi-001)는 다음 문단까지 상자가 들어가지 않아 여기 오지 않는다.
        let empty_topbottom_host = |para: &crate::model::paragraph::Paragraph| -> Option<i64> {
            if para_has_visible_text(para) || para.controls.len() != 1 {
                return None;
            }
            match &para.controls[0] {
                Control::Table(table)
                    if !table.common.treat_as_char
                        && table.common.vertical_offset == 0
                        && matches!(table.common.text_wrap, TextWrap::TopAndBottom)
                        && matches!(table.common.vert_rel_to, VertRelTo::Para)
                        && table.common.height <= i32::MAX as u32 =>
                {
                    Some(
                        i64::from(table.common.height)
                            + i64::from(table.outer_margin_top)
                            + i64::from(table.outer_margin_bottom),
                    )
                }
                _ => None,
            }
        };
        let table_host_line_is_top_after_table_host = !self.session_edited
            && !synthetic_prev_seg
            && empty_topbottom_host(prev_para).is_some()
            && paragraphs.get(item_para).is_some_and(|para| {
                let Some(outer_box) = empty_topbottom_host(para) else {
                    return false;
                };
                let (Some(line), Some(next)) = (
                    para.line_segs.first(),
                    paragraphs
                        .get(item_para + 1)
                        .and_then(|next| next.line_segs.first()),
                ) else {
                    return false;
                };
                let stored = |seg: &crate::model::paragraph::LineSeg| {
                    seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                };
                stored(line)
                    && stored(next)
                    && para.line_segs.len() == 1
                    && line.vertical_pos > seg.vertical_pos
                    && i64::from(next.vertical_pos) - i64::from(line.vertical_pos) >= outer_box
            });
        // [Task #412] 현재 paragraph first vpos 우선(spacing_after 인코딩), reset 시 fallback.
        //
        // 단, 현재 문단이 para-relative TopAndBottom 표의 host 이면 first_vpos 가 표
        // 예약 높이를 포함할 수 있다. 그 값을 inter-item 목표 y 로 쓰면 표 높이만큼
        // 빈 공간을 만든 뒤 표를 다시 배치하게 된다(PR #1088 hwp-multi-001 pi=14).
        // 이 경우에는 직전 문단의 line-seg 끝만 신뢰하고, 표 위치/높이는 Table
        // PageItem 렌더 단계에서 반영한다.
        let vpos_rewind = matches!(curr_first_vpos, Some(v) if v < seg.vertical_pos);
        let curr_tac_picture_only = paragraphs
            .get(item_para)
            .map(para_is_treat_as_char_picture_only)
            .unwrap_or(false);
        let prev_has_visible_text = paragraphs
            .get(prev_pi)
            .map(para_has_visible_text)
            .unwrap_or(false);
        let compact_endnote_tac_picture_rewind = self.suppress_large_forward_jump
            && vpos_rewind
            && curr_tac_picture_only
            && !prev_has_visible_text;
        let compact_endnote_bottom_rewind = self.suppress_large_forward_jump
            && vpos_rewind
            && y_offset > self.col_area_y + self.col_area_height * 0.75;
        let vpos_end = match curr_first_vpos {
            Some(v)
                if (self.allow_vpos_rewind
                    || compact_endnote_bottom_rewind
                    || compact_endnote_tac_picture_rewind)
                    && vpos_rewind =>
            {
                v
            }
            Some(v)
                if v > seg.vertical_pos
                    && (!curr_has_topbottom_para_table
                        || table_host_only_before_gap
                        || table_host_only_paragraph_gap
                        || table_host_line_is_top_after_table_host) =>
            {
                v
            }
            _ => prev_vpos_end,
        };
        // [#7351] 자리차지 표 호스트는 첫 줄 vpos 대신 앞 줄 끝(`prev_vpos_end`)을 쓴다 — 저장
        // 사다리에서 그 값은 이미 현재 문단의 앞 간격 **앞**(문단 상단)이다. 글자 있는 호스트의
        // 표는 문단 상단 + 세로 오프셋에 놓이고 앞 간격을 다시 더하는 경로가 없으므로, 스냅이
        // 수용된 목표에서 앞 간격을 사전 차감하면 표가 그만큼 위로 간다(쪽 저장 기준점(#7345)을
        // 쪽 원점으로 고치면 종전에 기각되던 차감 스냅이 수용된다 — `issue_6797` 의 오프셋 표가
        // 574.8 → 568.1). 수용 여부(≤8px 후방 클램프 등)는 종전
        // 목표로 판정해 바꾸지 않고, 수용된 목표만 문단 상단으로 되돌린다 — 이미 흐름이 밴드
        // 아래에 둔 표를 저장 앵커로 다시 끌어올리지 않는다(#6798).
        //
        // 글자 없고 세로 오프셋도 없는 호스트는 `#7063`(`layout.rs`
        // `empty_float_vpos_snap_flow_top`)이 흐름 커서 + 바깥여백으로 맞추는 계약을 이미
        // 갖고 있어 그 갈래를 바꾸지 않는다. 오프셋이 있는 표는 그 계약 밖이고 문단 상단 +
        // 오프셋이 기준이다.
        let vpos_end_is_table_host_top = vpos_end == prev_vpos_end
            && curr_first_vpos != Some(prev_vpos_end)
            && curr_has_topbottom_para_table
            && paragraphs.get(item_para).is_some_and(|para| {
                para_has_visible_text(para)
                    || para.controls.iter().any(|c| {
                        matches!(c, Control::Table(t)
                            if !t.common.treat_as_char
                                && matches!(t.common.text_wrap, TextWrap::TopAndBottom)
                                && matches!(t.common.vert_rel_to, VertRelTo::Para)
                                && t.common.vertical_offset != 0)
                    })
            });
        // [Task #643] sb_N 사전 차감 대상 (vpos_corrected_end_y 내부에서 차감).
        // [Task #1027 Stage A] 공유 클램프 함수.
        let allow_large_backward = (self.allow_vpos_rewind && vpos_rewind)
            || (self.allow_start_height_backtrack
                && y_offset > self.col_area_y + self.col_area_height * 0.75)
            || compact_endnote_bottom_rewind
            || compact_endnote_tac_picture_rewind;
        // [#7702] 로드 재구성 사다리도 문단 앞 간격을 담는다(`document.rs` 재구성이 `앞 아래 +
        // 뒤 위` 를 더한다). 그래서 합성 줄 사이도 저장 줄처럼 앞 간격을 미리 빼고 스냅한다 —
        // 빼지 않으면 앞 간격이 스냅 목표와 배치에 두 번 들어간다(issue5929 어울림 앵커 문단).
        // Section reflow can preserve the original source origins while
        // rebuilding a continuous cursor without paragraph-before spacing.
        // If the source gap equals that declared spacing and the rebuilt gap
        // is zero, the spacing has not yet been consumed. Paint adds it once;
        // prededucting it here would cancel it (also for an inline shape host).
        let rebuilt_before_not_consumed = !self.session_edited
            && !self.curr_item_is_table_fragment
            && paragraphs.get(item_para).is_some_and(|current| {
                rebuilt_ladder_omits_spacing_before(prev_para, current, curr_sb, self.dpi)
            });
        let skip_prededuct = self.skip_spacing_before_prededuct
            || rebuilt_before_not_consumed
            || inline_host_without_stored_anchor
            || table_host_line_is_top_after_table_host;
        // This rebuilt axis omits paragraph-before bands already consumed by
        // preceding flow items. Its absolute origin therefore cannot snap the
        // current item. The accepted previous item's end owns the origin;
        // current paragraph-before spacing will be added by its placement.
        // [#7874] 저장 사다리가 앞 문단의 아래 간격만 빼먹은 경계(다음 문단 첫 줄 = 앞 문단
        // 마지막 줄 끝 + 위 간격)에서, 흐름이 그 아래 간격만큼 앞서 있는 것은 드리프트가 아니라
        // 간격을 소비한 것이다. 한/글은 그 간격을 둔다(HWP5-nopassword 2024 PDF: 1600 + 568HU).
        // 8px 이내라는 이유로 낡은 저장 위치로 되감지 않는다.
        let stored_after_not_consumed = !self.session_edited
            && styles
                .para_styles
                .get(prev_para.para_shape_id as usize)
                .is_some_and(|style| {
                    let prev_after = style.spacing_after;
                    if !paragraphs.get(item_para).is_some_and(|current| {
                        stored_ladder_omits_spacing_after(
                            prev_para, current, prev_after, curr_sb, self.dpi,
                        )
                    }) {
                        return false;
                    }
                    let backward = y_offset
                        - (if is_page_path {
                            self.col_anchor_y
                        } else {
                            self.col_area_y
                        } + hwpunit_to_px(vpos_end - base, self.dpi)
                            - if skip_prededuct { 0.0 } else { curr_sb });
                    prev_after > 0.5 && (backward - prev_after).abs() <= 1.0
                });
        let (end_y, applied) = if rebuilt_before_not_consumed || stored_after_not_consumed {
            (y_offset, false)
        } else {
            vpos_corrected_end_y(
                is_page_path,
                self.col_anchor_y,
                self.col_area_y,
                self.col_area_height,
                vpos_end,
                base,
                curr_sb,
                y_offset,
                curr_has_topbottom_para_table,
                spacing_before_is_line_flow,
                skip_prededuct,
                allow_large_backward,
                self.dpi,
            )
        };
        // 수용된 목표만 앞 간격 차감 없는 문단 상단으로 바꾼다(차감 뒤 단 상단 clamp 가 걸린
        // 목표에 앞 간격을 더하면 문단 상단을 넘으므로 같은 공용 함수로 다시 구한다).
        let end_y = if applied && vpos_end_is_table_host_top && !skip_prededuct {
            let (paragraph_top_y, _) = vpos_corrected_end_y(
                is_page_path,
                self.col_anchor_y,
                self.col_area_y,
                self.col_area_height,
                vpos_end,
                base,
                curr_sb,
                y_offset,
                curr_has_topbottom_para_table,
                spacing_before_is_line_flow,
                true,
                allow_large_backward,
                self.dpi,
            );
            if paragraph_top_y <= self.col_area_y + self.col_area_height {
                paragraph_top_y
            } else {
                end_y
            }
        } else {
            end_y
        };
        let prev_line_spacing_px = (seg.line_spacing.max(0) as f64) / 7200.0 * self.dpi;
        let prev_content_bottom_y = y_offset - prev_line_spacing_px;
        let measured_prev_content_bottom_y =
            self.prev_item_content_bottom_y.filter(|y| y.is_finite());
        let measured_prev_occupied_end_y = super::endnote_spacing::occupied_end(
            measured_prev_content_bottom_y,
            self.prev_item_flow_line_bottom_y,
        );
        let prev_content_floor_y = measured_prev_content_bottom_y
            .map(|bottom| bottom.max(prev_content_bottom_y))
            .unwrap_or(prev_content_bottom_y);
        let follows_tall_inline_item = self.suppress_large_forward_jump && seg.line_height > 1500;
        let current_is_compact_endnote_title =
            self.suppress_large_forward_jump && self.starts_endnote(item_para);
        let prev_line_carries_note_gap = seg.line_spacing > 1000;
        let compact_endnote_question_title =
            current_is_compact_endnote_title && prev_line_carries_note_gap;
        let bottom_new_note_gap_cap = if self.suppress_large_forward_jump
            && end_y <= self.col_area_y + self.col_area_height
            && (y_offset > self.col_area_y + self.col_area_height * 0.75
                || compact_endnote_question_title)
        {
            let preserved_gap_y = if compact_endnote_question_title && follows_tall_inline_item {
                // compact 미주의 display 수식 뒤 새 문항 제목은 저장 trailing
                // line_spacing 전체 뒤가 아니라 실제 보이는 수식 하단 뒤의 "미주 사이"
                // 공통 간격에 맞춘다.
                // 렌더러가 실제 콘텐츠 하단을 제공하면 그 값을 공통 기준으로 삼고,
                // height-only 경로처럼 값이 없으면 기존 LINE_SEG 추정값으로 폴백한다.
                let content_bottom_y = measured_prev_occupied_end_y
                    .map(|y| y.max(prev_content_bottom_y))
                    .unwrap_or(prev_content_bottom_y);
                let gap_px = self.remaining_endnote_gap_px(compact_between_notes_gap_px(
                    self.endnote_between_notes_hu,
                    self.dpi,
                    prev_para.text.trim().is_empty()
                        || para_is_treat_as_char_equation_only(prev_para),
                ));
                content_bottom_y + gap_px
            } else if y_offset > self.col_area_y + self.col_area_height * 0.75
                || prev_para.text.trim().is_empty()
            {
                // Empty paragraphs before the next compact endnote title already carry the
                // visual spacer. Adding the mid-column buffer again pushes later notes down.
                y_offset + prev_line_spacing_px
            } else if prev_para.line_segs.len() > 1 && self.endnote_between_notes_hu <= 2500 {
                // 기본 미주 다줄 tail 뒤 새 문항은 single-line tail보다 완충이 작다.
                // 큰 40px buffer를 쓰면 2023-09 p19 문29처럼 뒤 풀이가 frame 밖으로 밀린다.
                y_offset + prev_line_spacing_px + 18.0
            } else {
                y_offset + prev_line_spacing_px + 40.0
            };
            if compact_endnote_question_title && follows_tall_inline_item {
                Some(preserved_gap_y)
            } else {
                Some(preserved_gap_y.min(end_y))
            }
        } else {
            None
        };
        let compact_endnote_new_note_jump = self.suppress_large_forward_jump
            && compact_endnote_question_title
            && (seg.line_height > 1500 || bottom_new_note_gap_cap.is_some())
            && end_y > y_offset + 32.0
            && end_y < y_offset + 120.0;
        let compact_endnote_stale_note_gap = self.suppress_large_forward_jump
            && !is_page_path
            && compact_endnote_question_title
            && !follows_tall_inline_item
            && y_offset <= self.col_area_y + self.col_area_height * 0.75
            && end_y > y_offset + 200.0
            && prev_line_spacing_px > 0.0;
        let compact_endnote_top_stale_note_gap = compact_endnote_stale_note_gap
            && y_offset <= self.col_area_y + self.col_area_height * 0.08;
        let stale_note_gap_y =
            compact_endnote_stale_note_gap.then_some(if compact_endnote_top_stale_note_gap {
                y_offset
            } else {
                super::endnote_spacing::origin_after_gap(
                    y_offset,
                    measured_prev_occupied_end_y,
                    prev_line_spacing_px,
                )
            });
        let compact_endnote_tac_picture_gap = self.suppress_large_forward_jump
            && !is_page_path
            && end_y > y_offset
            && end_y <= y_offset + 12.0
            && (paragraphs
                .get(prev_pi)
                .map(para_is_treat_as_char_picture_only)
                .unwrap_or(false)
                || paragraphs
                    .get(item_para)
                    .map(para_is_treat_as_char_picture_only)
                    .unwrap_or(false));
        let follows_endnote_title =
            self.suppress_large_forward_jump && self.starts_endnote(prev_pi);
        let current_is_endnote_title =
            self.suppress_large_forward_jump && self.starts_endnote(item_para);
        // page-path compact 미주 하단의 새 문항 제목은 저장 vpos가 이미
        // 제목/다음 본문을 분리하는 경우가 있다. 기존 95% 꼬리 조건은
        // 2022-09 p17 문29처럼 하단 1줄 차이에서 제목만 아래로 눌러
        // 다음 본문과 겹치게 만들었으므로 page-path 제목만 90%부터 허용한다.
        let title_bottom_threshold = if is_page_path { 0.90 } else { 0.95 };
        let compact_endnote_title_bottom_backtrack = current_is_endnote_title
            && !vpos_rewind
            && !prev_para.text.trim().is_empty()
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height * title_bottom_threshold
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset - end_y <= 32.0;
        // [Task #1302] curr 첫 줄 stored vpos 가 prev 한 줄 정상 전진(lh+ls) 이상을 인코딩하는
        // **breakable 비제목 텍스트** 연속 문단은 overlap tail 이 아니라 정상 연속이다. 이때
        // page_base drift 로 end_y 가 위로 보여도(end_y < y_offset) page_tail backtrack 으로
        // y_offset(=trailing 포함 정답)을 깎으면 같은 미주 연속 문단이 컬럼 하단에서 줄간격이
        // 좁아진다(3-11월 18쪽 pi=852→853). 텍스트는 컬럼/쪽으로 넘길 수 있어 frame-fit 이
        // 불필요하다. 반면 문항 제목은 title-bottom 보정 계열의 기존 PDF 핀(#1284)을 따라야
        // 하고, 수식-only tail(#1274)은 atomic 이라 frame 안에 맞춰야 하므로 제외하고 종전대로
        // backtrack 한다.
        let curr_is_equation_only_tail = paragraphs
            .get(item_para)
            .map(para_is_treat_as_char_equation_only)
            .unwrap_or(false);
        let curr_first_full_advance = !current_is_endnote_title
            && !curr_is_equation_only_tail
            && matches!(
                curr_first_vpos,
                Some(v) if v - seg.vertical_pos >= seg.line_height.saturating_add(seg.line_spacing)
            );
        let compact_endnote_page_tail_backtrack = self.suppress_large_forward_jump
            && is_page_path
            && !vpos_rewind
            && !follows_tall_inline_item
            && !curr_first_full_advance
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height * 0.95
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset - end_y <= 32.0;
        let current_has_visible_text = paragraphs
            .get(item_para)
            .map(para_has_visible_text)
            .unwrap_or(false);
        let current_looks_like_numbered_note = paragraphs
            .get(item_para)
            .map(|p| {
                let text = p.text.trim_start();
                let digit_len = text
                    .as_bytes()
                    .iter()
                    .take_while(|b| b.is_ascii_digit())
                    .count();
                (1..=3).contains(&digit_len) && text.as_bytes().get(digit_len) == Some(&b')')
            })
            .unwrap_or(false);
        let current_is_tac_table_host = paragraphs
            .get(item_para)
            .map(para_has_treat_as_char_table)
            .unwrap_or(false);
        let compact_endnote_title_body_stale_forward = self.suppress_large_forward_jump
            && !is_page_path
            && follows_endnote_title
            && !current_is_endnote_title
            && !vpos_rewind
            && current_has_visible_text
            && end_y > y_offset + 32.0
            && end_y < y_offset + 120.0
            && y_offset > self.col_area_y + 1.0;
        // 연속된 저장 경계에서는 y_offset이 제목의 줄·간격을 이미 소비했다.
        // 오래된 절대 원점의 drift를 별도 제목 간격으로 다시 더하지 않는다.
        let title_body_gap = if paragraphs
            .get(item_para)
            .is_some_and(|current| saved_boundary::continuous(prev_para, current))
        {
            0.0
        } else {
            prev_line_spacing_px.max(10.0).min(18.0)
        };
        let title_body_gap_y =
            compact_endnote_title_body_stale_forward.then_some(y_offset + title_body_gap);
        let compact_endnote_text_after_tall_tail_backtrack = self.suppress_large_forward_jump
            && is_page_path
            && !vpos_rewind
            && follows_tall_inline_item
            && current_has_visible_text
            && !current_is_endnote_title
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset - end_y <= 32.0;
        let compact_endnote_text_after_lazy_tall_equation_floor = self.suppress_large_forward_jump
            && !is_page_path
            && !vpos_rewind
            && follows_tall_inline_item
            && current_has_visible_text
            && !current_is_endnote_title
            && para_has_equation_only(prev_para)
            && y_offset <= self.col_area_y + self.col_area_height - 80.0;
        let compact_endnote_deep_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && !vpos_rewind
            && !follows_endnote_title
            && !follows_tall_inline_item
            && !(compact_endnote_question_title && prev_para.text.trim().is_empty())
            && end_y < y_offset - 8.0
            && end_y >= prev_content_bottom_y
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && y_offset - end_y <= 80.0;
        let compact_endnote_single_line_tail_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && !vpos_rewind
            && follows_endnote_title
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height
            && end_y <= self.col_area_y + self.col_area_height
            && end_y >= prev_content_bottom_y
            && y_offset - end_y <= 32.0;
        let current_line_advance_px = paragraphs
            .get(item_para)
            .and_then(|p| p.line_segs.first())
            .map(|s| {
                hwpunit_to_px(
                    (s.line_height.saturating_add(s.line_spacing)).max(0),
                    self.dpi,
                )
            })
            .unwrap_or(0.0);
        let compact_endnote_page_no_separator_tail_pullup = self.suppress_large_forward_jump
            && is_page_path
            && current_has_visible_text
            && current_looks_like_numbered_note
            && !curr_is_equation_only_tail
            && seg.line_spacing < 0
            && current_line_advance_px <= 14.5
            && end_y < y_offset - 6.0
            && y_offset - end_y <= 18.0
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset > self.col_area_y + self.col_area_height - 80.0;
        let current_line_height_px = paragraphs
            .get(item_para)
            .and_then(|p| p.line_segs.first())
            .map(|s| hwpunit_to_px(s.line_height.max(0), self.dpi))
            .unwrap_or(current_line_advance_px);
        let col_bottom = self.col_area_y + self.col_area_height;
        let compact_endnote_question_title_bottom_fit = self.suppress_large_forward_jump
            && current_is_endnote_title
            && !vpos_rewind
            && current_line_height_px > 0.0
            && y_offset + current_line_height_px > col_bottom + 0.5
            && y_offset <= col_bottom + 80.0
            && prev_content_bottom_y < col_bottom;
        let compact_endnote_question_title_tail_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && prev_para.text.trim().is_empty()
            && end_y < y_offset - 32.0
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && y_offset <= col_bottom
            && y_offset - end_y <= 96.0;
        let compact_endnote_question_title_tail_soft_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && follows_tall_inline_item
            && prev_para.text.trim().is_empty()
            && end_y < y_offset - 20.0
            && end_y >= y_offset - 32.0
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && y_offset <= col_bottom;
        let compact_endnote_question_title_after_tall_tail_backtrack = self
            .suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && follows_tall_inline_item
            && !prev_para.text.trim().is_empty()
            && end_y < y_offset - 32.0
            && y_offset > self.col_area_y + self.col_area_height * 0.84
            && y_offset <= col_bottom
            && y_offset - end_y <= 120.0;
        let compact_endnote_question_title_after_tall_mid_backtrack = self
            .suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && follows_tall_inline_item
            && seg.line_height <= 3600
            && (!prev_para.text.trim().is_empty() || para_has_equation_only(prev_para))
            && end_y < y_offset - 32.0
            && y_offset > self.col_area_y + self.col_area_height * 0.50
            && y_offset <= self.col_area_y + self.col_area_height * 0.75
            && y_offset - end_y <= 96.0
            && self.endnote_between_notes_hu <= 2500;
        let compact_endnote_question_title_after_tall_regular_gap = self
            .suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && follows_tall_inline_item
            && compact_endnote_new_note_jump
            && !prev_para.text.trim().is_empty()
            && !para_is_treat_as_char_equation_only(prev_para)
            && self.endnote_between_notes_hu <= 2500
            && y_offset <= self.col_area_y + self.col_area_height * 0.45;
        let compact_endnote_question_title_after_tall_upper_flow = self.suppress_large_forward_jump
            && current_is_endnote_title
            && !vpos_rewind
            && follows_tall_inline_item
            && !prev_para.text.trim().is_empty()
            && end_y > y_offset + 8.0
            && end_y - y_offset <= 48.0
            && !compact_endnote_new_note_jump
            && y_offset <= self.col_area_y + self.col_area_height * 0.35;
        let compact_endnote_zero_gap_title_forward = self.suppress_large_forward_jump
            && current_is_endnote_title
            && !vpos_rewind
            && self.endnote_between_notes_hu == 0
            && !prev_para.text.trim().is_empty()
            && seg.line_spacing <= 800
            && end_y > y_offset + 18.0
            && end_y <= y_offset + 96.0
            && (!follows_tall_inline_item || !prev_para.text.trim().is_empty())
            && y_offset <= self.col_area_y + self.col_area_height * 0.35;
        let compact_endnote_title_tail_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && !vpos_rewind
            && follows_endnote_title
            && paragraphs
                .get(item_para)
                .map(|p| p.line_segs.len() >= 3)
                .unwrap_or(false)
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && y_offset - end_y <= 80.0;
        // Compact endnote LINE_SEG sometimes encodes a saved visual gap inside
        // the previous line spacing. In the active mid-column flow it is safe
        // to honor that backward target when it stays below the previous
        // visible content bottom; near the column tail, the configured endnote
        // note-gap must remain authoritative.
        let compact_endnote_safe_vpos_backtrack = self.suppress_large_forward_jump
            && !vpos_rewind
            && !(current_is_endnote_title && self.endnote_between_notes_hu > 3000)
            && end_y < y_offset - 8.0
            && end_y >= prev_content_bottom_y
            && end_y <= self.col_area_y + self.col_area_height
            && y_offset <= self.col_area_y + self.col_area_height * 0.75;
        let stale_forward = self.suppress_large_forward_jump && end_y > y_offset + 100.0;
        let prev_is_initial_empty_reset = prev_pi == 0
            && seg.vertical_pos == 0
            && !prev_has_visible_text
            && prev_para.text.trim().is_empty()
            && y_offset <= self.col_area_y + 48.0;
        let current_vpos_far_from_prev =
            matches!(curr_first_vpos, Some(v) if v - prev_vpos_end > 3200);
        let previous_has_stale_hwpx_line_metrics = self.suppress_hwpx_stale_forward
            && crate::renderer::paragraph_source_line_metrics_need_reflow(
                prev_para, styles, self.dpi,
            );
        let hwpx_page_start_stale_forward = self.suppress_hwpx_stale_forward
            && is_page_path
            && applied
            && !vpos_rewind
            && y_offset <= self.col_area_y + 96.0
            && end_y > y_offset + 48.0
            && ((prev_is_initial_empty_reset
                && current_has_visible_text
                && current_vpos_far_from_prev)
                || (current_is_tac_table_host && end_y > y_offset + 180.0)
                // 손상된 단일 줄의 저장 높이가 이후 문단의 절대 vpos까지 밀어 둔
                // HWPX는 순차 조판 위치를 유지한다. 그렇지 않으면 앞 줄을 재조판해도
                // 다음 문단에서 동일한 빈 공간이 다시 복원된다.
                || (previous_has_stale_hwpx_line_metrics && current_has_visible_text));
        if hwpx_page_start_stale_forward {
            self.rejected_stored_forward_origin = curr_first_vpos;
        }
        let compact_endnote_large_gap_body_stale_forward = self.suppress_large_forward_jump
            && !is_page_path
            && !vpos_rewind
            && self.endnote_between_notes_hu > 3000
            && current_has_visible_text
            && !current_is_endnote_title
            && end_y > y_offset + 80.0
            && end_y < y_offset + 140.0
            && y_offset > self.col_area_y + self.col_area_height * 0.55
            && y_offset < self.col_area_y + self.col_area_height * 0.80;
        let compact_endnote_page_title_body_stale_forward = self.suppress_large_forward_jump
            && is_page_path
            && !vpos_rewind
            && self.endnote_between_notes_hu > 3000
            && follows_endnote_title
            && !current_is_endnote_title
            && current_has_visible_text
            && end_y > y_offset + 32.0
            && end_y < y_offset + 120.0
            && y_offset <= self.col_area_y + self.col_area_height * 0.25;
        let compact_endnote_page_title_mid_stale_gap = self.suppress_large_forward_jump
            && is_page_path
            && !vpos_rewind
            && stale_forward
            && current_is_endnote_title
            && self.endnote_between_notes_hu > 0
            && self.endnote_between_notes_hu <= 2500
            && seg.line_spacing >= self.endnote_between_notes_hu
            && y_offset > self.col_area_y + self.col_area_height * 0.55
            && y_offset <= self.col_area_y + self.col_area_height * 0.85;
        let compact_endnote_page_title_default_mid_gap = self.suppress_large_forward_jump
            && is_page_path
            && !vpos_rewind
            && current_is_endnote_title
            && self.endnote_between_notes_hu > 0
            && self.endnote_between_notes_hu <= 2500
            && seg.line_spacing > 0
            && seg.line_spacing < self.endnote_between_notes_hu
            && end_y > y_offset + 48.0
            && end_y <= y_offset + 120.0
            && y_offset > self.col_area_y + self.col_area_height * 0.35
            && y_offset <= self.col_area_y + self.col_area_height * 0.55;
        let compact_endnote_large_empty_spacer_collapse = self.suppress_large_forward_jump
            && !is_page_path
            && stale_forward
            && current_is_endnote_title
            && !vpos_rewind
            && self.endnote_between_notes_hu > 3000
            && seg.line_spacing >= self.endnote_between_notes_hu
            && prev_para.line_segs.len() == 1
            && prev_para.text.trim().is_empty()
            && prev_para.controls.is_empty()
            && y_offset > self.col_area_y + self.col_area_height * 0.75;
        let compact_endnote_large_between_title_tail_backtrack = self.suppress_large_forward_jump
            && !is_page_path
            && current_is_endnote_title
            && !vpos_rewind
            && self.endnote_between_notes_hu > 3000
            && seg.line_spacing >= self.endnote_between_notes_hu
            && end_y < y_offset - 8.0
            && y_offset > self.col_area_y + self.col_area_height * 0.80
            && end_y <= col_bottom
            && end_y >= prev_content_floor_y
            && y_offset - end_y <= 36.0;
        let compact_no_separator_large_title_tail_gap = self.suppress_large_forward_jump
            && !is_page_path
            && stale_forward
            && current_is_endnote_title
            && !vpos_rewind
            && self.endnote_between_notes_hu > 3000
            && seg.line_spacing >= self.endnote_between_notes_hu
            && !prev_para.text.trim().is_empty()
            && !follows_tall_inline_item
            && y_offset > self.col_area_y + self.col_area_height * 0.90
            && y_offset <= col_bottom;
        let compact_endnote_zero_gap_text_floor = self.suppress_large_forward_jump
            && is_page_path
            && self.endnote_between_notes_hu == 0
            && !current_is_endnote_title
            && current_has_visible_text
            && current_looks_like_numbered_note
            && !curr_is_equation_only_tail
            && measured_prev_content_bottom_y.is_some()
            && end_y < prev_content_floor_y - 0.25
            && y_offset >= prev_content_floor_y
            && y_offset - end_y <= 24.0;
        if compact_endnote_stale_note_gap
            || compact_endnote_title_body_stale_forward
            || compact_endnote_large_gap_body_stale_forward
            || compact_endnote_page_title_body_stale_forward
            || compact_endnote_page_title_mid_stale_gap
            || compact_no_separator_large_title_tail_gap
            || hwpx_page_start_stale_forward
            || (applied && (compact_endnote_new_note_jump || compact_endnote_tac_picture_gap))
        {
            // Compact endnote flow encodes visual gaps in absolute vpos.
            // Suppressed gaps must also move the vpos base, otherwise the next
            // line restores the skipped gap.
            let rendered_y = if let Some(y) = title_body_gap_y {
                y
            } else if compact_endnote_page_title_body_stale_forward {
                // 구분선 없는 큰 미주 block의 page-path에서도 문항 제목 뒤
                // 본문 첫 줄 vpos가 미주 사이만큼 stale-forward로 남는 경우가
                // 있다. 제목 자체는 한컴 위치와 맞으므로 본문부터 순차 gap에
                // 붙이고 후속 vpos 기준도 함께 당긴다.
                y_offset + title_body_gap
            } else if compact_endnote_page_title_mid_stale_gap {
                // 보이는 구분선 + compact 미주의 page-path 중하단 제목은 저장
                // vpos가 이전 미주 사이를 한 번 더 포함한 채 stale-forward로
                // 남을 수 있다. 제목을 현재 단 순차 위치에서 note gap 한 번만
                // 접고, 뒤따르는 같은 미주 본문도 같은 base를 쓰게 한다.
                y_offset - prev_line_spacing_px
            } else if compact_endnote_large_gap_body_stale_forward {
                y_offset
            } else if compact_no_separator_large_title_tail_gap {
                // 구분선 없는 큰 미주 block의 마지막 단에서 새 문항 제목은
                // 저장된 20mm gap 전체보다 조금 위에 놓인다. 직전 풀이의
                // line spacing이 이미 시각 gap을 만들었으므로 약 1/4만 접고,
                // 뒤따르는 같은 미주 본문도 같은 기준으로 흐르게 한다.
                // 제목 문단은 paragraph layout에서 spacing_before가 다시 더해지므로
                // 커서 기준 y에서는 그만큼 미리 빼야 실제 첫 줄이 목표 gap에 놓인다.
                y_offset - prev_line_spacing_px * 0.25 - curr_sb
            } else if hwpx_page_start_stale_forward {
                y_offset
            } else if compact_endnote_new_note_jump {
                bottom_new_note_gap_cap.unwrap_or(y_offset)
            } else if let Some(y) = stale_note_gap_y {
                y
            } else {
                y_offset
            };
            let base_delta_hu = ((end_y - rendered_y) / self.dpi * 7200.0).round() as i32;
            if base_delta_hu != 0 {
                if is_page_path {
                    self.vpos_page_base = Some(base + base_delta_hu);
                } else {
                    self.vpos_lazy_base = Some(base + base_delta_hu);
                }
            }
        }
        let mut result = if compact_endnote_title_bottom_backtrack {
            // 저장 vpos가 제목 top만 frame 안쪽으로 맞추는 경우가 있어,
            // page-tail이 아닌 제목+첫줄 보존 케이스에서는 작은 하단 여유를 둔다.
            let title_tail_pad = if compact_endnote_page_tail_backtrack {
                0.0
            } else {
                4.0
            };
            (end_y - title_tail_pad)
                .max(prev_content_bottom_y)
                .max(self.col_area_y)
        } else if compact_endnote_question_title_tail_backtrack {
            // 빈 spacer 뒤 새 문항 제목은 저장 line_spacing 전체가 아니라
            // 한컴처럼 하단 tail 1줄만 앞 단에 남긴다.
            (y_offset - (y_offset - end_y).min(50.0))
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_question_title_tail_soft_backtrack {
            // 직전 수식 tail 보정으로 hard backtrack 임계값 바로 위에 놓인
            // 제목은 순차 y를 그대로 쓰면 한컴보다 약 1줄 낮아진다.
            // 저장 end_y 전체가 아니라 작은 폭만 당겨 tail과 제목 간격을 맞춘다.
            (y_offset - (y_offset - end_y).min(10.0))
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_question_title_after_tall_tail_backtrack {
            // 하단부 큰 수식/inline 뒤 새 문항 제목은 저장 vpos 전체를 따르면
            // 앞 문항과 겹친다. 한컴처럼 제한적으로만 당겨 뒤 풀이 줄이
            // frame 안에 들어갈 공간을 확보한다.
            let strong_tall_tail_backtrack = measured_prev_content_bottom_y.is_some()
                && prev_line_carries_note_gap
                && seg.line_height >= 2000
                && y_offset - end_y > 80.0;
            let backtrack_limit = if strong_tall_tail_backtrack {
                56.0
            } else {
                30.0
            };
            let prev_floor_pad = if strong_tall_tail_backtrack {
                40.0
            } else {
                12.0
            };
            (y_offset - (y_offset - end_y).min(backtrack_limit) - curr_sb)
                .max(prev_content_bottom_y - curr_sb - prev_floor_pad)
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_question_title_after_tall_mid_backtrack {
            // 중단 하단의 큰 수식 line 뒤 문항 제목은 저장 vpos가 한컴보다
            // 약 한 줄 아래로 밀린 케이스가 있다. 전체 end_y까지 당기면 앞
            // 풀이와 붙으므로, 수식 바닥 기준을 침범하지 않는 선에서만 제한한다.
            (y_offset - (y_offset - end_y).min(41.0) - curr_sb)
                .max(prev_content_bottom_y - curr_sb + 10.0)
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_question_title_after_tall_regular_gap {
            // 기본 7mm compact 미주에서 텍스트가 섞인 큰 수식 line 뒤 문항 제목은
            // 저장된 미주 사이 전체가 아니라 보이는 line bottom 뒤 짧은 gap에 붙는다.
            let target =
                measured_prev_content_bottom_y.unwrap_or(prev_content_bottom_y) + 10.0 - curr_sb;
            if measured_prev_content_bottom_y.is_some() {
                target.max(self.col_area_y)
            } else {
                target.max(self.col_area_y).min(y_offset)
            }
        } else if compact_endnote_question_title_after_tall_upper_flow {
            // 단 상단/중단의 큰 수식 tail 뒤 새 문항 제목은 순차 흐름이 이미
            // PDF/Hancom 위치와 맞는 경우가 있다. 이때 저장 vpos forward를 따르면
            // 같은 단의 뒤 문항까지 누적되어 마지막 풀이 줄이 frame 밖으로 밀린다.
            y_offset
        } else if compact_endnote_zero_gap_title_forward {
            // 구분선 위/미주 사이/구분선 아래가 모두 0에 가까운 미주는 새 문항
            // 제목 앞 저장 vpos gap이 이전 단 재배치 흔적으로 남을 수 있다.
            // 한컴처럼 직전 tail 바로 다음 순차 위치를 따르고, 후속 문항도 같은
            // 기준으로 흐르도록 아래에서 vpos base를 함께 옮긴다.
            y_offset
        } else if compact_endnote_large_empty_spacer_collapse {
            // 큰 미주 사이 문서의 단 하단에서 빈 spacer 문단이 이미 한 줄 높이를
            // 만들었는데, 주입된 line_spacing까지 그대로 소비하면 다음 문항 제목이
            // 한컴/PDF보다 한 note 간격만큼 내려간다. 빈 줄은 유지하고 주입된
            // "미주 사이" trailing만 접어 현재 단의 문항 흐름을 맞춘다.
            (y_offset - prev_line_spacing_px - 4.0)
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_large_between_title_tail_backtrack {
            // 보이는 구분선 + 큰 "미주 사이"에서 직전 spacer의 주입 gap과
            // 저장 vpos가 동시에 존재하면 단 하단 제목/본문이 한 줄가량 내려간다.
            // 저장 vpos가 직전 콘텐츠 바닥을 침범하지 않고 frame 안쪽을 가리키는
            // 경우에는 그 위치를 공통 기준으로 삼아 뒤 본문도 함께 끌어올린다.
            end_y.max(prev_content_floor_y).min(y_offset)
        } else if compact_no_separator_large_title_tail_gap {
            (y_offset - prev_line_spacing_px * 0.25 - curr_sb)
                .max(prev_content_floor_y)
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_zero_gap_text_floor {
            // 0mm 미주의 일반 텍스트 연속 문단은 저장 vpos가 실제 렌더 하단보다
            // 위를 가리키는 경우가 있다. 제목/수식 tail 특수 보정이 아닌 일반
            // 텍스트에서는 직전 TextLine bbox 하단을 최소 시작점으로 보존한다.
            prev_content_floor_y.max(self.col_area_y).min(y_offset)
        } else if hwpx_page_start_stale_forward {
            y_offset
        } else if compact_endnote_large_gap_body_stale_forward {
            // 큰 미주 사이 문서의 본문 중간 텍스트는 저장 vpos가 이전 제목/수식
            // 그룹의 절대 위치 흔적으로 남아 순차 y보다 한 note 간격 이상 앞으로
            // 튈 수 있다. 이 경우 한컴처럼 순차 흐름을 유지하고 base만 보정한다.
            y_offset
        } else if compact_endnote_page_title_body_stale_forward {
            // page-path에서 새 문항 제목은 이미 올바른 tail 위치에 있고, 바로
            // 뒤 본문만 stale-forward vpos로 내려간 경우다. 본문은 제목 뒤
            // 순차 gap으로 붙이고 base를 옮겨 다음 풀이도 같은 기준을 따른다.
            y_offset + title_body_gap
        } else if compact_endnote_page_title_mid_stale_gap {
            // 보이는 구분선 + compact 미주의 중하단 제목은 저장 vpos의
            // stale-forward 간격을 한컴처럼 한 note gap만 접어 배치한다.
            (y_offset - prev_line_spacing_px)
                .max(prev_content_floor_y)
                .max(self.col_area_y)
                .min(y_offset)
        } else if compact_endnote_page_title_default_mid_gap {
            // 직전 줄이 기본 lineSpacing만 들고 있는 page-path 중단 제목은
            // 저장 vpos forward를 그대로 쓰면 `미주 사이`가 과대해진다.
            // 순차 y 뒤에 공식 미주 사이에서 이미 소비된 lineSpacing만 뺀
            // gap을 보존해 한컴/PDF의 중단 제목 위치에 맞춘다.
            let target_gap =
                hwpunit_to_px(self.endnote_between_notes_hu, self.dpi) - prev_line_spacing_px;
            (y_offset + target_gap.max(0.0))
                .max(prev_content_floor_y)
                .max(self.col_area_y)
                .min(end_y)
        } else if compact_endnote_page_tail_backtrack {
            // page-path 하단 tail은 frame 안에 남기기 위해 저장 vpos를 따르되,
            // 이전 텍스트 line의 실제 하단을 깊게 침범하면 문20처럼 본문/수식이
            // 겹친다. 이전 line 하단보다 위로 올라가지 않게 한다.
            end_y.max(prev_content_bottom_y).min(y_offset)
        } else if compact_endnote_text_after_tall_tail_backtrack {
            let mut prev_floor = measured_prev_content_bottom_y
                .map(|y| y + 0.25)
                .unwrap_or(prev_content_bottom_y);
            if para_has_equation_only(prev_para) {
                let inferred_extra =
                    hwpunit_to_px((seg.line_height - seg.line_spacing).max(0), self.dpi).min(1.8);
                let equation_line_floor = prev_content_bottom_y + inferred_extra;
                prev_floor = prev_floor.max(equation_line_floor);
            }
            end_y.max(prev_floor).min(y_offset)
        } else if compact_endnote_question_title_bottom_fit {
            // 큰 미주 사이 문서에서는 새 문항 제목 1줄만 단 하단에 남기고
            // 본문은 다음 단으로 넘기는 저장본이 있다. 이때 stale-forward vpos는
            // 버리되, 순차 y가 frame을 조금 넘으면 제목 visual line-height만큼
            // 하단 안쪽으로 당겨 한컴/PDF처럼 제목 tail을 보존한다. 제목 바로
            // 다음 첫 줄까지 하단 frame에 걸리는 케이스가 있어 여유를 조금 둔다. 반환값은
            // paragraph top이므로 layout에서 다시 더해지는 spacing_before를 뺀다.
            if self.endnote_between_notes_hu == 0
                && para_has_equation_only(prev_para)
                && prev_content_bottom_y > col_bottom - 24.0
            {
                // 0mm 미주에서 작은 equation-only 결과식 바로 뒤 제목은 내부 여유를
                // 더 빼면 결과식과 같은 줄처럼 붙는다. 순차 y를 유지하면 제목의
                // 실제 visual line은 frame 안쪽에서 결과식 뒤에 놓인다.
                y_offset
            } else {
                (col_bottom - current_line_height_px - 11.0 - curr_sb)
                    .max(prev_content_bottom_y - curr_sb - 4.0)
                    .max(self.col_area_y)
                    .min(y_offset)
            }
        } else if compact_endnote_page_no_separator_tail_pullup {
            // 렌더용 lineSeg를 위로 당긴 page-path 한 줄 tail은 저장 end_y가
            // 의도한 위치다. 여기서 순차 y_offset을 고르면 127~129 같은 마지막
            // 번호 묶음이 frame 아래로 잘린다.
            end_y.max(self.col_area_y).min(y_offset)
        } else if compact_endnote_single_line_tail_backtrack {
            end_y
        } else if compact_endnote_title_tail_backtrack {
            // 제목 다음 본문을 너무 위로 당기면 제목 bbox와 첫 줄이 겹친다.
            // 저장 vpos backtrack은 존중하되, 직전 제목의 실제 하단 아래에서만
            // 시작하도록 제한한다.
            let capped = y_offset - (y_offset - end_y).min(16.0);
            let floor = measured_prev_content_bottom_y
                .map(|y| y + 2.0)
                .unwrap_or(self.col_area_y);
            capped.max(floor).min(y_offset)
        } else if let Some(y) = title_body_gap_y {
            y
        } else if self.suppress_large_forward_jump && vpos_rewind && end_y < prev_content_floor_y {
            // compact 미주의 vpos rewind가 직전 줄의 실제 콘텐츠 하단을 침범하면
            // 저장 vpos가 같은 단의 재배치 흔적으로 남은 것이다. 이 경우 순차 y를
            // 유지해야 문항 tail 본문이나 TAC 그림이 앞줄 위로 겹치지 않는다.
            y_offset
        } else if (applied || compact_endnote_deep_backtrack || compact_endnote_safe_vpos_backtrack)
            && !stale_forward
            && !compact_endnote_new_note_jump
            && !compact_endnote_tac_picture_gap
        {
            end_y
        } else if compact_endnote_new_note_jump {
            bottom_new_note_gap_cap.unwrap_or(y_offset)
        } else if let Some(y) = stale_note_gap_y {
            y
        } else {
            y_offset
        };
        // [#6550] 새 문항 제목을 **직전 미주의 콘텐츠 하단 위**로 스냅하면 앞 풀이의
        // 마지막 줄과 겹친다(2023-09 18쪽 문26: 흐름 1044.3 → 저장 1035.9, 앞 줄 하단
        // 1043.9 — `overlap 142.51×11.63px` + `text-overlap` 7건).
        //
        // 저장 vpos 를 따르는 보정들은 프레임 맞춤이 목적이지 겹침 허가가 아니다. 흐름이
        // 이미 앞 콘텐츠 아래에 있을 때만(= 되감김이 아니라 스냅이 만든 침범일 때만)
        // 바닥을 둔다. 흐름 자체가 위에 있으면 종전대로 둔다 — 그건 다른 축이다.
        //
        // ⚠ 범위는 **기본 「미주 사이」(≤1984HU) + 보통 높이 tail** 로만 좁힌다.
        //   · 큰 미주 사이(5669HU)는 spacer 가 만든 trailing y 를 일부러 접는다
        //     (`..._large_empty_spacer_collapses_trailing_gap_at_bottom`)
        //   · 큰 수식/inline tail(lh>1500) 뒤 제목은 제한 폭 backtrack 이 계약이다
        //     (`..._question_title_after_tall_tail_limited_backtrack`, #1284 PDF 핀)
        if self.suppress_large_forward_jump
            && current_is_endnote_title
            && !follows_tall_inline_item
            && self.endnote_between_notes_hu > 0
            && self.endnote_between_notes_hu <= super::layout::ENDNOTE_BETWEEN_NOTES_BASE_FLOW_HU
            && result < prev_content_floor_y
            && y_offset >= prev_content_floor_y
        {
            result = prev_content_floor_y.min(y_offset);
        }
        if compact_endnote_zero_gap_text_floor && result > end_y + 0.5 {
            self.shift_vpos_base_for_rendered_delta(result - end_y);
        }
        if compact_endnote_text_after_lazy_tall_equation_floor {
            let stored_continuous = curr_first_vpos == Some(prev_vpos_end)
                && !prev_para.stored_text_partition_is_dirty()
                && seg.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0
                && paragraphs.get(item_para).is_some_and(|paragraph| {
                    !paragraph.stored_text_partition_is_dirty()
                        && paragraph.line_segs.first().is_some_and(|line| {
                            line.tag & crate::model::paragraph::LineSeg::TAG_IMPLEMENTATION_PROPERTY
                                == 0
                        })
                });
            if let Some(bottom) = measured_prev_content_bottom_y.filter(|_| stored_continuous) {
                // 저장 다음 원점이 실제 수식 줄+간격의 끝과 연속이면 그 점유
                // 결과를 소비한다. 수식 높이의 임의 비율을 빈 밴드로 더하지 않는다.
                result = result.max(bottom);
            } else {
                let inferred_extra =
                    hwpunit_to_px((seg.line_height - seg.line_spacing).max(0), self.dpi) * 0.4;
                result = result.max(prev_content_bottom_y + inferred_extra + 0.25);
            }
        }
        let compact_endnote_zero_gap_title_boundary_applied = if self.suppress_large_forward_jump
            && current_is_endnote_title
            && self.endnote_between_notes_hu == 0
            && !vpos_rewind
            && seg.line_spacing > 0
            && seg.line_spacing <= 800
            && (result - y_offset).abs() <= 0.5
            && !compact_endnote_zero_gap_title_forward
            && !compact_endnote_title_bottom_backtrack
            && !compact_endnote_question_title_bottom_fit
            && !compact_endnote_question_title_tail_backtrack
            && !compact_endnote_question_title_tail_soft_backtrack
            && !compact_endnote_question_title_after_tall_tail_backtrack
            && !compact_endnote_question_title_after_tall_mid_backtrack
            && !compact_endnote_question_title_after_tall_regular_gap
            && !compact_endnote_question_title_after_tall_upper_flow
        {
            // 0/0/0 미주의 새 문항 경계에서는 저장 vpos가 직전 문단의
            // trailing line_spacing을 포함한 연속값으로 기록될 수 있다. 미주
            // 사이가 0mm이면 한컴은 이 trailing을 다음 문항 제목 앞 공백으로
            // 쓰지 않으므로, 실제 콘텐츠 하단을 침범하지 않는 범위에서 한
            // 줄 gap을 접고 후속 vpos 기준도 함께 이동한다.
            let compacted = (result - prev_line_spacing_px)
                .max(prev_content_floor_y)
                .max(self.col_area_y);
            if compacted < result - 0.5 {
                result = compacted;
                true
            } else {
                false
            }
        } else {
            false
        };
        if (compact_endnote_title_bottom_backtrack
            || compact_endnote_question_title_after_tall_regular_gap
            || compact_endnote_question_title_after_tall_upper_flow
            || compact_endnote_zero_gap_title_forward
            || compact_endnote_zero_gap_title_boundary_applied
            || compact_endnote_page_title_default_mid_gap)
            && result < end_y - 0.5
        {
            let base_delta_hu = ((end_y - result) / self.dpi * 7200.0).round() as i32;
            if base_delta_hu != 0 {
                if is_page_path {
                    self.vpos_page_base = Some(base + base_delta_hu);
                } else {
                    self.vpos_lazy_base = Some(base + base_delta_hu);
                }
            }
        }
        if compact_endnote_question_title_after_tall_mid_backtrack && result > end_y + 0.5 {
            let base_delta_hu = ((end_y - result) / self.dpi * 7200.0).round() as i32;
            if base_delta_hu != 0 {
                if is_page_path {
                    self.vpos_page_base = Some(base + base_delta_hu);
                } else {
                    self.vpos_lazy_base = Some(base + base_delta_hu);
                }
            }
        }
        self.last_compacted_endnote_title_gap = compact_endnote_new_note_jump
            && bottom_new_note_gap_cap
                .map(|cap| end_y - cap > 8.0)
                .unwrap_or(false)
            || compact_no_separator_large_title_tail_gap;
        if std::env::var("RHWP_VPOS_DEBUG").is_ok() {
            if current_is_endnote_title {
                eprintln!(
                    "VPOS_NOTE_GAP pi={} gap_hu={} prev_content={:?} prev_flow={:?} gap_cap={:?} tall={} carries_gap={} title_regular={} title_upper={} page_mid={} page_default={}",
                    item_para, self.endnote_between_notes_hu, measured_prev_content_bottom_y,
                    self.prev_item_flow_line_bottom_y, bottom_new_note_gap_cap,
                    follows_tall_inline_item, prev_line_carries_note_gap,
                    compact_endnote_question_title_after_tall_regular_gap,
                    compact_endnote_question_title_after_tall_upper_flow,
                    compact_endnote_page_title_mid_stale_gap,
                    compact_endnote_page_title_default_mid_gap,
                );
            }
            let path = if is_page_path { "page" } else { "lazy" };
            eprintln!(
                "VPOS_CORR: path={} pi={} prev_pi={} prev_vpos={} prev_lh={} prev_ls={} vpos_end={} base={} col_y={:.17} y_in={:.17} end_y={:.17} result={:.17} stale_forward={} large_gap_body_stale={} current_title={} title_bottom={} page_tail={} single_tail={} zero_gap_title={} compact_new_note={} compact_stale_note_gap={} compact_tac_pic_gap={} compact_bottom_rewind={} compact_deep_backtrack={} compact_safe_backtrack={} applied={}",
                path, item_para, prev_pi, seg.vertical_pos, seg.line_height, seg.line_spacing,
                vpos_end, base, self.col_area_y, y_offset, end_y, result, stale_forward,
                compact_endnote_large_gap_body_stale_forward, current_is_endnote_title, compact_endnote_title_bottom_backtrack,
                compact_endnote_page_tail_backtrack,
                compact_endnote_single_line_tail_backtrack,
                compact_endnote_zero_gap_title_forward,
                compact_endnote_new_note_jump, compact_endnote_stale_note_gap,
                compact_endnote_tac_picture_gap, compact_endnote_bottom_rewind,
                compact_endnote_deep_backtrack, compact_endnote_safe_vpos_backtrack,
                (applied || compact_endnote_deep_backtrack || compact_endnote_safe_vpos_backtrack) && !stale_forward && !compact_endnote_new_note_jump && !compact_endnote_tac_picture_gap,
            );
        }
        let prev_is_multiline = prev_para.line_segs.len() > 1;
        let stored_gap_px = result - y_offset;
        // [Task #1256/#1261] 단일 줄 prev(빈 separator)로 끝나는 미주 제목 경계: y_offset 은
        // typeset 이 주입한 between-notes trailing 을 이미 포함한다. applied/
        // safe_vpos_backtrack 이 그보다 위로 당기는 경우뿐 아니라, page-path vpos 가 소폭
        // 아래로 미는 경우도 y_offset 을 유지해야 한다. 그렇지 않으면 `미주 사이`가 두 번
        // 적용되어 다음 제목들이 아래로 누적 밀린다(미주사이20 p10 문10→문12 overflow).
        // 기준을 y_offset 으로 유지하고, 차이만큼 활성 vpos base 를 이동해 후속 미주 항목이
        // 동일 기준을 따르게 한다. 다줄 prev(문22)는 y_offset 이 between-notes 를 못 가지는
        // 별개 경로라 아래 #1246 rescue(+prev_ls)가 담당.
        let injected_between_notes =
            self.endnote_between_notes_hu > 0 && seg.line_spacing >= self.endnote_between_notes_hu;
        // 실제 마지막 줄 점유 뒤의 간격이 순차 흐름에 이미 예약됐으면,
        // 새 미주 저장 원점의 전방 이동으로 같은 간격을 다시 소비하지 않는다.
        let measured_gap_already_reserved = measured_prev_occupied_end_y.is_some_and(|bottom| {
            super::endnote_spacing::gap_is_reserved(y_offset, bottom, prev_line_spacing_px)
        });
        let legacy_single_line_gap_keep = !compact_endnote_question_title_tail_backtrack
            && !compact_endnote_question_title_tail_soft_backtrack
            && !compact_endnote_question_title_after_tall_tail_backtrack
            && !compact_endnote_question_title_after_tall_mid_backtrack
            && !compact_endnote_question_title_after_tall_regular_gap
            && !compact_endnote_title_bottom_backtrack
            && !compact_endnote_large_empty_spacer_collapse
            && !compact_endnote_large_between_title_tail_backtrack
            && !compact_no_separator_large_title_tail_gap
            && !prev_is_multiline
            && (stored_gap_px < -0.5
                || (stored_gap_px > 0.5
                    && (self.endnote_between_notes_hu > 3000 || measured_gap_already_reserved)));
        if injected_between_notes
            && compact_endnote_question_title
            && !vpos_rewind
            && (measured_gap_already_reserved || legacy_single_line_gap_keep)
        {
            // 실제 점유 뒤에 설정 간격이 이미 있으면 하단 backtrack도 그
            // 간격을 없앨 근거가 아니다. fit과 paint가 같은 순차 원점을 쓴다.
            // 최종 제목 원점을 보존할 때 기준은 기존 저장 목표 end_y다.
            // 중간 result에 더한 gap 보정은 이 반환에서 쓰지 않으므로,
            // 그것을 기준으로 base를 덮어쓰면 뒤 본문의 상대 간격이 줄어든다.
            let delta_hu = ((end_y - y_offset) / self.dpi * 7200.0).round() as i32;
            if delta_hu != 0 {
                if is_page_path {
                    self.vpos_page_base = Some(base + delta_hu);
                } else {
                    self.vpos_lazy_base = Some(base + delta_hu);
                }
            }
            return y_offset;
        }
        // [Task #1246] 미주 사이 min-gap: 새 미주 제목이 forward 흐름인데 between-notes 간격을
        // 확보하지 못하면(다줄 풀이로 끝나는 미주 → 직전 다줄 문단 마지막 줄 trailing 이 render
        // 에서 누락 → gap≈0, 문22) 직전 줄간격(주입된 between_notes)만큼 끌어올린다.
        // - 다줄 prev 한정: 단일줄 prev 는 위 #1256 분기가 y_offset(주입 7mm 포함) 유지로 처리.
        // - 이미 충분한 간격(result >= y_offset + prev_ls, 3-09월 문15 등)은 무변경(max 의미).
        // - backtrack/rewind 류(result < y_offset)는 위 분기가 의도 선택한 값이므로 제외.
        // #1238 render-클램프가 침범하던 #1209 safe-vpos-backtrack 과 양립(여기선 forward 만).
        // 핵심: stored vpos 가 gap 을 거의 안 주는 경우(≈0)만 보정한다. 다줄 풀이로 끝나는 미주의
        // 마지막 줄 trailing 이 render 에서 누락되어 gap≈0 이 된 케이스(문22)가 대상.
        // stored vpos 가 의도적으로 작은 gap(예: 문13 ~12px)을 인코딩한 경우는 존중(over-lift 방지).
        if self.endnote_between_notes_hu > 0
            && compact_endnote_question_title
            && !vpos_rewind
            && prev_is_multiline
            && (-0.5..4.0).contains(&stored_gap_px)
        {
            return y_offset + prev_line_spacing_px;
        }
        // [Task #1811] 합성 seg(구현 속성 bit31) 뒤의 저장 vpos 는 **전방 이동의 근거가
        // 아니다**. 되감기(result < y_offset)는 sequential 이 앞서 나갔을 때의 재동기화로
        // 허용한다.
        //
        // 종전 v2 는 48px 넘는 전방 점프를 "구조적 재앵커"로 허용했다(seoul_1006 HWP↔HWPX
        // 왕복 쪽나눔 수렴 근거). 그러나 합성 줄 문단은 저장 당시와 내용·줄 수가 달라졌다는
        // 표지이고(가림 처리한 결재문서는 가린 문단에 bit31 을 달고 줄 수가 줄어든다), 그
        // 뒤 문단의 저장 vpos 는 옛 줄 수로 잰 좌표다. 한/글은 이 간격을 재현하지 않는다 —
        // 정본 PDF 대조 240문서에서 크기 제한을 없애면 개선 3쪽(53.5→0.7, 240.9→3.2,
        // 295.0→7.2px)·악화 0, 36457457 은 8→7쪽으로 한/글 쪽수와 같아진다.
        if synthetic_prev_seg && result > y_offset + 0.5 {
            // 거부한 합성 줄의 원점을 다음 저장 문단으로 넘기지 않는다.
            // 현재 줄은 실제 흐름에 남았으므로 같은 사다리의 후속 상대 좌표도
            // 이 원점에서 이어져야 한다. 커서만 되돌리면 다음 저장 줄에서
            // 방금 거부한 전방 간격이 다시 적용된다.
            self.shift_vpos_base_for_rendered_backtrack(result - y_offset);
            if std::env::var("RHWP_VPOS_DEBUG").is_ok() {
                eprintln!(
                    "VPOS_SYNTH_FWD_SKIP: pi={} prev_pi={} y_in={:.2} result={:.2}",
                    item_para, prev_pi, y_offset, result,
                );
            }
            return y_offset;
        }
        // [편집 세션] 전방 점프 목적지가 쪽 말미(하단 15%)면 낡은 저장 좌표다 —
        // fresh 흐름을 유지한다. 같은 쪽 소폭 재동기화(상단·중단)는 종전대로.
        if self.session_edited
            && result > y_offset
            && result > self.col_area_y + self.col_area_height * 0.85
        {
            return y_offset;
        }
        result
    }

    fn rebase_after_empty_prefix(
        &mut self,
        y: f64,
        current: usize,
        previous: usize,
        paragraphs: &[Paragraph],
    ) -> bool {
        let Some(para) = paragraphs.get(current) else {
            return false;
        };
        if current != previous + 1
            || para.column_type != crate::model::paragraph::ColumnBreakType::None
            || para
                .line_segs
                .first()
                .is_none_or(|seg| seg.vertical_pos != 0)
            || y <= self.col_anchor_y
        {
            return false;
        }
        let Some(origin) = self
            .stored_column_origin
            .map(|(raw, _)| raw)
            .or(self.vpos_page_base)
            .or(self.vpos_lazy_base)
            .filter(|raw| *raw > 0)
        else {
            return false;
        };
        let begins_at_empty = paragraphs[..current]
            .iter()
            .rev()
            .take_while(|p| {
                p.text.is_empty()
                    && p.controls.is_empty()
                    && p.column_type == crate::model::paragraph::ColumnBreakType::None
            })
            .any(|p| {
                p.line_segs
                    .first()
                    .is_some_and(|seg| seg.vertical_pos == origin)
            });
        if !begins_at_empty {
            return false;
        }
        let offset = crate::renderer::px_to_hwpunit(y - self.col_anchor_y, self.dpi);
        self.vpos_page_base = Some(-offset);
        self.vpos_lazy_base = None;
        true
    }

    /// 활성 base 로 사영한 저장-사다리 기대 y. 렌더 점프가 사다리에 이미
    /// 인코딩된 공간인지(기준점 이동 불필요) 가리는 데 쓴다 (#4533 2135039).
    pub(crate) fn ladder_expected_y(&self, col_y: f64, first_vpos: i32) -> Option<f64> {
        let base = self.vpos_page_base.or(self.vpos_lazy_base)?;
        Some(col_y + hwpunit_to_px(first_vpos - base, self.dpi))
    }

    /// 이미 계산된 vpos 기준 y보다 실제 렌더 y를 아래로 밀었을 때, 후속 항목도
    /// 같은 시각 기준을 따르도록 활성 vpos base를 반대로 이동한다.
    pub(crate) fn shift_vpos_base_for_rendered_delta(&mut self, delta_px: f64) {
        if delta_px <= 0.0 {
            return;
        }
        let delta_hu = (delta_px / self.dpi * 7200.0).round() as i32;
        if delta_hu <= 0 {
            return;
        }
        if let Some(base) = self.vpos_page_base {
            self.vpos_page_base = Some(base - delta_hu);
        } else if let Some(base) = self.vpos_lazy_base {
            self.vpos_lazy_base = Some(base - delta_hu);
        }
    }

    /// [#4613 · #4599 밴드-플로우] 렌더가 저장 사다리보다 `delta_px` 만큼 **뒤로**(위로) 배치된
    /// 경우의 역보정 — 낡은 사다리 전방 스냅을 기각해 줄을 자리차지 표 위 틈에 남길 때,
    /// 후속 문단의 사다리 목표가 함께 위로 이동해야 상대 간격이 유지된다.
    /// `shift_vpos_base_for_rendered_delta`(전방 밀림, base 감소)의 대칭이다.
    pub(crate) fn shift_vpos_base_for_rendered_backtrack(&mut self, delta_px: f64) {
        if delta_px <= 0.0 {
            return;
        }
        let delta_hu = (delta_px / self.dpi * 7200.0).round() as i32;
        if delta_hu <= 0 {
            return;
        }
        if let Some(base) = self.vpos_page_base {
            self.vpos_page_base = Some(base + delta_hu);
        } else if let Some(base) = self.vpos_lazy_base {
            self.vpos_lazy_base = Some(base + delta_hu);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::paragraph::LineSeg;
    use crate::renderer::style_resolver::ResolvedParaStyle;

    /// [#4626] 글자처럼 취급하는 도형 하나만 든 문단.
    fn tac_shape_para(text: &str) -> Paragraph {
        use crate::model::shape::{RectangleShape, ShapeObject};
        let mut rect = RectangleShape::default();
        rect.common.treat_as_char = true;
        Paragraph {
            text: text.to_string(),
            controls: vec![Control::Shape(Box::new(ShapeObject::Rectangle(rect)))],
            ..Default::default()
        }
    }

    /// 도형만 있는 문단의 **표준형**은 `text == "\u{FFFC}"` 다. 종전 판정은
    /// `trim()` 이 개체 대체 문자를 공백으로 보지 않아 여기서 `false` 를 냈고,
    /// `typeset.rs` 의 동명 술어(`true`)와 정면으로 어긋났다.
    #[test]
    fn object_replacement_only_para_is_treat_as_char_picture_only() {
        assert!(
            para_is_treat_as_char_picture_only(&tac_shape_para("\u{FFFC}")),
            "개체 대체 문자만 있는 문단을 도형 전용으로 보지 않았다"
        );
    }

    /// 같은 파일의 형제 술어와 같은 답을 내야 한다 — 빈 텍스트 판정의 단일 정의.
    #[test]
    fn empty_and_control_only_paras_agree_with_visible_text_helper() {
        for text in ["", "\u{FFFC}", "\u{FFFC}\u{FFFC}", "\u{000D}"] {
            let para = tac_shape_para(text);
            assert_eq!(
                para_is_treat_as_char_picture_only(&para),
                !para_has_visible_text(&para),
                "text={text:?} 에서 빈 텍스트 판정이 갈렸다"
            );
        }
    }

    /// 실제 글자가 있으면 도형 전용이 아니다.
    #[test]
    fn para_with_real_text_is_not_treat_as_char_picture_only() {
        assert!(!para_is_treat_as_char_picture_only(&tac_shape_para("가")));
        assert!(!para_is_treat_as_char_picture_only(&tac_shape_para(
            "\u{FFFC}가"
        )));
    }

    /// 도형이 없으면 텍스트가 비어도 도형 전용이 아니다.
    #[test]
    fn para_without_treat_as_char_shape_is_not_picture_only() {
        let para = Paragraph {
            text: "\u{FFFC}".to_string(),
            ..Default::default()
        };
        assert!(!para_is_treat_as_char_picture_only(&para));
    }

    // DPI=96 → 75 HWPUNIT = 1px (1 inch = 7200 HU = 96px). 손계산 정합용.
    const DPI: f64 = 96.0;
    const COL_Y: f64 = 100.0;
    const COL_H: f64 = 900.0;

    fn para(para_shape_id: u16, vpos: i32, lh: i32, ls: i32, seg_w: i32) -> Paragraph {
        Paragraph {
            para_shape_id,
            line_segs: vec![LineSeg {
                vertical_pos: vpos,
                line_height: lh,
                line_spacing: ls,
                segment_width: seg_w,
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    fn styles(spacing_before: f64) -> ResolvedStyleSet {
        ResolvedStyleSet {
            hwp3_variant: false,
            hft_ascii_halfwidth: false,
            para_styles: vec![ResolvedParaStyle {
                spacing_before,
                ..Default::default()
            }],
            ..Default::default()
        }
    }

    fn cursor(page_base: Option<i32>) -> HeightCursor {
        HeightCursor::new(
            DPI, COL_Y, COL_H, COL_Y, page_base, false, false, false, false,
        )
    }

    fn hwp3_origin_cursor(page_base: Option<i32>) -> HeightCursor {
        HeightCursor::new(
            DPI, COL_Y, COL_H, COL_Y, page_base, true, false, false, false,
        )
    }

    /// 미주 첫 문단(새 문항 제목)으로 표시한다 — 렌더의 `endnote_note_first_paras` 와 같은 소유 경계.
    fn mark_note_first(c: &mut HeightCursor, para_index: usize) {
        std::sync::Arc::make_mut(&mut c.endnote_note_first_paras).insert(para_index);
    }

    fn compact_endnote_cursor(page_base: Option<i32>) -> HeightCursor {
        HeightCursor::new(
            DPI, COL_Y, COL_H, COL_Y, page_base, false, false, false, true,
        )
    }

    /// 직전 문단이 없으면 보정하지 않는다.
    #[test]
    fn no_prev_para_passthrough() {
        let mut c = cursor(Some(0));
        let ps = vec![para(0, 2000, 1000, 0, 5000)];
        assert_eq!(c.vpos_adjust(90.0, 0, &ps, &styles(0.0)), 90.0);
    }

    /// 같은 문단(item==prev)이면 보정하지 않는다.
    #[test]
    fn same_para_passthrough() {
        let mut c = cursor(Some(0));
        c.prev_layout_para = Some(1);
        let ps = vec![para(0, 1000, 1000, 0, 5000), para(0, 2000, 1000, 0, 5000)];
        assert_eq!(c.vpos_adjust(123.0, 1, &ps, &styles(0.0)), 123.0);
    }

    /// 직전 항목이 분할 표였으면(#991) sequential 신뢰 — 보정 안 함.
    #[test]
    fn partial_table_bypass() {
        let mut c = cursor(Some(0));
        c.prev_layout_para = Some(0);
        c.prev_item_was_partial_table = true;
        let ps = vec![para(0, 1000, 1000, 0, 5000), para(0, 2000, 1000, 0, 5000)];
        assert_eq!(c.vpos_adjust(90.0, 1, &ps, &styles(0.0)), 90.0);
    }

    /// 직전 문단의 마지막 seg vpos==0(reset, prev_pi>0)이면 보정 안 함.
    #[test]
    fn vpos_reset_bypass() {
        let mut c = cursor(Some(0));
        c.prev_layout_para = Some(2);
        let ps = vec![
            para(0, 0, 0, 0, 0),
            para(0, 0, 0, 0, 0),
            para(0, 0, 1000, 0, 5000), // prev seg vpos==0, prev_pi=2>0
        ];
        // item_para=1: get(1)=일반. prev=2 의 seg.vpos==0 → bypass.
        assert_eq!(c.vpos_adjust(90.0, 1, &ps, &styles(0.0)), 90.0);
    }

    /// page_path: end_y = col_anchor_y + (vpos_end - base)*scale, 백워드 허용 내 적용.
    #[test]
    fn page_path_applied() {
        let mut c = cursor(Some(0)); // base=0, page_path
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 1000, 1000, 0, 5000), // prev: vpos_end=2000
            para(0, 2000, 1000, 0, 5000), // curr first vpos=2000 > 1000 → vpos_end=2000
        ];
        // raw_end_y = 100 + (2000-0)/75 = 126.6667, sb=0
        let got = c.vpos_adjust(90.0, 1, &ps, &styles(0.0));
        assert!((got - (100.0 + 2000.0 / 75.0)).abs() < 1e-6, "got={got}");
    }

    /// page_path + sb 사전 차감(#643): end_y 에서 spacing_before(px) 만큼 당겨짐.
    #[test]
    fn page_path_sb_prededuct() {
        let mut c = cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![para(0, 1000, 1000, 0, 5000), para(0, 2000, 1000, 0, 5000)];
        // curr_sb=10px → end_y = max(126.6667 - 10, col_y=100) = 116.6667
        let got = c.vpos_adjust(90.0, 1, &ps, &styles(10.0));
        assert!(
            (got - (100.0 + 2000.0 / 75.0 - 10.0)).abs() < 1e-6,
            "got={got}"
        );
    }

    /// HWP3-origin 흐름에서는 #1116 p3 3mm 격자 정합을 위해 sb 사전 차감을 생략한다.
    #[test]
    fn hwp3_origin_page_path_keeps_spacing_before_in_vpos() {
        let mut c = hwp3_origin_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![para(0, 1000, 1000, 0, 5000), para(0, 2000, 1000, 0, 5000)];
        let got = c.vpos_adjust(90.0, 1, &ps, &styles(10.0));
        assert!((got - (100.0 + 2000.0 / 75.0)).abs() < 1e-6, "got={got}");
    }

    /// lazy_path: page_base 없음 → sequential y 에서 lazy_base 역산, 이후 적용.
    #[test]
    fn lazy_path_applied_and_base_set() {
        let mut c = cursor(None); // page_base/lazy_base 모두 None
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 1000, 1000, 0, 5000), // prev_vpos_end=2000
            para(0, 2200, 1000, 0, 5000), // curr vpos=2200>1000 → vpos_end=2200
        ];
        // y_in=120: y_delta_hu=(120-100)*75=1500, lazy_base=2000-1500=500
        // anchor=col_y=100 (lazy): raw_end_y=100+(2200-500)/75=122.6667
        let got = c.vpos_adjust(120.0, 1, &ps, &styles(0.0));
        assert_eq!(c.vpos_lazy_base, Some(500));
        assert!((got - (100.0 + 1700.0 / 75.0)).abs() < 1e-6, "got={got}");

        // 실제 점유 끝116px와 순차 위치124px가 저장 간격8px 소비를 입증한다.
        let mut c = cursor(None);
        c.suppress_hwpx_stale_forward = true;
        c.prev_layout_para = Some(0);
        c.prev_item_flow_line_bottom_y = Some(116.0);
        c.stored_column_origin = Some((800, COL_Y));
        let ps = vec![para(0, 1000, 1000, 600, 5000), para(0, 2600, 1000, 0, 5000)];
        let got = c.vpos_adjust(124.0, 1, &ps, &styles(0.0));
        assert_eq!(c.vpos_lazy_base, Some(800));
        assert!((got - 124.0).abs() < 1e-6);

        // 실제 저장 줄에서 소비·연속성 근거가 없으면 누락 간격 bridge를 유지한다.
        // 합성 줄은 절대 저장 좌표가 아니다. #6101의 전체 시각 대조로 확인한
        // 재조판→저장 빈 줄 및 재조판 본문의 순차 흐름을 따로 검증한다.
        for case in 0..8 {
            let mut c = cursor(None);
            c.suppress_hwpx_stale_forward = true;
            c.prev_layout_para = Some(0);
            c.prev_item_flow_line_bottom_y = Some(116.0);
            c.stored_column_origin = Some((800, COL_Y));
            let mut ps = vec![para(0, 1000, 1000, 600, 5000), para(0, 2600, 1000, 0, 5000)];
            match case {
                0 => c.prev_item_flow_line_bottom_y = None,
                1 => c.prev_item_flow_line_bottom_y = Some(123.0),
                2 => ps[1].line_segs[0].vertical_pos = 2700,
                3 => ps[0].line_segs[0].tag |= LineSeg::TAG_IMPLEMENTATION_PROPERTY,
                4 => ps[1].line_segs[0].tag |= LineSeg::TAG_IMPLEMENTATION_PROPERTY,
                5 => c.session_edited = true,
                6 => c.stored_column_origin = None,
                7 => c.stored_column_origin = Some((500, COL_Y)),
                _ => unreachable!(),
            }
            let got = c.vpos_adjust(124.0, 1, &ps, &styles(0.0));
            let expected = match case {
                // 저장 빈 줄 2600HU를 현재 124px에 연결한다:
                // 2600-(124-100)*75=800HU. 합성 이전 줄의 간격은 더하지 않는다.
                3 => Some(800),
                // 현재 줄도 재조판이면 저장 기준을 만들지 않고 실제 흐름을 유지한다.
                4 => None,
                _ => Some(200),
            };
            assert_eq!(c.vpos_lazy_base, expected, "저장/재조판 경로{case}");
            if matches!(case, 3 | 4) {
                assert!((got - 124.0).abs() < 1e-6, "순차 흐름 경로{case}: {got}");
            }
        }
    }

    /// 백워드 클램프: end_y 가 y_offset-8px 미만이면 보정 거부(원 y 유지).
    #[test]
    fn backward_clamp_rejected() {
        let mut c = cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 50, 1000, 0, 5000),
            para(0, 100, 1000, 0, 5000), // curr vpos=100 → end_y≈101.33
        ];
        // y_in=500: end_y=100+100/75=101.33 < 500-8=492 → 미적용
        assert_eq!(c.vpos_adjust(500.0, 1, &ps, &styles(0.0)), 500.0);
    }

    /// Compact 미주 하단 rewind가 직전 콘텐츠 하단을 침범하지 않으면 저장 vpos를 존중한다.
    #[test]
    fn compact_endnote_bottom_rewind_uses_current_vpos_when_safe() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 55350, 900, 12000, 5000), // prev_content_bottom≈690, rewind → y=700
            para(0, 45000, 900, 0, 5000),     // rewind → y=700
        ];

        let got = c.vpos_adjust(850.0, 1, &ps, &styles(0.0));
        assert!((got - 700.0).abs() < 1e-6, "got={got}");
    }

    /// Compact 미주 하단 rewind가 직전 콘텐츠 하단 위로 올라가면 순차 y를 유지한다.
    #[test]
    fn compact_endnote_bottom_rewind_skips_when_crossing_previous_content() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 55350, 900, 0, 5000), // prev_content_bottom=y_offset
            para(0, 45000, 900, 0, 5000), // rewind → y=700, but crosses previous content
        ];

        let got = c.vpos_adjust(850.0, 1, &ps, &styles(0.0));
        assert!((got - 850.0).abs() < 1e-6, "got={got}");
    }

    /// 같은 compact 미주 되감김이라도 단 하단부가 아니면 기존 순차 흐름을 유지한다.
    #[test]
    fn compact_endnote_rewind_above_bottom_keeps_previous_vpos() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 44100, 900, 0, 5000), // prev_vpos_end=45000 → y=700
            para(0, 37500, 900, 0, 5000), // rewind → y=600, but above bottom band
        ];

        let got = c.vpos_adjust(700.0, 1, &ps, &styles(0.0));
        assert!((got - 700.0).abs() < 1e-6, "got={got}");
    }

    /// Compact 미주 하단에서 reset 없는 VPOS 후퇴가 80px 이내면 overflow 완화를 위해 적용한다.
    #[test]
    fn compact_endnote_deep_backtrack_uses_vpos_near_column_bottom() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 71900, 900, 6000, 5000), // prev_vpos_end=78800; spacing 안에서만 backtrack 허용
            para(0, 71950, 900, 0, 5000),    // curr advances, but VPOS target is behind y
        ];

        let got = c.vpos_adjust(980.0, 1, &ps, &styles(0.0));
        assert!(
            (got - (100.0 + (71950.0 - 6800.0) / 75.0)).abs() < 1e-6,
            "got={got}"
        );
    }

    /// Page-base가 이미 확정된 흐름에서는 같은 보정이 직전 줄과 겹칠 수 있어 적용하지 않는다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_page_path() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![para(0, 65000, 2700, 0, 5000), para(0, 66000, 900, 0, 5000)];

        let got = c.vpos_adjust(1005.0, 1, &ps, &styles(0.0));
        assert!((got - 1005.0).abs() < 1e-6, "got={got}");
    }

    /// 수식처럼 tall inline 항목 뒤에서는 되감김이 수식 bbox와 다음 문단을 겹치게 만든다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_after_tall_line() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let ps = vec![para(0, 70100, 2200, 0, 5000), para(0, 70150, 900, 0, 5000)];

        let got = c.vpos_adjust(1030.0, 1, &ps, &styles(0.0));
        assert!((got - 1030.0).abs() < 1e-6, "got={got}");
    }

    /// 새 미주 제목은 미주 사이 간격을 보존해야 하므로 deep backtrack 대상이 아니다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_new_note_title() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![para(0, 70100, 900, 0, 5000), para(0, 70150, 900, 0, 5000)];
        ps[1].text = "문11)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(1030.0, 1, &ps, &styles(0.0));
        assert!((got - 1030.0).abs() < 1e-6, "got={got}");
    }

    /// 실텍스트 뒤에서 직전 문단의 line spacing 안으로만 당겨지는 새 미주 제목은
    /// 하단 overflow 완화를 위해 허용한다.
    #[test]
    fn compact_endnote_deep_backtrack_allows_safe_new_note_title() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 70100, 900, 6000, 5000),
            para(0, 76100, 900, 0, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문30)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(980.0, 1, &ps, &styles(0.0));
        assert!(got < 980.0, "got={got}");
    }

    /// page-path 하단의 새 미주 제목도 저장 vpos가 32px 이내 위쪽을 가리키면
    /// 제목을 그 위치 근처로 되돌리되, 첫 본문 line과 겹치지 않도록 4px 여유를 둔다.
    #[test]
    fn compact_endnote_page_path_title_bottom_backtrack_allows_safe_title() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 61000, 2070, 1984, 5000),
            para(0, 62000, 900, 452, 5000),
        ];
        ps[0].text = "구하는 확률은".to_string();
        ps[1].text = "문29)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(946.0, 1, &ps, &styles(0.0));
        let expected = 100.0 + 62000.0 / 75.0 - 4.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// page-path 하단 tail backtrack은 frame 안에 남아야 하지만 직전 줄의
    /// 실제 콘텐츠 하단을 깊게 침범하면 문20처럼 본문 line과 다음 수식 line이 겹친다.
    #[test]
    fn compact_endnote_page_tail_backtrack_keeps_previous_content_bottom() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 65000, 900, 452, 5000),
            para(0, 66000, 900, 452, 5000),
        ];

        let got = c.vpos_adjust(1000.0, 1, &ps, &styles(0.0));
        let expected = 1000.0 - 452.0 / 75.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// page-path 하단에서 tall inline 뒤의 일반 텍스트도 저장 vpos가 안전한
    /// 위치를 가리키면 직전 콘텐츠 하단까지 당겨 뒤 수식 line의 공간을 만든다.
    #[test]
    fn compact_endnote_page_tail_text_after_tall_line_backtracks_to_previous_bottom() {
        let mut c = compact_endnote_cursor(Some(0));
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 65000, 1650, 452, 5000),
            para(0, 66000, 900, 452, 5000),
        ];
        ps[1].text = "이므로 삼차식".to_string();

        let got = c.vpos_adjust(1000.0, 1, &ps, &styles(0.0));
        let expected = 1000.0 - 452.0 / 75.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 빈 spacer 문단 뒤의 새 미주 제목은 빈 문단이 만든 간격을 다시 되감으면 안 된다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_title_after_empty_spacer() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 70100, 900, 6000, 5000),
            para(0, 70150, 900, 0, 5000),
        ];
        ps[1].text = "문23)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(980.0, 1, &ps, &styles(0.0));

        assert!((got - 980.0).abs() < 1e-6, "got={got}");
    }

    /// 큰 미주 사이가 빈 spacer의 trailing line_spacing에 주입되어 있고 단 하단에서
    /// 다음 문항 제목의 저장 vpos가 stale-forward이면, 빈 줄 높이는 유지하되
    /// 주입된 trailing만 접어 한컴/PDF의 문항 흐름을 따른다.
    #[test]
    fn compact_endnote_large_empty_spacer_collapses_trailing_gap_at_bottom() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(622_317);
        c.endnote_between_notes_hu = 5669;
        let prev = para(0, 681_069, 900, 5669, 5000);
        let mut curr = para(0, 706_832, 900, 452, 5000);
        curr.text = "문23)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 961.65;
        let got = c.vpos_adjust(y_offset, 1, &[prev, curr], &styles(0.0));
        let expected = y_offset - 5669.0 / 75.0 - 4.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 보이는 구분선 + 큰 미주 사이에서 단 하단의 새 문항 제목은 직전 spacer가
    /// 만든 trailing y를 무조건 유지하지 않는다. 저장 vpos가 frame 안쪽이고
    /// 직전 콘텐츠 바닥을 침범하지 않으면 그 위치를 따라 제목/본문 전체를 올린다.
    #[test]
    fn compact_endnote_large_between_title_tail_uses_saved_vpos_at_bottom() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(0);
        c.endnote_between_notes_hu = 5669;
        let prev = para(0, 57_000, 900, 5669, 5000);
        let mut curr = para(0, 62_250, 900, 452, 5000);
        curr.text = "문16)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(950.0, 1, &[prev, curr], &styles(0.0));
        let expected = 930.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 기본 미주 사이 간격을 가진 새 문제 제목이 단 중간에서 과도하게 전진하면
    /// 뒤쪽 TAC 그림/문단이 단 하단을 넘는다. 제목 자체는 유지하되 저장된 간격에
    /// 완충분만 더해 forward jump를 제한한다.
    #[test]
    fn compact_endnote_question_title_caps_large_forward_gap() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 100000, 900, 1984, 5000),
            para(0, 108025, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문29)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(650.0, 1, &ps, &styles(0.0));
        let expected = 650.0 + 1984.0 / 75.0 + 40.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 미주 사이가 0인 문서의 새 문항 제목은 저장 vpos의 큰 제목 gap을
    /// 그대로 쓰지 않고 직전 문단 뒤의 순차 위치를 따른다.
    #[test]
    fn compact_endnote_zero_between_question_title_caps_forward_gap() {
        let mut c = compact_endnote_cursor(Some(100000));
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 101000, 900, 452, 5000),
            para(0, 106000, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문29)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(120.0, 1, &ps, &styles(0.0));

        assert!((got - 120.0).abs() < 1e-6, "got={got}");
    }

    /// 단 중간의 새 미주 제목에서 저장 VPOS가 페이지 하단 근처까지 크게 튀면
    /// 그 절대 위치는 버리되 직전 문단의 미주 사이 간격만 보존한다.
    #[test]
    fn compact_endnote_question_title_preserves_spacing_on_stale_forward_jump() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 100000, 900, 1984, 5000),
            para(0, 150000, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문22)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(450.0, 1, &ps, &styles(0.0));
        let expected = 450.0 + 1984.0 / 75.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 단 상단에 가까운 새 미주 제목은 순차 y가 이미 한컴/PDF 위치이므로
    /// stale-forward 저장 vpos를 버리되 미주 사이 line spacing을 한 번 더 넣지 않는다.
    #[test]
    fn compact_endnote_question_title_top_stale_forward_keeps_sequential_y() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(719467);
        let mut ps = vec![
            para(0, 722803, 900, 1984, 5000),
            para(0, 742719, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문23)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 147.19;
        let end_y = COL_Y + (742719.0 - 719467.0) / 75.0;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        let expected_base = 719467 + ((end_y - y_offset) / DPI * 7200.0).round() as i32;

        assert!(
            (got - y_offset).abs() < 1e-6,
            "got={got}, expected={y_offset}"
        );
        assert_eq!(c.vpos_lazy_base, Some(expected_base));
    }

    /// 빈 문단이 새 미주 제목 앞의 시각 간격을 이미 만들었다면 추가 40px 완충은 넣지 않는다.
    #[test]
    fn compact_endnote_question_title_after_empty_spacer_keeps_stored_gap_only() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 100000, 900, 1984, 5000),
            para(0, 108025, 900, 452, 5000),
        ];
        ps[1].text = "문19)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(650.0, 1, &ps, &styles(0.0));
        let expected = 650.0 + 1984.0 / 75.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 기본 미주 다줄 tail 뒤 새 문항 제목은 single-line tail보다 작은 buffer를 쓴다.
    #[test]
    fn compact_endnote_question_title_caps_multiline_tail_with_smaller_gap() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(1091323);
        let mut prev = para(0, 1130344, 900, 0, 5000);
        prev.line_segs.push(LineSeg {
            vertical_pos: 1132866,
            line_height: 900,
            line_spacing: 1984,
            segment_width: 5000,
            ..Default::default()
        });
        prev.text = " ( ㉡)".to_string();
        let mut curr = para(0, 1140848, 900, 452, 5000);
        curr.text = "문29)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 656.61;
        let got = c.vpos_adjust(y_offset, 1, &[prev, curr], &styles(0.0));
        let expected = y_offset + 1984.0 / 7200.0 * DPI + 18.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 큰 디스플레이 수식 줄 뒤 새 문제 제목은 trailing 줄간격 전체 뒤가 아니라
    /// 보이는 수식 바닥 직후로 붙는다.
    #[test]
    fn compact_endnote_question_title_after_tall_line_uses_content_bottom_gap() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 100000, 2690, 1984, 5000),
            para(0, 109174, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문13)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(500.0, 1, &ps, &styles(0.0));
        let expected = 500.0 - 1984.0 / 75.0 + 10.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 렌더러가 실제 콘텐츠 하단을 제공하면 display 수식 뒤 제목은 그 하단 아래로 배치한다.
    #[test]
    fn compact_endnote_question_title_after_tall_line_uses_rendered_content_bottom_gap() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.prev_item_content_bottom_y = Some(500.0);
        let mut ps = vec![
            para(0, 100000, 2690, 1984, 5000),
            para(0, 109174, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문8)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(500.0, 1, &ps, &styles(0.0));
        let expected = 510.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 설정된 미주 사이 값이 있으면 display 수식 하단 뒤에 그 공통 간격을 적용한다.
    #[test]
    fn compact_endnote_question_title_after_tall_line_uses_between_notes_gap() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.prev_item_content_bottom_y = Some(500.0);
        c.endnote_between_notes_hu = 5669; // 20mm
        let mut ps = vec![
            para(0, 100000, 2690, 1984, 5000),
            para(0, 109174, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문8)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(500.0, 1, &ps, &styles(0.0));
        let expected = 500.0 + 5669.0 / 75.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 기본 7mm 미주 상단에서 텍스트가 섞인 큰 수식 line 뒤 새 문항은
    /// line_spacing 전체가 아니라 보이는 line bottom 뒤 짧은 gap으로 붙는다.
    #[test]
    fn compact_endnote_question_title_after_tall_regular_gap_uses_line_bottom() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(171940);
        c.endnote_between_notes_hu = 1984;
        let mut ps = vec![
            para(0, 193919, 2690, 1984, 5000),
            para(0, 199704, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문13)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 419.63;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        let expected = y_offset - (1984.0 / 7200.0 * DPI) + 10.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 중단 하단의 큰 수식 line 뒤 문항 제목은 한컴처럼 한 줄가량만 당기고,
    /// 후속 문항이 저장 vpos와 다시 충돌하지 않도록 lazy base도 함께 이동한다.
    #[test]
    fn compact_endnote_question_title_after_tall_mid_backtrack_shifts_lazy_base() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(736951);
        c.endnote_between_notes_hu = 1984;
        let mut ps = vec![
            para(0, 771046, 2395, 1984, 5000),
            para(0, 773893, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문26)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 639.45;
        let end_y = COL_Y + (773893.0 - 736951.0) / 75.0;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        let expected = (y_offset - 41.0).max(y_offset - 1984.0 / 75.0 + 10.0);
        let expected_base = 736951 + ((end_y - expected) / DPI * 7200.0).round() as i32;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
        assert_eq!(c.vpos_lazy_base, Some(expected_base));
    }

    /// 수식 tail 보정 직후의 제목이 hard backtrack 임계값보다 작게 남으면
    /// 순차 y를 그대로 두지 않고 작은 폭만 당겨 한컴의 하단 제목 위치에 맞춘다.
    #[test]
    fn compact_endnote_question_title_tail_soft_backtrack_after_equation_tail() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(100000);
        let mut ps = vec![
            para(0, 135000, 3240, 1984, 5000),
            para(0, 164586, 900, 452, 5000),
        ];
        ps[1].text = "문27)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 990.0;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        let expected = 980.0;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 단 하단의 큰 수식/inline 뒤 새 문항 제목은 저장 vpos 전체가 아니라
    /// 제한 폭만 당겨 뒤 풀이 줄이 frame 안에 들어가게 한다.
    #[test]
    fn compact_endnote_question_title_after_tall_tail_limited_backtrack() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(615940);
        let mut ps = vec![
            para(0, 672236, 2295, 1984, 5000),
            para(0, 674983, 900, 452, 5000),
        ];
        ps[0].text = "에서".to_string();
        ps[1].text = "문25)".to_string();
        mark_note_first(&mut c, 1);

        let got = c.vpos_adjust(969.89, 1, &ps, &styles(30.0));
        let expected = 909.89;

        assert!(
            (got - expected).abs() < 1e-6,
            "got={got}, expected={expected}"
        );
    }

    /// 단 상단 큰 수식 tail 뒤 새 문항 제목은 순차 흐름이 PDF 위치와 맞으면
    /// 저장 vpos forward를 버리고 후속 미주 base도 같은 폭으로 당긴다.
    #[test]
    fn compact_endnote_question_title_after_tall_upper_flow_keeps_sequential_y() {
        let mut c = compact_endnote_cursor(Some(984738));
        c.prev_layout_para = Some(0);
        let mut ps = vec![
            para(0, 989379, 2070, 1984, 5000),
            para(0, 994892, 900, 452, 5000),
        ];
        ps[0].text = "따라서".to_string();
        ps[1].text = "문28)".to_string();
        mark_note_first(&mut c, 1);

        let y_offset = 216.0;
        let end_y = COL_Y + (994892.0 - 984738.0) / 7200.0 * DPI;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        let expected_base = 984738 + ((end_y - y_offset) / DPI * 7200.0).round() as i32;

        assert!(
            (got - y_offset).abs() < 1e-6,
            "got={got}, expected={y_offset}"
        );
        assert_eq!(c.vpos_page_base, Some(expected_base));
    }

    /// 새 미주 제목 바로 다음 문단도 제목 위로 되감기면 미주 사이 간격과 제목이 깨진다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_after_note_title() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![para(0, 70100, 900, 0, 5000), para(0, 70150, 900, 0, 5000)];
        ps[0].text = "문11)".to_string();
        mark_note_first(&mut c, 0);

        let got = c.vpos_adjust(1030.0, 1, &ps, &styles(0.0));
        assert!((got - 1030.0).abs() < 1e-6, "got={got}");
    }

    /// 제목 직후의 다줄 꼬리 문단은 하단 overflow를 막기 위해 제한적으로만 당긴다.
    #[test]
    fn compact_endnote_limited_backtrack_after_note_title_tail() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let mut ps = vec![para(0, 70100, 900, 0, 5000), para(0, 70150, 900, 0, 5000)];
        ps[0].text = "문27)".to_string();
        mark_note_first(&mut c, 0);
        ps[1].line_segs.push(LineSeg {
            vertical_pos: 71502,
            line_height: 900,
            text_height: 900,
            baseline_distance: 765,
            line_spacing: 452,
            column_start: 0,
            segment_width: 5000,
            text_start: 0,
            tag: 0,
        });
        ps[1].line_segs.push(LineSeg {
            vertical_pos: 72854,
            line_height: 900,
            text_height: 900,
            baseline_distance: 765,
            line_spacing: 452,
            column_start: 0,
            segment_width: 5000,
            text_start: 0,
            tag: 0,
        });

        let got = c.vpos_adjust(1030.0, 1, &ps, &styles(0.0));
        assert!(got < 1030.0, "got={got}");
        assert!(got >= 1014.0, "backtrack must stay capped: got={got}");
    }

    /// 되감긴 목표가 직전 줄 내용 하단보다 위이면 overflow보다 겹침 위험이 크다.
    #[test]
    fn compact_endnote_deep_backtrack_skips_if_it_crosses_previous_content() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let ps = vec![para(0, 70100, 900, 452, 5000), para(0, 70150, 900, 0, 5000)];

        let got = c.vpos_adjust(1030.0, 1, &ps, &styles(0.0));
        assert!((got - 1030.0).abs() < 1e-6, "got={got}");
    }

    /// 앞선 TAC 표 높이 때문에 lazy base 역산이 음수가 되면 되감김 보정을 건너뛴다.
    #[test]
    fn invalid_lazy_base_skips_backtrack_after_tall_object() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 18177, 900, 452, 5000), // prev_vpos_end=19529
            para(0, 19529, 900, 452, 5000),
        ];

        let got = c.vpos_adjust(361.37, 1, &ps, &styles(0.0));
        assert!((got - 361.37).abs() < 1e-6, "got={got}");
        assert_eq!(c.vpos_lazy_base, None);
    }

    /// VPOS가 하단부에서 크게 되감길 때(8px 이상)에도 보정이 적용되면
    /// 반환 y 자체가 새 기준이므로 page base는 추가로 움직이지 않는다.
    #[test]
    fn backward_correction_keeps_page_base() {
        let mut c = HeightCursor::new(DPI, COL_Y, COL_H, COL_Y, Some(0), false, true, true, false);
        c.prev_layout_para = Some(0);
        let ps = vec![
            para(0, 1000, 1000, 0, 5000), // prev end: 1100
            para(0, 200, 1000, 0, 5000),  // vpos rewind candidate
        ];

        let got = c.vpos_adjust(780.0, 1, &ps, &styles(0.0));
        let expected_end_y = 100.0 + 200.0 / 75.0;

        assert!((got - expected_end_y).abs() < 1e-6, "got={got}");
        assert_eq!(c.vpos_page_base, Some(0));
    }

    fn multiline_prev_with_injected_gap() -> Paragraph {
        // 다줄(2 seg) 미주 문단, 마지막 seg ls=1984(typeset 가 주입한 between-notes).
        let mut p = para(0, 1000, 900, 0, 5000);
        p.line_segs.push(LineSeg {
            vertical_pos: 1900,
            line_height: 900,
            line_spacing: 1984,
            segment_width: 5000,
            ..Default::default()
        });
        p
    }

    /// [Task #1246] 다줄 풀이로 끝나는 미주 다음 제목이 stored vpos gap≈0(마지막 줄 trailing
    /// 누락=문22)이면 between-notes(직전 주입 줄간격)만큼 끌어올린다.
    #[test]
    fn compact_endnote_min_gap_lifts_zero_gap_question_title() {
        let mut c = compact_endnote_cursor(Some(0));
        c.endnote_between_notes_hu = 1984;
        c.prev_layout_para = Some(0);
        let mut curr = para(0, 2800, 900, 0, 5000); // prev 내용 바닥(1900+900) → stored gap≈0
        curr.text = "문11)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![multiline_prev_with_injected_gap(), curr];
        let y_in = 100.0 + 2800.0 / 75.0; // page_path end_y 와 동일 → stored gap 0
        let got = c.vpos_adjust(y_in, 1, &ps, &styles(0.0));
        let expected = y_in + 1984.0 / 75.0;
        assert!(
            (got - expected).abs() < 1e-6,
            "got={got} expected={expected}"
        );
    }

    /// stored vpos 가 의도적 gap(>4px)을 인코딩하면 over-lift 하지 않는다(문13 류 backtrack/소gap).
    #[test]
    fn compact_endnote_min_gap_respects_existing_vpos_gap() {
        let mut c = compact_endnote_cursor(Some(0));
        c.endnote_between_notes_hu = 1984;
        c.prev_layout_para = Some(0);
        let mut curr = para(0, 3550, 900, 0, 5000); // 2800 + 750(=10px) → stored gap 10px
        curr.text = "문13)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![multiline_prev_with_injected_gap(), curr];
        let y_in = 100.0 + 2800.0 / 75.0;
        let got = c.vpos_adjust(y_in, 1, &ps, &styles(0.0));
        let expected_end = 100.0 + 3550.0 / 75.0; // 보정 없이 vpos 위치 유지
        assert!(
            (got - expected_end).abs() < 1e-6,
            "got={got} expected={expected_end}"
        );
    }

    /// 단일줄 prev 는 trailing 이 이미 sequential y 에 포함되므로 min-gap 보정 대상이 아니다.
    #[test]
    fn compact_endnote_min_gap_skips_single_line_prev() {
        let mut c = compact_endnote_cursor(Some(0));
        c.endnote_between_notes_hu = 1984;
        c.prev_layout_para = Some(0);
        let prev = para(0, 1900, 900, 1984, 5000); // 단일줄, ls=1984
        let mut curr = para(0, 2800, 900, 0, 5000);
        curr.text = "문11)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![prev, curr];
        let y_in = 100.0 + 2800.0 / 75.0;
        let got = c.vpos_adjust(y_in, 1, &ps, &styles(0.0));
        // 단일줄 prev → 보정 없음 (stored gap 0 이어도 lift 안 함)
        assert!((got - y_in).abs() < 1e-6, "got={got} expected={y_in}");
    }

    /// 단일줄 prev 뒤 stale forward vpos가 크게 튀어도, sequential y가 이미
    /// PDF 위치와 맞으면 미주 사이를 추가로 넣지 않는다.
    #[test]
    fn compact_endnote_stale_gap_skips_single_line_prev() {
        let mut c = compact_endnote_cursor(None);
        c.prev_layout_para = Some(0);
        c.vpos_lazy_base = Some(946616);
        let mut prev = para(0, 1011363, 1035, 1984, 5000);
        let mut curr = para(0, 1012850, 900, 452, 5000);
        prev.text = "따라서 이다.".to_string();
        curr.text = "문24)".to_string();
        mark_note_first(&mut c, 1);

        let y_in = 831.44;
        let got = c.vpos_adjust(y_in, 1, &[prev, curr], &styles(0.0));

        assert!((got - y_in).abs() < 1e-6, "got={got} expected={y_in}");
    }

    /// 0mm 미주 일반 텍스트 연속 문단은 저장 vpos가 직전 렌더 bbox 하단보다 위를
    /// 가리켜도 실제 콘텐츠 하단 아래에서 시작해야 글자 겹침이 생기지 않는다.
    #[test]
    fn compact_endnote_zero_gap_text_keeps_previous_content_floor() {
        let mut c = compact_endnote_cursor(Some(1000));
        c.endnote_between_notes_hu = 0;
        c.prev_layout_para = Some(0);
        c.prev_item_content_bottom_y = Some(115.0);

        let mut prev = para(0, 1000, 800, 160, 5000);
        prev.text = "202) 무력한 과거의 삶".to_string();
        let mut curr = para(0, 1960, 800, 160, 5000);
        curr.text = "203) 현실에 정면으로 맞서는 삶".to_string();

        let y_offset = 118.0;
        let got = c.vpos_adjust(y_offset, 1, &[prev, curr], &styles(0.0));
        let expected_floor = y_offset - 160.0 / 75.0;
        assert!(
            (got - expected_floor).abs() < 1e-6,
            "got={got} expected={expected_floor}"
        );

        let end_y = COL_Y + (1960.0 - 1000.0) / 75.0;
        let expected_base = 1000 - (((got - end_y) / DPI * 7200.0).round() as i32);
        assert_eq!(
            c.vpos_page_base,
            Some(expected_base),
            "내린 만큼 vpos base를 이동해야 후속 문단이 다시 당겨지지 않음"
        );
    }

    /// [Task #1256] 단일 줄 prev(빈 separator, ls=between_notes)로 끝나는 미주 제목 경계에서
    /// safe_vpos_backtrack 이 end_y(주입 7mm 미포함)로 cram 하면, y_offset(7mm 포함)을 유지하고
    /// 내린 만큼 vpos base 를 이동한다.
    #[test]
    fn compact_endnote_between_notes_singleline_prev_keeps_gap_and_shifts_base() {
        let mut c = compact_endnote_cursor(Some(0)); // page_path, base=0
        c.endnote_between_notes_hu = 1984;
        c.prev_layout_para = Some(0);
        let prev = para(0, 1900, 900, 1984, 5000); // 단일줄 빈 separator, ls=1984(주입 7mm)
        let mut curr = para(0, 2800, 900, 0, 5000);
        curr.text = "문7)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![prev, curr];
        // end_y = 100 + 2800/75 = 137.333. y_offset=160 → safe_backtrack(end_y<y_offset-8,
        // end_y>=prev_content_bottom=160-1984/75=133.55, mid-column) 발동 → 베이스라인 cram.
        let y_offset = 160.0;
        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));
        assert!(
            (got - y_offset).abs() < 1e-6,
            "y_offset(7mm 포함) 유지해야 함: got={got}"
        );
        // 제목을 (160 - 137.333)px 내렸으므로 page base 가 그만큼 음수로 이동.
        let end_y = 100.0 + 2800.0 / 75.0;
        let expected_base = -(((y_offset - end_y) / DPI * 7200.0).round() as i32);
        assert_eq!(
            c.vpos_page_base,
            Some(expected_base),
            "내린 만큼 vpos base 이동해야 후속 항목 desync 방지"
        );
    }

    /// [Task #1261] 단일 줄 prev의 between-notes gap이 이미 y_offset에 있으면,
    /// page-path vpos가 제목을 소폭 아래로 밀어도 gap을 한 번 더 더하지 않는다.
    #[test]
    fn compact_endnote_between_notes_singleline_prev_ignores_small_forward_vpos() {
        let mut c = compact_endnote_cursor(Some(0));
        c.endnote_between_notes_hu = 5669;
        c.prev_layout_para = Some(0);
        let prev = para(0, 1900, 900, 5669, 5000);
        let mut curr = para(0, 3550, 900, 0, 5000); // y_offset보다 10px 아래 저장 vpos
        curr.text = "문10)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![prev, curr];
        let y_offset = 100.0 + 2800.0 / 75.0;

        let got = c.vpos_adjust(y_offset, 1, &ps, &styles(0.0));

        assert!(
            (got - y_offset).abs() < 1e-6,
            "이미 주입된 미주 사이 y_offset을 유지해야 함: got={got}, expected={y_offset}"
        );
        let end_y = 100.0 + 3550.0 / 75.0;
        let expected_base = ((end_y - y_offset) / DPI * 7200.0).round() as i32;
        assert_eq!(
            c.vpos_page_base,
            Some(expected_base),
            "올린 만큼 vpos base 이동해야 후속 제목이 다시 밀리지 않음"
        );
    }

    /// [Task #1256] 자연 trailing(ls < between_notes)인 단일 줄 prev 는 injected_between_notes
    /// 가 아니므로 위 보정 대상이 아니다(backtrack 결과 그대로, base 무이동).
    #[test]
    fn compact_endnote_between_notes_skips_natural_trailing_prev() {
        let mut c = compact_endnote_cursor(Some(0));
        c.endnote_between_notes_hu = 1984;
        c.prev_layout_para = Some(0);
        let prev = para(0, 1900, 900, 180, 5000); // 자연 trailing(180 < 1984)
        let mut curr = para(0, 2800, 900, 0, 5000);
        curr.text = "문7)".to_string();
        mark_note_first(&mut c, 1);
        let ps = vec![prev, curr];
        let base_before = c.vpos_page_base;
        let got = c.vpos_adjust(160.0, 1, &ps, &styles(0.0));
        // injected_between_notes=false → #1256 분기 미발동. base 무변경.
        assert_eq!(c.vpos_page_base, base_before, "base 무이동");
        // 보정 분기를 타지 않으므로 y_offset 유지(cram 아님) 또는 backtrack — 핵심은 base 무이동.
        let _ = got;
    }

    /// [#4613 · #4599 밴드-플로우] 후방 배치 역보정은 base 를 delta 만큼 늘려(전방 밀림 보정의
    /// 대칭) 후속 문단의 사다리 목표를 함께 위로 이동시킨다.
    #[test]
    fn backtrack_shift_raises_vpos_base_symmetrically() {
        let mut c = cursor(Some(6000));
        c.shift_vpos_base_for_rendered_delta(10.0); // 전방 10px → base -750
        assert_eq!(c.vpos_page_base, Some(5250));
        c.shift_vpos_base_for_rendered_backtrack(10.0); // 후방 10px → base +750 복원
        assert_eq!(c.vpos_page_base, Some(6000));
        // 0 이하 무동작
        c.shift_vpos_base_for_rendered_backtrack(0.0);
        c.shift_vpos_base_for_rendered_backtrack(-3.0);
        assert_eq!(c.vpos_page_base, Some(6000));
    }
}