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
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
//! 줄 나눔 엔진 (Line Breaking Engine)
//!
//! 문단 텍스트를 토큰화하고 줄 나눔을 수행한다.
//! 한글 어절/글자, 영어 단어/하이픈, CJK 개별 분할을 지원한다.

use super::picture_anchor_projection::{self, FramePurpose};
use super::supplemental_clusters::ParagraphMetricScope;
use super::{char_lang_slot, find_active_char_shape, is_lang_neutral, ComposedParagraph};
use crate::model::control::{Control, CTRL_CHAR_CODE_UNITS};
use crate::model::paragraph::{CharShapeRef, ColumnBreakType, LineSeg, Paragraph, SpaceMetric};
use crate::model::style::{Alignment, HeadType, LineSpacingType};
use crate::renderer::equation_tac_flow::indent_leaves_line_room_hwp;
use crate::renderer::layout::{
    estimate_text_width, estimate_text_width_unrounded, glyph_letter_spacing_advance,
    hancom_regenerated_space_width, is_cjk_char, kopub_space_advance_em, resolved_letter_spacing,
};
use crate::renderer::layout_frame::{FrameRowMetrics, LayoutFrame, ParagraphBox, RowSegment};
use crate::renderer::style_resolver::storage::{Storage, Unbounded};
use crate::renderer::style_resolver::{
    detect_lang_category, is_latin_slot_symbol, ResolvedParaStyle, ResolvedStyleSet,
};
use crate::renderer::{hwpunit_to_px, px_to_hwpunit};
use std::ops::Range;

mod inline_frame_input;
mod list_marker_metrics;
mod stored_external_geometry;
use stored_external_geometry::stored_rows_require_external_geometry;

struct PreparedParagraphKerning {
    context: std::sync::Arc<crate::renderer::kerning::KerningMeasurementContext>,
    scalar_styles: Vec<crate::renderer::kerning::KerningParagraphScalarStyle>,
    hard_boundaries: Vec<bool>,
    measurement: std::sync::Arc<crate::renderer::kerning::KerningParagraphMeasurement>,
}

struct PreparedParagraphProjection {
    base_positions: Vec<f64>,
    kerning_scalar_styles: Vec<crate::renderer::kerning::KerningParagraphScalarStyle>,
    shaping_scalar_styles:
        Vec<crate::renderer::shaping_paragraph::HorizontalShapingParagraphScalarStyle>,
    hard_boundaries: Vec<bool>,
}

/// A complete, source-independent projection of one supported Picture wrap
/// band. The document layer owns the one-shot publication of every paragraph
/// in this range.
#[derive(Debug, Clone)]
pub(crate) struct PictureBandLayout {
    pub(crate) paragraph_range: Range<usize>,
    pub(crate) line_segs: Vec<Vec<LineSeg>>,
    pub(crate) space_metrics: Vec<Vec<(u32, SpaceMetric)>>,
    pub(crate) preserved_stored: Vec<bool>,
}

/// How the frame resolved a paragraph's stored rows.
///
/// Stored rows are a cache of a prior frame computation. Reuse is therefore
/// allowed only after the current frame reproduces their physical-row key:
/// interval count plus exact `column_start`/`segment_width` for every slot.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) enum StoredRowResolution {
    /// The current frame admitted every stored physical row exactly.
    ///
    /// This is the right answer rather than a placeholder, and the reason is
    /// worth stating because "the frame owns both routes" makes it sound wrong.
    /// The frame is licensed to write two lanes, and on this arm neither one
    /// has anything to say:
    ///
    /// - **Geometry** (`column_start`, `segment_width`). Publishing is a no-op
    ///   by construction: exact equality is the admission test.
    /// - **Row metrics** (`line_height`, `baseline_distance`, `line_spacing`).
    ///   Deliberately not published: §1.4.1's accept-arm write-back is not
    ///   implemented. [`LayoutFrame::try_admit_stored_rows`] records the
    ///   measurement that settled it — publishing them took the suite from
    ///   5983 passed / 2 failed to 5979 / 6.
    ///
    /// So the stored partition may stand only after the frame has checked it.
    Stored,
    /// The stored rows were stale or their physical-row key did not match the
    /// current frame, so strict reflow carved replacement rows. The rows live in
    /// the frame; take them with `project_line_segs()`.
    Reflowed,
}

/// What a caller may conclude from an exact stored-row geometry miss.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum StoredRowMissPolicy {
    /// The caller knows its Frame inputs are current and may publish fresh rows.
    Reflow,
    /// Imported geometry is not derivable from this Frame. A dirty text/style
    /// partition still reflows; a clean geometry miss stays with its source owner.
    UnmodelledUnlessStale,
}

/// 줄 나눔 토큰
#[derive(Debug, Clone)]
pub(crate) enum BreakToken {
    /// 제어 soft-hyphen은 중간 전진 없이, 하이픈이 fit하는 줄 끝만 제공한다.
    DiscretionaryHyphen {
        idx: usize,
        width: f64,
        max_font_size: f64,
    },
    /// 분할 불가 텍스트 조각 (어절/단어/글자)
    /// char_widths: 글자별 px 폭 (char_level_break용, 단일 글자 토큰은 비어있음)
    Text {
        start_idx: usize,
        end_idx: usize,
        /// K0 scalar pen width. Dynamic space/tab accounting and boundary
        /// pair correction are applied against this invariant base.
        base_width: f64,
        /// Owned paragraph-position token total. K0에서는 base_width와 같다.
        width: f64,
        max_font_size: f64,
        base_char_widths: Vec<f64>,
        char_widths: Vec<f64>,
    },
    /// 공백 (줄 바꿈 가능 지점, 줄 끝에서 흡수)
    Space {
        idx: usize,
        width: f64,
        /// [#7418] 자간을 적용하기 **전**의 공백 폭(px). 공백 최소값(condense)은 이 폭의
        /// c% 만큼 줄인다 — 한/글 2024 합성 실험(자간 −20·−12·−6·+10% × condense 0~75,
        /// 777줄)에서 자간 적용 후 폭을 기준으로 하면 음수 자간 문단이 한 줄에 덜 담았다.
        condense_base: f64,
        max_font_size: f64,
        /// 이 자리에 함께 놓인 글자처럼 취급 개체의 폭(px, 없으면 0). `width` 에 들어 있다.
        /// 개체는 줄 끝에 걸 수 없지만 그 뒤 공백은 다른 공백처럼 줄 끝에 건다.
        inline_width: f64,
    },
    /// 탭 (줄 바꿈 가능 지점, 폭은 줄 위치에 따라 동적)
    Tab {
        idx: usize,
        max_font_size: f64,
        auto_left_target: Option<f64>,
    },
    /// 강제 줄 바꿈 (\n)
    LineBreak { idx: usize },
}

/// 글자처럼 취급되는 인라인 제어문의 문단 내 위치와 물리 크기.
///
/// HWP `PARA_TEXT`에는 수식·그림 본문이 보이지 않는 8 UTF-16 단위 제어문자로
/// 들어가므로, visible text만 토큰화하면 제어문이 차지한 폭이 사라진다. 재조판은
/// 그 폭과 높이를 별도로 들고 줄나눔과 line box에 반영해야 한다 (#3211).
#[derive(Debug, Clone, Copy)]
struct FlowInlineControl {
    char_position: usize,
    utf16_position: u32,
    width_hwp: i32,
    height_hwp: i32,
    /// Equation supplies an object-owned baseline for the physical row. Other
    /// inline objects keep the text metrics already selected by the caller.
    baseline_distance_hwp: Option<i32>,
    /// Source-owned participation in paragraph line spacing is separate from
    /// the object's occupied height. A larger non-participant must not enlarge it.
    spacing_height_hwp: Option<i32>,
}

/// 줄 채움 결과
#[derive(Debug, Clone, PartialEq)]
struct LineBreakResult {
    start_idx: usize,
    end_idx: usize, // exclusive
    max_font_size: f64,
    has_line_break: bool, // 강제 줄 바꿈 여부
}

/// Why one carved interval stopped receiving text.
///
/// A false `has_line_break` alone is ambiguous: a segment can stop because it
/// reached its interval, or because it finished the paragraph. Frame layout
/// needs the distinction to decide whether the next horizontal interval is
/// part of the same physical row.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum FillTermination {
    IntervalFull,
    ForcedBreak,
    ParagraphEnd,
}

#[derive(Debug, Clone, PartialEq)]
struct FilledInterval {
    line: LineBreakResult,
    termination: FillTermination,
}

/// 줄 머리 금칙: 줄 시작에 올 수 없는 문자
pub(crate) fn is_line_start_forbidden(ch: char) -> bool {
    matches!(
        ch,
        ')' | ']'
            | '}'
            | ','
            | '.'
            | '!'
            | '?'
            | ';'
            | ':'
            | '\''
            | '"'
            | '\u{3001}'
            | '\u{3002}'
            | '\u{2026}'
            // ONE DOT LEADER도 앞 글자와 줄을 함께 소유한다. UAX #14 IN/LB22와
            // 독립 한컴 Print의 `흡|기․냉각수`처럼 점만 다음 줄 머리로 보내지 않는다.
            | '\u{2024}'
            | '\u{00B7}'
            // ‧ HYPHENATION POINT — 한컴 저장 조판 실측: 줄머리 0건 · 줄끝 2건.
            // `·`(U+00B7)는 이미 있는데 이것만 빠져 있어 줄 머리로 내려갔다.
            | '\u{2027}'
            | '\u{2015}'
            | '\u{30FC}'
            | '\u{300B}'
            | '\u{300D}'
            | '\u{300F}'
            | '\u{3011}'
            | '\u{FF09}'
            | '\u{FF5D}'
            | '\u{3015}'
            | '\u{3009}'
            | '\u{FF1E}'
            | '\u{226B}'
            | '\u{FF3D}'
            | '\u{FE5E}'
            | '\u{301E}'
            | '\u{2019}'
            | '\u{201D}'
            | '\u{FF0C}'
            | '\u{FF0E}'
            | '\u{FF01}'
            | '\u{FF1F}'
            | '\u{FF1B}'
            | '\u{FF1A}'
            | '%'
            | '\u{2030}'
            | '\u{2103}'
            | '\u{00B0}'
            | '\u{FF05}'
    )
}

/// 줄 꼬리 금칙: 줄 끝에 올 수 없는 문자
/// [#7418] 글자 단위 한글 문단에서 `start_idx` 의 한글 글자 **앞**이 줄 끝 자리인가.
///
/// 글자 단위 모드는 한글 글자마다 그 **뒤**를 줄 끝 후보로 등록한다. 그래서 한글 앞에
/// 라틴·숫자 토큰이 공백 없이 붙으면(`3,588만원`) 그 경계를 끊을 수 없었고, `만` 이 넘치면
/// 줄이 앞 공백으로 되감겨 `3,588` 까지 다음 줄로 내려갔다. 한/글은 그 경계에서 끊는다 —
/// 말뭉치 `pdf/` 에서 같은 문단의 이어진 줄이 라틴·숫자로 끝나고 한글로 시작하는 경계가
/// 809곳이다(`제37조제1|항` · `CBTA|훈련체계` · `Annex 1|의` · `연간 10|시간`).
///
/// 직전 글자가 공백이면 이미 공백 토큰이 줄 끝 후보이고, 줄 끝 금칙 문자(`(`·`「` 등)면
/// 줄 끝에 둘 수 없다. 직전이 한글이면 그 글자 뒤로 이미 등록된 같은 자리다.
fn break_before_text_token(
    text_chars: &[char],
    start_idx: usize,
    line_start_idx: usize,
    korean_break_unit: u8,
) -> bool {
    if start_idx <= line_start_idx || start_idx >= text_chars.len() {
        return false;
    }
    let previous = text_chars[start_idx - 1];
    // UAX #14의 CB(OBJECT REPLACEMENT CHARACTER, LB20)는 개체 앞의
    // 줄바꿈 기회를 갖는다. 이 경계를 빠뜨리면 넓은 인라인 표 앞의
    // 이모지·라틴 글자까지 이전 공백으로 되감겨 빈 줄이 하나 더 생긴다.
    // 여는 금칙 문자와 명시적인 줄바꿈 억제 문자는 기존 결합을 유지한다.
    if text_chars[start_idx] == '\u{FFFC}'
        && !previous.is_whitespace()
        && !is_line_end_forbidden(previous)
        && !matches!(previous, '\u{2060}' | '\u{FEFF}')
    {
        return true;
    }
    // 수식 뒤 단위의 곱셈점도 낱말 경계다. 독립 Print의 `(kN․|m)`처럼
    // 앞쪽 단위가 물리 폭 안에 들면 공백/수식 앞까지 되감지 않는다.
    if matches!(previous, '\u{2024}' | '\u{2219}')
        && !is_line_start_forbidden(text_chars[start_idx])
    {
        return true;
    }
    // A'·AA'의 prime/닫는 따옴표는 여는 작은따옴표와 문자값이 같다.
    // 실제 앞 글자를 확인해 닫힌 낱말 뒤 한글 경계를 허용한다. 공백 뒤의
    // 여는 따옴표와 방향이 명시된 여는 괄호/따옴표는 기존 금칙을 유지한다.
    let closing_apostrophe =
        previous == '\'' && start_idx >= 2 && text_chars[start_idx - 2].is_alphanumeric();
    // 독립 한컴 Print의 `<개정 ...>`은 여는 꺾쇠와 다음 글자가 한 줄을
    // 소유한다. 단독 `<`는 비교·리다이렉션 연산자로 줄 끝에 올 수 있으므로
    // 뒤에 공백 없이 이어지는 짝 닫힘이 확인된 경우에만 이 계약을 쓴다.
    let paired_angle_open = previous == '<'
        && text_chars
            .get(start_idx)
            .is_some_and(|c| !c.is_whitespace())
        && text_chars[start_idx..]
            .iter()
            .take_while(|c| !matches!(**c, '\n' | '\r' | '<'))
            .any(|c| *c == '>');
    // [#2185] bit7=1 = 글자 단위
    korean_break_unit == 1
        && start_idx > line_start_idx
        && text_chars.get(start_idx).is_some_and(|c| is_hangul(*c))
        && text_chars.get(start_idx - 1).is_some_and(|prev| {
            !prev.is_whitespace()
                && !paired_angle_open
                && (!is_line_end_forbidden(*prev) || closing_apostrophe)
        })
}

/// 독립 Print에서 낱말 유지 문단도 한점 리더·분철점 뒤에서 나뉜다.
/// 같은 폭의 U+00B7·ASCII 마침표는 라틴 낱말을 유지한다. 글꼴 슬롯과
/// 줄 경계는 별도 계약이며, 이미 분리한 기호 토큰의 끝을 공통 소비한다.
fn can_break_after_text_token(ch: char, korean_break_unit: u8) -> bool {
    if is_hangul(ch) || ch.is_ascii_digit() {
        korean_break_unit == 1
    } else {
        // CJK 호환 단위도 한자로 된 낱글자처럼 줄 끝 후보를 소유한다.
        // Unicode Line_Break의 3300..33FF는 모두 ID다. 독립 한컴 Print의
        // `0.5㎥|/kg`에서 단위 뒤 후보를 잃고 앞 공백까지 되감지 않는다.
        // 원문 슬롯·전진폭과 후행 문자의 기존 금칙 판정은 바꾸지 않는다.
        is_cjk_ideograph(ch) || matches!(ch, '\u{3300}'..='\u{33FF}' | '\u{2024}' | '\u{2027}')
    }
}

pub(crate) fn is_line_end_forbidden(ch: char) -> bool {
    // ASCII 큰따옴표는 여는/닫는 모양이 같아 문자값만으로 줄끝 금칙으로
    // 분류할 수 없다. 독립 Print에서도 큰따옴표 뒤 한글 경계가 줄끝이 된다.
    // 방향이 명시된 여는 따옴표·괄호와 기존 줄머리 금칙은 별도로 유지한다.
    matches!(
        ch,
        '(' | '['
            | '{'
            | '\''
            | '\u{300A}'
            | '\u{300C}'
            | '\u{300E}'
            | '\u{3010}'
            | '\u{FF08}'
            | '\u{FF5B}'
            | '\u{3014}'
            | '\u{3008}'
            | '\u{FF1C}'
            | '\u{226A}'
            | '\u{FF3B}'
            | '\u{301D}'
            | '\u{2018}'
            | '\u{201C}'
            | '$'
            | '\u{20A9}'
            | '\u{00A3}'
            | '\u{20AC}'
            | '\u{00A5}'
            | '\u{FF04}'
            | '\u{FFE5}'
    )
}

/// 한글 음절/자모 여부 (옛한글 확장 자모 포함)
fn is_hangul(ch: char) -> bool {
    ('\u{AC00}'..='\u{D7A3}').contains(&ch)       // 한글 음절
        || ('\u{1100}'..='\u{11FF}').contains(&ch) // 한글 자모
        || ('\u{3130}'..='\u{318F}').contains(&ch) // 한글 호환 자모 (ㆍ U+318D 포함)
        || ('\u{A960}'..='\u{A97F}').contains(&ch) // 한글 자모 확장-A (옛한글 초성)
        || ('\u{D7B0}'..='\u{D7FF}').contains(&ch) // 한글 자모 확장-B (옛한글 중/종성)
}

/// 라틴 문자 여부 (영문+숫자)
/// 영문 낱말을 이루는 글자. 영문 슬롯 기호(`·`·`°`·곡선 따옴표)는 글꼴만 영문
/// 슬롯이고 낱말 글자가 아니다(#7702).
fn is_latin(ch: char) -> bool {
    detect_lang_category(ch) == 1 && !is_latin_slot_symbol(ch)
}

/// 영문 낱말 안에 머무는 글자 — 언어 중립 문자와, 중립 문자이던 Latin-1 기호(U+00A1–00BF,
/// `·`·`°` 포함 — #7702·#8136). 글꼴만 영문 슬롯으로 옮겼고 낱말 경계는 바꾸지 않는다.
/// 곡선·아래 따옴표는 종전처럼 낱말을 끊는다.
fn stays_in_latin_word(ch: char) -> bool {
    is_lang_neutral(ch) || matches!(ch, '\u{00A1}'..='\u{00BF}')
}

/// 한글 글자 단위 조판에서 비라틴 줄머리 금칙 앞의 숫자는 영문 낱말이 아니다.
/// 독립 한컴 Print는 `140℃`를 `14|0℃`로 나누지만 `140%`와 `ABC℃`는
/// 낱말째 이월한다. 마지막 숫자와 금칙 문자는 기존 글자 토큰의 흡수 규칙이
/// 함께 소유한다. 글꼴 슬롯이나 숫자의 실제 전진폭은 바꾸지 않는다.
fn numeric_run_before_non_latin_closer(chars: &[char], start: usize) -> Option<usize> {
    let end = start
        + chars[start..]
            .iter()
            .take_while(|ch| ch.is_ascii_digit())
            .count();
    chars
        .get(end)
        .filter(|ch| is_line_start_forbidden(**ch) && !is_latin(**ch) && !stays_in_latin_word(**ch))
        .map(|_| end)
}

/// CJK 문자 여부 (한자/일본어 — 개별 분할 대상)
fn is_cjk_ideograph(ch: char) -> bool {
    let lang = detect_lang_category(ch);
    lang == 2 || lang == 3 // Chinese or Japanese
}

/// 문단 텍스트를 줄 나눔 토큰으로 분할한다.
pub(crate) fn tokenize_paragraph(
    text_chars: &[char],
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    english_break_unit: u8,
    korean_break_unit: u8,
) -> Vec<BreakToken> {
    tokenize_paragraph_with_regenerated_space_metric(
        text_chars,
        char_offsets,
        char_shapes,
        styles,
        english_break_unit,
        korean_break_unit,
        SpaceMetric::Stored,
        &[],
        false,
        &[],
    )
}

impl SpaceMetric {
    /// 줄 채움과 실제 run 배치가 소비하는 동일한 공백 규칙.
    pub(crate) fn apply_to_style(self, style: &mut crate::renderer::TextStyle) {
        match self {
            Self::Stored => {}
            Self::HancomRegenerated => {
                if hancom_regenerated_space_width(style).is_some() {
                    style.layout_half_space = true;
                }
            }
            Self::HalfCell => {
                style.layout_half_space = true;
            }
            Self::KoPubJustified => {
                if let Some(em) = kopub_space_advance_em(style) {
                    style.font_space_em = Some(em);
                }
            }
        }
    }

    fn space_advance(self, style: &crate::renderer::TextStyle) -> f64 {
        let mut selected = style.clone();
        self.apply_to_style(&mut selected);
        estimate_text_width_unrounded(" ", &selected)
    }
}

/// `space_metric` 은 공백 advance 규칙이다. 일반 HWP/HWPX tokenization 은 저장
/// `LINE_SEG` 호환성을 위해 [`SpaceMetric::Stored`] 를 쓴다.
/// 상대 크기는 글리프 폭과 표시 크기이며 기본 줄 상자를 바꾸지 않는다.
/// 원본 LineSeg도 상대 크기 95%(줄이기)·106%(키우기, #7398 `exam_eng.hwp`
/// 라틴 문단 `lh = th = 1150`) 모두 기준 크기의 textheight를 보존한다.
fn token_line_font_size(styles: &ResolvedStyleSet, style_id: u32) -> f64 {
    styles
        .char_styles
        .get(style_id as usize)
        .map(|s| s.font_size)
        .filter(|size| *size > 0.0)
        .unwrap_or(12.0)
}

/// Lexical text units shared with physical TAC row placement. Inline control
/// boundaries remain owned by the caller, rather than joined into a word.
pub(crate) fn text_word_ranges(para: &Paragraph, styles: &ResolvedStyleSet) -> Vec<Range<usize>> {
    match text_word_ranges_with_storage(para, styles, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn text_word_ranges_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    storage: &S,
) -> Result<Vec<Range<usize>>, S::Error> {
    let chars: Vec<_> = storage.collect(para.text.chars())?;
    let style = styles.para_styles.get(para.para_shape_id as usize);
    storage.collect(
        try_tokenize_paragraph_with_regenerated_space_metric(
            &chars,
            &para.char_offsets,
            &para.char_shapes,
            styles,
            style.map_or(0, |s| s.english_break_unit),
            style.map_or(0, |s| s.korean_break_unit),
            SpaceMetric::Stored,
            &[],
            para.control_mask & (1 << 0x18) != 0,
            &para.literal_figure_spaces,
            storage,
        )?
        .into_iter()
        .filter_map(|token| match token {
            BreakToken::Text {
                start_idx, end_idx, ..
            } => Some(start_idx..end_idx),
            _ => None,
        }),
    )
}

fn tokenize_paragraph_with_regenerated_space_metric(
    text_chars: &[char],
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    english_break_unit: u8,
    korean_break_unit: u8,
    space_metric: SpaceMetric,
    inline_controls: &[FlowInlineControl],
    soft_hyphen_control: bool,
    literal_figure_spaces: &[usize],
) -> Vec<BreakToken> {
    match try_tokenize_paragraph_with_regenerated_space_metric(
        text_chars,
        char_offsets,
        char_shapes,
        styles,
        english_break_unit,
        korean_break_unit,
        space_metric,
        inline_controls,
        soft_hyphen_control,
        literal_figure_spaces,
        &crate::renderer::style_resolver::storage::Unbounded,
    ) {
        Ok(tokens) => tokens,
        Err(never) => match never {},
    }
}

fn try_tokenize_paragraph_with_regenerated_space_metric<
    S: crate::renderer::style_resolver::storage::Storage,
>(
    text_chars: &[char],
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    english_break_unit: u8,
    korean_break_unit: u8,
    space_metric: SpaceMetric,
    inline_controls: &[FlowInlineControl],
    soft_hyphen_control: bool,
    literal_figure_spaces: &[usize],
    storage: &S,
) -> Result<Vec<BreakToken>, S::Error> {
    let text_len = text_chars.len();
    if text_len == 0 {
        return Ok(Vec::new());
    }

    let mut tokens = Vec::new();
    let mut i = 0;
    let metric_scope = ParagraphMetricScope::try_new(text_chars, styles, storage)?
        .with_space_metric(space_metric)
        .with_literal_figure_spaces(literal_figure_spaces);
    let mut current_lang: usize = 0;
    // 같은 숫자열의 끝은 한 번만 찾는다. 긴 숫자열을 글자마다 재탐색하지 않는다.
    let mut numeric_closer_end = 0;

    while i < text_len {
        storage.reserve(&mut tokens, 1)?;
        let ch = text_chars[i];

        if soft_hyphen_control && ch == '\u{00AD}' {
            let position = char_offsets.get(i).copied().unwrap_or(i as u32);
            let shape = find_active_char_shape(char_shapes, position);
            let style = metric_scope.try_style(styles, shape, current_lang, i, storage)?;
            storage.push(
                &mut tokens,
                BreakToken::DiscretionaryHyphen {
                    idx: i,
                    width: estimate_text_width_unrounded("-", &style),
                    max_font_size: token_line_font_size(styles, shape),
                },
            )?;
            i += 1;
            continue;
        }

        // 강제 줄 바꿈
        if ch == '\n' {
            storage.push(&mut tokens, BreakToken::LineBreak { idx: i })?;
            i += 1;
            continue;
        }

        // 탭
        if ch == '\t' {
            let utf16_pos = if i < char_offsets.len() {
                char_offsets[i]
            } else {
                i as u32
            };
            let style_id = find_active_char_shape(char_shapes, utf16_pos);
            let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
            let font_size = token_line_font_size(styles, style_id);
            storage.push(
                &mut tokens,
                BreakToken::Tab {
                    idx: i,
                    max_font_size: font_size,
                    auto_left_target: None,
                },
            )?;
            i += 1;
            continue;
        }

        // 공백 (줄 바꿈 지점) — NonBreakingSpace(\u{00A0})는 제외
        // 개체 슬롯은 뒤 글자와 별개의 분할 불가 토큰이다. 글꼴 글리프의
        // 폭은 없으며 공통 측정 결과가 제공한 물리 폭만 소비한다.
        if ch == '\u{FFFC}'
            && inline_controls
                .iter()
                .any(|control| control.char_position == i)
        {
            let width = inline_width_px_at(inline_controls, i, styles);
            let style_id = find_active_char_shape(
                char_shapes,
                char_offsets.get(i).copied().unwrap_or(i as u32),
            );
            storage.push(
                &mut tokens,
                BreakToken::Text {
                    start_idx: i,
                    end_idx: i + 1,
                    base_width: width,
                    width,
                    max_font_size: token_line_font_size(styles, style_id),
                    base_char_widths: storage.collect([width])?,
                    char_widths: storage.collect([width])?,
                },
            )?;
            i += 1;
            continue;
        }
        if ch == ' ' {
            let utf16_pos = if i < char_offsets.len() {
                char_offsets[i]
            } else {
                i as u32
            };
            let style_id = find_active_char_shape(char_shapes, utf16_pos);
            let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
            let font_size = token_line_font_size(styles, style_id);
            let inline_width = inline_width_px_at(inline_controls, i, styles);
            let unspaced = crate::renderer::TextStyle {
                letter_spacing: 0.0,
                ..ts.clone()
            };
            storage.push(
                &mut tokens,
                BreakToken::Space {
                    idx: i,
                    width: space_metric.space_advance(&ts) + inline_width,
                    condense_base: space_metric.space_advance(&unspaced),
                    max_font_size: font_size,
                    inline_width,
                },
            )?;
            i += 1;
            continue;
        }

        // 한글 어절 또는 글자.
        // [#2185] bit7=1(KEEP_WORD)이 **글자 단위**, bit7=0(BREAK_WORD)이
        // 어절 단위 — 스키마 명목과 반대 (한컴 통제 실측 3중 확증: #2169
        // kbu 사다리, 80168 r10, #2185 giant-cell LINE_SEG [0,44,84,122]
        // 보존 대조). 종전 == 1 어절 분기는 역해석 (0da18bbc 회귀).
        if korean_break_unit == 1 && ch.is_ascii_digit() && i >= numeric_closer_end {
            numeric_closer_end = numeric_run_before_non_latin_closer(text_chars, i).unwrap_or(i);
        }
        let numeric_closer =
            korean_break_unit == 1 && ch.is_ascii_digit() && i < numeric_closer_end;
        if is_hangul(ch) || is_cjk_ideograph(ch) || numeric_closer {
            if korean_break_unit == 0 && is_hangul(ch) {
                // 어절 모드: 연속 한글 + 후행 금칙 문자를 하나의 토큰으로
                let start = i;
                let mut max_fs = 0.0f64;
                let mut token_lang = current_lang;

                while i < text_len {
                    let c = text_chars[i];
                    if soft_hyphen_control && c == '\u{00AD}' {
                        break;
                    }
                    if c == ' ' || c == '\n' || c == '\t' || c == '\u{FFFC}' {
                        break;
                    }
                    // 한글이 아니고 라틴이면 다른 토큰으로 분리
                    if !is_hangul(c) && is_latin(c) {
                        break;
                    }
                    // CJK 한자/일본어는 개별 토큰
                    if is_cjk_ideograph(c) {
                        break;
                    }

                    let utf16_pos = if i < char_offsets.len() {
                        char_offsets[i]
                    } else {
                        i as u32
                    };
                    let style_id = find_active_char_shape(char_shapes, utf16_pos);
                    let lang = if is_lang_neutral(c) {
                        token_lang
                    } else {
                        let detected = detect_lang_category(c);
                        token_lang = detected;
                        current_lang = detected;
                        detected
                    };
                    let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
                    let fs = token_line_font_size(styles, style_id);
                    if fs > max_fs {
                        max_fs = fs;
                    }
                    i += 1;
                }

                // 후행 금칙 문자 (줄 머리 금칙) 흡수
                while i < text_len
                    && is_line_start_forbidden(text_chars[i])
                    && text_chars[i] != '\n'
                    && text_chars[i] != '\t'
                {
                    let c = text_chars[i];
                    let utf16_pos = if i < char_offsets.len() {
                        char_offsets[i]
                    } else {
                        i as u32
                    };
                    let style_id = find_active_char_shape(char_shapes, utf16_pos);
                    let lang = if is_lang_neutral(c) {
                        current_lang
                    } else {
                        let detected = detect_lang_category(c);
                        current_lang = detected;
                        detected
                    };
                    let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
                    let fs = token_line_font_size(styles, style_id);
                    if fs > max_fs {
                        max_fs = fs;
                    }
                    i += 1;
                }

                if i > start {
                    // 토큰 폭과 **그 합을 이루는 글자별 폭**을 한 번에 받는다.
                    //
                    // 종전에는 글자별 폭을 inline control 이 있는 토큰에만 채웠다.
                    // 그러면 한 줄에 안 들어가는 보통의 한글 토큰이 글자 단위 폴백으로
                    // 내려갔을 때 `base_char_widths` 가 비어, 폴백이 측정과 무관한 상수
                    // (`line_max_fs.max(12.0)`) 로 글자를 잘랐다 — 같은 토큰을 재는 자가
                    // 둘이 된다. `#7407` 대상 셀(연속 줄 38208 HWPUNIT, 9pt 장평 95%)에서
                    // 실제 전진폭은 11.400px 인데 폴백은 12.000px 로 세어 줄마다 42자만
                    // 담았다 — 43번째 글자는 19px 을 남기고 들어가는데도 거부됐다.
                    // 한/글 출력은 같은 줄에 44자를 담는다.
                    let (width, char_widths) = try_measure_token_chars(
                        &metric_scope,
                        &text_chars[start..i],
                        start,
                        char_offsets,
                        char_shapes,
                        styles,
                        current_lang,
                        inline_controls,
                        true,
                        storage,
                    )?;
                    storage.push(
                        &mut tokens,
                        BreakToken::Text {
                            start_idx: start,
                            end_idx: i,
                            base_width: width,
                            width,
                            max_font_size: max_fs,
                            base_char_widths: storage.copy_slice(&char_widths)?,
                            char_widths,
                        },
                    )?;
                }
                continue;
            } else {
                // 글자 모드: 한글·CJK의 한 글자와 뒤따르는 줄머리 금칙을 함께 소유한다.
                // CJK도 독립 Print의 `滴下|物)`처럼 닫는 괄호를 앞 글자와 묶는다.
                let utf16_pos = if i < char_offsets.len() {
                    char_offsets[i]
                } else {
                    i as u32
                };
                let style_id = find_active_char_shape(char_shapes, utf16_pos);
                current_lang = detect_lang_category(ch);
                let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
                let fs = token_line_font_size(styles, style_id);
                // [#7702] 첫가끝 자모(초성+중성(+종성))는 한 글자다 — 옛한글 `ᄒᆞᆫ` 을 자모마다
                // 한 글자 폭으로 재면 줄을 두 글자 일찍 끊는다. 그리기(`split_into_clusters`)처럼
                // 묶어 잰다.
                let cluster_end = hangul_jamo_cluster_end(text_chars, i);
                let mut single = [0u8; 4];
                let display = metric_display(&text_chars[i..cluster_end], &mut single, storage)?;
                let mut w = estimate_text_width_unrounded(&display, &ts)
                    + (i..cluster_end)
                        .map(|idx| inline_width_px_at(inline_controls, idx, styles))
                        .sum::<f64>();
                // 글자 모드에서도 **줄 머리 금칙**을 지킨다.
                //
                // 어절 모드(위 분기)만 후행 금칙 문자를 앞 토큰에 흡수하고 있어, 글자 모드
                // 문단은 쉼표·가운뎃점이 다음 줄 첫 글자로 내려갔다. 한글은 같은 문단 설정에서도
                // 그렇게 조판하지 않는다 — 실측: 원본 파일 284줄 중 줄머리 금칙 0건,
                // 우리 재조판 291줄 중 6건(", 생산성 정체를…" · "·경쟁하면서…").
                // 저장된 사다리가 있는 문서는 그 값을 쓰므로 영향이 없고, 편집·붙여넣기처럼
                // 다시 조판하는 경우에만 달라진다.
                let start = i;
                i = cluster_end;
                while i < text_len
                    && is_line_start_forbidden(text_chars[i])
                    && text_chars[i] != '\n'
                    && text_chars[i] != '\t'
                    // 🔴 금칙 문자 바로 뒤에 라틴/숫자 낱말이 이어지면 앞 글자에 붙이지 않는다.
                    // 한컴은 `한다.111…` 에서 `.` 을 앞의 `다` 가 아니라 뒤의 숫자 낱말에 붙여
                    // 통째로 다음 줄로 내린다(#2214 핀: 줄 시작 129 = `.`). 뒤가 공백·한글·끝이면
                    // 종전대로 앞 글자에 흡수한다(`, 생산성`·`‧기업` — 정답지 284줄 줄머리 금칙 0건).
                    && !text_chars
                        .get(i + 1)
                        .is_some_and(|next| next.is_ascii_alphanumeric())
                {
                    let follow_pos = if i < char_offsets.len() {
                        char_offsets[i]
                    } else {
                        i as u32
                    };
                    let follow_style = find_active_char_shape(char_shapes, follow_pos);
                    // [#7702] 흡수한 글자도 제 슬롯으로 잰다 — `·` 는 앞 글자가 한글이어도
                    // 영문 슬롯이다(어절 모드 갈래와 같은 규칙).
                    let follow_lang = if is_lang_neutral(text_chars[i]) {
                        current_lang
                    } else {
                        detect_lang_category(text_chars[i])
                    };
                    let follow_ts =
                        metric_scope.try_style(styles, follow_style, follow_lang, i, storage)?;
                    w += reflow_scalar_width(text_chars[i], &follow_ts)
                        + inline_width_px_at(inline_controls, i, styles);
                    i += 1;
                }
                storage.push(
                    &mut tokens,
                    BreakToken::Text {
                        start_idx: start,
                        end_idx: i,
                        base_width: w,
                        width: w,
                        max_font_size: fs,
                        base_char_widths: vec![],
                        char_widths: vec![],
                    },
                )?;
                continue;
            }
        }

        // 라틴 단어 또는 글자
        if is_latin(ch) {
            if english_break_unit == 0 || english_break_unit == 1 {
                // 단어/하이픈 모드: 연속 라틴 문자를 하나의 토큰으로
                let start = i;
                let mut max_fs = 0.0f64;

                while i < text_len {
                    let c = text_chars[i];
                    if soft_hyphen_control && c == '\u{00AD}' {
                        break;
                    }
                    if c == ' ' || c == '\n' || c == '\t' {
                        break;
                    }
                    if !is_latin(c) && !stays_in_latin_word(c) {
                        break;
                    }
                    // 하이픈 모드: 하이픈에서 분할 (하이픈 포함 후 분리)
                    if english_break_unit == 1 && c == '-' && i > start {
                        let utf16_pos = if i < char_offsets.len() {
                            char_offsets[i]
                        } else {
                            i as u32
                        };
                        let style_id = find_active_char_shape(char_shapes, utf16_pos);
                        let lang = 1usize; // English
                        let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
                        let fs = token_line_font_size(styles, style_id);
                        if fs > max_fs {
                            max_fs = fs;
                        }
                        i += 1;
                        break; // 하이픈 뒤에서 분할
                    }

                    let utf16_pos = if i < char_offsets.len() {
                        char_offsets[i]
                    } else {
                        i as u32
                    };
                    let style_id = find_active_char_shape(char_shapes, utf16_pos);
                    let lang = if is_lang_neutral(c) {
                        current_lang
                    } else {
                        current_lang = 1; // English
                        1
                    };
                    let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
                    let fs = token_line_font_size(styles, style_id);
                    if fs > max_fs {
                        max_fs = fs;
                    }
                    i += 1;
                }

                if i > start {
                    let (width, _) = try_measure_token_chars(
                        &metric_scope,
                        &text_chars[start..i],
                        start,
                        char_offsets,
                        char_shapes,
                        styles,
                        current_lang,
                        inline_controls,
                        false,
                        storage,
                    )?;
                    // 개별 글자 폭 수집 (char_level_break용)
                    let mut cw = storage.vec(i - start)?;
                    for ci in start..i {
                        let c = text_chars[ci];
                        let u16p = if ci < char_offsets.len() {
                            char_offsets[ci]
                        } else {
                            ci as u32
                        };
                        let sid = find_active_char_shape(char_shapes, u16p);
                        let lang = if is_lang_neutral(c) { current_lang } else { 1 };
                        let ts = metric_scope.try_style(styles, sid, lang, ci, storage)?;
                        cw.push(
                            reflow_scalar_width(c, &ts)
                                + inline_width_px_at(inline_controls, ci, styles),
                        );
                    }
                    storage.push(
                        &mut tokens,
                        BreakToken::Text {
                            start_idx: start,
                            end_idx: i,
                            base_width: width,
                            width,
                            max_font_size: max_fs,
                            base_char_widths: storage.copy_slice(&cw)?,
                            char_widths: cw,
                        },
                    )?;
                }
                continue;
            } else {
                // 글자 모드
                let utf16_pos = if i < char_offsets.len() {
                    char_offsets[i]
                } else {
                    i as u32
                };
                let style_id = find_active_char_shape(char_shapes, utf16_pos);
                current_lang = 1;
                let ts = metric_scope.try_style(styles, style_id, current_lang, i, storage)?;
                let fs = token_line_font_size(styles, style_id);
                let w =
                    reflow_scalar_width(ch, &ts) + inline_width_px_at(inline_controls, i, styles);
                storage.push(
                    &mut tokens,
                    BreakToken::Text {
                        start_idx: i,
                        end_idx: i + 1,
                        base_width: w,
                        width: w,
                        max_font_size: fs,
                        base_char_widths: vec![],
                        char_widths: vec![],
                    },
                )?;
                i += 1;
                continue;
            }
        }

        // 기타 문자 (기호, NonBreakingSpace 등): 개별 Text 토큰
        {
            let utf16_pos = if i < char_offsets.len() {
                char_offsets[i]
            } else {
                i as u32
            };
            let style_id = find_active_char_shape(char_shapes, utf16_pos);
            let lang = if is_lang_neutral(ch) {
                current_lang
            } else {
                let detected = detect_lang_category(ch);
                current_lang = detected;
                detected
            };
            let ts = metric_scope.try_style(styles, style_id, lang, i, storage)?;
            let fs = token_line_font_size(styles, style_id);
            let w = reflow_scalar_width(ch, &ts) + inline_width_px_at(inline_controls, i, styles);
            storage.push(
                &mut tokens,
                BreakToken::Text {
                    start_idx: i,
                    end_idx: i + 1,
                    base_width: w,
                    width: w,
                    max_font_size: fs,
                    base_char_widths: vec![],
                    char_widths: vec![],
                },
            )?;
            i += 1;
        }
    }

    Ok(tokens)
}

/// 모든 토큰 분기가 원문 슬롯을 보존하며 동일한 표시 글리프를 측정한다.
fn reflow_scalar_width(ch: char, style: &crate::renderer::TextStyle) -> f64 {
    let display = super::verified_pua_replay_scalar(ch).unwrap_or(ch);
    let mut bytes = [0u8; 4];
    estimate_text_width_unrounded(display.encode_utf8(&mut bytes), style)
}

/// 토큰 텍스트의 폭을 글자별 언어 인식 측정으로 합산한다.
fn measure_token_width(
    metric_scope: &ParagraphMetricScope,
    text: &str,
    start_char_idx: usize,
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    default_lang: usize,
    inline_controls: &[FlowInlineControl],
) -> f64 {
    let mut iter = text.chars();
    let first = iter.next();
    if let Some(first) = first.filter(|_| iter.clone().next().is_none()) {
        return match try_measure_token_chars(
            metric_scope,
            std::slice::from_ref(&first),
            start_char_idx,
            char_offsets,
            char_shapes,
            styles,
            default_lang,
            inline_controls,
            false,
            &crate::renderer::style_resolver::storage::Unbounded,
        ) {
            Ok((width, _)) => width,
            Err(never) => match never {},
        };
    }
    let chars: Vec<_> = text.chars().collect();
    match try_measure_token_chars(
        metric_scope,
        &chars,
        start_char_idx,
        char_offsets,
        char_shapes,
        styles,
        default_lang,
        inline_controls,
        false,
        &crate::renderer::style_resolver::storage::Unbounded,
    ) {
        Ok((width, _)) => width,
        Err(never) => match never {},
    }
}

/// Scalar display uses the shared mapping without per-glyph heap strings.
fn metric_display<'a, S: crate::renderer::style_resolver::storage::Storage>(
    chars: &[char],
    single: &'a mut [u8; 4],
    storage: &S,
) -> Result<std::borrow::Cow<'a, str>, S::Error> {
    if let [scalar] = chars {
        let scalar = super::verified_pua_replay_scalar(*scalar).unwrap_or(*scalar);
        return Ok(std::borrow::Cow::Borrowed(scalar.encode_utf8(single)));
    }
    Ok(std::borrow::Cow::Owned(
        storage.chars(
            chars
                .iter()
                .copied()
                .map(|c| super::verified_pua_replay_scalar(c).unwrap_or(c)),
        )?,
    ))
}

/// 토큰 전체 폭과, **그 합을 이루는 글자별 폭**을 함께 낸다.
///
/// 줄 나눔은 토큰이 통째로 들어갈 때는 합만 쓰고, 안 들어갈 때는 글자 단위 폴백에서
/// 개별 폭을 쓴다. 두 값이 같은 순회에서 나와야 한 토큰을 두 잣대로 재지 않는다.
/// 합은 종전 `measure_token_width` 와 같은 순서로 누적하므로 값이 바뀌지 않는다.
fn try_measure_token_chars<S: crate::renderer::style_resolver::storage::Storage>(
    metric_scope: &ParagraphMetricScope,
    chars: &[char],
    start_char_idx: usize,
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    default_lang: usize,
    inline_controls: &[FlowInlineControl],
    retain_widths: bool,
    storage: &S,
) -> Result<(f64, Vec<f64>), S::Error> {
    let mut total = 0.0;
    let mut char_widths = if retain_widths {
        storage.vec(chars.len())?
    } else {
        Vec::new()
    };
    let mut current_lang = default_lang;
    let mut offset = 0;
    while offset < chars.len() {
        let ch = chars[offset];
        let idx = start_char_idx + offset;
        // [#7702] 첫가끝 자모 묶음은 한 글자 폭을 첫 자모에 주고 나머지는 0 으로 둔다
        // (글자별 폭 배열의 칸 수는 글자 수와 같아야 한다).
        let cluster_end = hangul_jamo_cluster_end(&chars, offset);
        let utf16_pos = if idx < char_offsets.len() {
            char_offsets[idx]
        } else {
            idx as u32
        };
        let style_id = find_active_char_shape(char_shapes, utf16_pos);
        let lang = if is_lang_neutral(ch) {
            current_lang
        } else {
            let detected = detect_lang_category(ch);
            current_lang = detected;
            detected
        };
        let ts = metric_scope.try_style(styles, style_id, lang, idx, storage)?;
        // 원문과 언어 슬롯은 유지하고 paint와 같은 1:1 표시 글리프로 잰다.
        let mut single = [0u8; 4];
        let display = metric_display(&chars[offset..cluster_end], &mut single, storage)?;
        let width = estimate_text_width_unrounded(&display, &ts)
            + inline_width_px_at(inline_controls, idx, styles);
        total += width;
        if retain_widths {
            char_widths.push(width);
        }
        for tail in offset + 1..cluster_end {
            let tail_width = inline_width_px_at(inline_controls, start_char_idx + tail, styles);
            total += tail_width;
            if retain_widths {
                char_widths.push(tail_width);
            }
        }
        offset = cluster_end;
    }
    Ok((total, char_widths))
}

/// [#7702] `start` 에서 시작하는 첫가끝 자모 묶음(초성 + 중성 (+ 종성))의 끝 (배타).
/// 초성으로 시작하지 않거나 중성이 따르지 않으면 한 글자다. 그리기의 클러스터
/// (`split_into_clusters`)와 같은 묶음이다.
fn hangul_jamo_cluster_end(chars: &[char], start: usize) -> usize {
    let is_choseong =
        |c: char| ('\u{1100}'..='\u{115F}').contains(&c) || ('\u{A960}'..='\u{A97F}').contains(&c);
    let is_jungseong =
        |c: char| ('\u{1160}'..='\u{11A7}').contains(&c) || ('\u{D7B0}'..='\u{D7C6}').contains(&c);
    let is_jongseong =
        |c: char| ('\u{11A8}'..='\u{11FF}').contains(&c) || ('\u{D7CB}'..='\u{D7FB}').contains(&c);
    if !chars.get(start).is_some_and(|&c| is_choseong(c)) {
        return start + 1;
    }
    let mut end = start + 1;
    if chars.get(end).is_some_and(|&c| is_jungseong(c)) {
        end += 1;
        if chars.get(end).is_some_and(|&c| is_jongseong(c)) {
            end += 1;
        }
    }
    end
}

fn inline_width_px_at(
    inline_controls: &[FlowInlineControl],
    char_idx: usize,
    styles: &ResolvedStyleSet,
) -> f64 {
    // 스타일의 px 메트릭과 같은 배율로 원본 제어문의 HWPUNIT을 해소한다.
    let dpi = styles.resolved_dpi.unwrap_or(crate::renderer::DEFAULT_DPI);
    inline_controls
        .iter()
        .filter(|control| control.char_position == char_idx)
        .map(|control| hwpunit_to_px(control.width_hwp, dpi))
        .sum()
}

/// 기존 scalar tokenization과 같은 문자별 base pen을 만든 뒤, 그 입력 전체를
/// transaction-shared paragraph measurement cache에 건넨다.
fn prepare_paragraph_projection(
    para: &Paragraph,
    text_chars: &[char],
    styles: &ResolvedStyleSet,
    space_metric: SpaceMetric,
    inline_controls: &[FlowInlineControl],
) -> Option<PreparedParagraphProjection> {
    if text_chars.is_empty() {
        return None;
    }
    let mut current_lang = 0usize;
    let mut base_positions = Vec::with_capacity(text_chars.len().saturating_add(1));
    let metric_scope = ParagraphMetricScope::new(text_chars, styles)
        .with_space_metric(space_metric)
        .with_literal_figure_spaces(&para.literal_figure_spaces);
    let mut kerning_scalar_styles = Vec::with_capacity(text_chars.len());
    let mut shaping_scalar_styles = Vec::with_capacity(text_chars.len());
    let mut hard_boundaries = vec![false; text_chars.len().saturating_add(1)];
    let mut pen = 0.0f64;
    base_positions.push(pen);

    for (index, character) in text_chars.iter().copied().enumerate() {
        let language_index = if is_lang_neutral(character) {
            current_lang
        } else {
            let detected = detect_lang_category(character);
            current_lang = detected;
            detected
        };
        let utf16_pos = para
            .char_offsets
            .get(index)
            .copied()
            .unwrap_or(index as u32);
        let char_shape_id = find_active_char_shape(&para.char_shapes, utf16_pos);
        let text_style = metric_scope.style(styles, char_shape_id, language_index, index);
        let base_font_size = text_style.effective_font_size();
        let effective_font_size_px = text_style.script_font_size(base_font_size);
        let width_ratio = if text_style.ratio > 0.0 {
            text_style.ratio
        } else {
            1.0
        };
        let slot = crate::renderer::kerning::ExactFontSlot::new(char_shape_id, language_index);
        kerning_scalar_styles.push(crate::renderer::kerning::KerningParagraphScalarStyle {
            slot,
            requested: text_style.kerning,
            effective_font_size_px,
            width_ratio,
        });
        shaping_scalar_styles.push(
            crate::renderer::shaping_paragraph::HorizontalShapingParagraphScalarStyle {
                slot,
                effective_font_size_px,
                width_ratio,
                letter_spacing_px: text_style.letter_spacing,
                kerning: text_style.kerning,
                bold: text_style.bold,
                italic: text_style.italic,
                superscript: text_style.superscript,
                subscript: text_style.subscript,
            },
        );

        let scalar_width = match character {
            '\u{FFFC}'
                if inline_controls
                    .iter()
                    .any(|control| control.char_position == index) =>
            {
                0.0
            }
            '\t' | '\n' | '\r' => 0.0,
            ' ' => space_metric.space_advance(&text_style),
            _ => reflow_scalar_width(character, &text_style),
        } + inline_width_px_at(inline_controls, index, styles);
        pen += scalar_width.max(0.0);
        base_positions.push(pen);
    }

    for control in inline_controls {
        let boundary = control.char_position.min(text_chars.len());
        hard_boundaries[boundary] = true;
        if boundary < text_chars.len() {
            hard_boundaries[boundary + 1] = true;
        }
    }
    Some(PreparedParagraphProjection {
        base_positions,
        kerning_scalar_styles,
        shaping_scalar_styles,
        hard_boundaries,
    })
}

fn prepare_paragraph_kerning(
    para: &Paragraph,
    text_chars: &[char],
    styles: &ResolvedStyleSet,
    space_metric: SpaceMetric,
    inline_controls: &[FlowInlineControl],
) -> Option<PreparedParagraphKerning> {
    // 모델 한 칸→표시 여러 글자의 값은 현재 scalar 커닝 투영의 지원 범위 밖이다.
    if !para.layout_field_values.is_empty() {
        return None;
    }
    let paragraph_requests_kerning = if para.char_shapes.is_empty() {
        styles
            .char_styles
            .first()
            .is_some_and(|style| style.kerning)
    } else {
        para.char_shapes.iter().any(|shape| {
            styles
                .char_styles
                .get(shape.char_shape_id as usize)
                .is_some_and(|style| style.kerning)
        })
    };
    if !paragraph_requests_kerning {
        return None;
    }
    let context = styles.kerning_measurement_context.as_ref()?.clone();
    let projection =
        prepare_paragraph_projection(para, text_chars, styles, space_metric, inline_controls)?;
    if !projection
        .kerning_scalar_styles
        .iter()
        .any(|style| style.requested)
    {
        return None;
    }
    let measurement = context.paragraph_measurement(
        &para.text,
        projection.base_positions,
        &projection.kerning_scalar_styles,
        &projection.hard_boundaries,
    );
    if measurement.disposition
        != crate::renderer::kerning::KerningParagraphMeasurementDisposition::PairAdjusted
    {
        return None;
    }

    Some(PreparedParagraphKerning {
        context,
        scalar_styles: projection.kerning_scalar_styles,
        hard_boundaries: projection.hard_boundaries,
        measurement,
    })
}

fn has_rtl_or_bidi_control(text: &str) -> bool {
    text.chars().any(|character| {
        matches!(
            character as u32,
            0x0590..=0x08FF
                | 0xFB1D..=0xFDFF
                | 0xFE70..=0xFEFF
                | 0x10800..=0x10FFF
                | 0x1E800..=0x1EEFF
                | 0x200E..=0x200F
                | 0x202A..=0x202E
                | 0x2066..=0x2069
        )
    })
}

/// Run Q2-C only at the opt-in composition boundary and retain the exact Arc
/// returned by the transaction.  Every malformed or unsupported input maps to
/// `None`; the legacy `ComposedParagraph` fields are never rewritten here.
pub(super) fn compose_horizontal_shaping_handoff(
    para: &Paragraph,
    composed: &ComposedParagraph,
    styles: &ResolvedStyleSet,
) -> Option<std::sync::Arc<crate::renderer::shaping_paragraph::HorizontalShapingLineOutcome>> {
    let kerning_context = styles.kerning_measurement_context.as_ref()?;
    let shaping_context = styles.horizontal_shaping_context.as_ref()?;
    if kerning_context.registry_generation() != shaping_context.registry_generation() {
        return None;
    }
    let q2_candidate =
        crate::renderer::shaping_paragraph::is_bounded_horizontal_shaping_candidate_text(
            &para.text,
        );
    if !q2_candidate && shaping_context.instance_request_count() == 0 {
        return None;
    }

    let text_chars = para.text.chars().collect::<Vec<_>>();
    let inline_controls = flow_inline_controls(para, styles);
    let projection = prepare_paragraph_projection(
        para,
        &text_chars,
        styles,
        SpaceMetric::Stored,
        &inline_controls,
    )?;
    let kerning_measurement = kerning_context.paragraph_measurement(
        &para.text,
        projection.base_positions.clone(),
        &projection.kerning_scalar_styles,
        &projection.hard_boundaries,
    );
    let (fallback_positions, fallback_owner) = if kerning_measurement.disposition
        == crate::renderer::kerning::KerningParagraphMeasurementDisposition::PairAdjusted
    {
        (
            kerning_measurement.positions(),
            crate::renderer::shaping_paragraph::HorizontalShapingFallbackOwner::W9K1,
        )
    } else {
        (
            projection.base_positions.as_slice(),
            crate::renderer::shaping_paragraph::HorizontalShapingFallbackOwner::ExistingK0,
        )
    };

    let code_point_count = text_chars.len();
    let mut candidate_boundaries = composed
        .lines
        .iter()
        .map(|line| line.char_start)
        .chain(std::iter::once(code_point_count))
        .collect::<Vec<_>>();
    candidate_boundaries.sort_unstable();
    candidate_boundaries.dedup();
    if candidate_boundaries
        .iter()
        .any(|index| *index > code_point_count)
    {
        return None;
    }
    let available_widths_px = composed
        .lines
        .iter()
        .map(|line| hwpunit_to_px(line.segment_width, 96.0))
        .collect::<Vec<_>>();
    if available_widths_px.is_empty()
        || available_widths_px
            .iter()
            .any(|width| !width.is_finite() || *width <= 0.0)
    {
        return None;
    }

    let composed_text = composed
        .lines
        .iter()
        .flat_map(|line| line.runs.iter())
        .map(|run| run.text.as_str())
        .collect::<String>();
    let has_char_overlap = composed
        .lines
        .iter()
        .flat_map(|line| line.runs.iter())
        .any(|run| run.char_overlap.is_some());
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    let paragraph = crate::renderer::shaping_paragraph::HorizontalShapingParagraphRequest {
        attempt_id_base: 1,
        text: &para.text,
        fallback_positions,
        scalar_styles: &projection.shaping_scalar_styles,
        hard_boundaries: &projection.hard_boundaries,
        fallback_owner,
        model_text_matches_shaping_text: composed_text == para.text,
        horizontal_ltr_bidi0: !has_rtl_or_bidi_control(&para.text),
        condense_min_space: para_style
            .map(|style| style.condense_min_space)
            .unwrap_or(0),
        has_inline_controls: !para.controls.is_empty(),
        has_tabs: para.text.contains('\t'),
        has_rotation: false,
        has_char_overlap,
    };
    let request = crate::renderer::shaping_paragraph::HorizontalShapingLineRequest {
        paragraph,
        candidate_boundaries: &candidate_boundaries,
        available_widths_px: &available_widths_px,
    };
    let outcome = if q2_candidate {
        let mut transaction = shaping_context.transaction();
        std::sync::Arc::new(
            crate::renderer::shaping_paragraph::run_horizontal_shaping_line_transaction(
                &mut transaction,
                &request,
            ),
        )
    } else {
        let line = composed.lines.first()?;
        let run = line.runs.first()?;
        if composed.lines.len() != 1
            || line.runs.len() != 1
            || line.has_line_break
            || line.char_start != 0
            || run.text != para.text
            || run.display_text.is_some()
        {
            return None;
        }
        let slot = projection.shaping_scalar_styles.first()?.slot;
        let mut transaction = shaping_context.explicit_instance_transaction(slot).ok()?;
        // An explicit default remains distinct in the request registry and
        // shaping cache, but must not widen the product activation surface.
        // Returning to the existing composer here preserves Q2 pixels and
        // geometry; only a canonical non-default instance may publish the
        // Q3-E portable pair.
        if transaction.is_default_instance() {
            return None;
        }
        if !crate::renderer::shaping_paragraph::is_bounded_explicit_instance_candidate_text(
            &para.text,
        ) {
            return None;
        }
        std::sync::Arc::new(
            crate::renderer::shaping_paragraph::run_bounded_explicit_instance_line_transaction(
                &mut transaction,
                &request,
            ),
        )
    };
    crate::renderer::shaping_composition::retain_qualified_horizontal_shaping_outcome(outcome)
}

fn apply_paragraph_kerning_to_tokens(
    tokens: &mut [BreakToken],
    measurement: &crate::renderer::kerning::KerningParagraphMeasurement,
) -> Option<()> {
    for token in tokens {
        let BreakToken::Text {
            start_idx,
            end_idx,
            width,
            char_widths,
            ..
        } = token
        else {
            continue;
        };
        *width = measurement.range_width(*start_idx, *end_idx)?;
        *char_widths = (*start_idx..*end_idx)
            .map(|index| measurement.range_width(index, index + 1))
            .collect::<Option<Vec<_>>>()?;
    }
    Some(())
}

/// px를 HWPUNIT(i32)로 변환 (내림, DPI=96 기준: px * 75)
///
/// [#7702] 정수 HWPUNIT 인 폭(예: 880 HU = 11.7333…px)이 부동소수 오차로 그 아래에
/// 놓이면 절삭이 한 단위를 잃는다. 오차 범위 안이면 그 정수로 본다.
#[inline]
fn to_hwp(px: f64) -> i32 {
    let scaled = px * 75.0;
    let nearest = scaled.round();
    if (scaled - nearest).abs() <= 1e-6 {
        nearest as i32
    } else {
        scaled as i32
    }
}

/// [#7418] 이 공백 앞에 같은 줄의 글자가 하나도 없는가 — 줄 맨 앞 공백.
///
/// 한/글은 줄 맨 앞 공백을 condense 로 줄이지 않는다. 문단 첫 줄의 들여 쓴 공백
/// 0·2·4·6 개를 condense 50·75 로 바꾼 합성 문단 8개의 줄 끊음을 한/글 2024 가
/// 저장한 줄과 맞대면, 맨 앞 공백을 줄이지 않는 모형만 8/8 로 맞는다(줄이는 모형 2/8).
fn space_is_line_leading(text_chars: &[char], line_start: usize, space_idx: usize) -> bool {
    text_chars
        .get(line_start..space_idx)
        .is_none_or(|before| before.iter().all(|c| *c == ' '))
}

/// 공백 하나를 condense 로 줄일 수 있는 폭. `space_width_hwp` 는 자간 **적용 전** 폭이다
/// (`BreakToken::Space::condense_base`).
fn condense_space_savings_hwp(space_width_hwp: i32, condense_min_space: u8) -> i32 {
    if condense_min_space == 0 || space_width_hwp <= 0 {
        return 0;
    }
    let shrink_percent = condense_min_space.min(75) as i32;
    space_width_hwp * shrink_percent / 100
}

/// 실제 배치도 줄 수용과 같은 원본 HU 공백 예산을 소비한다.
pub(crate) fn condense_space_savings_px(space_width_px: f64, percent: u8, dpi: f64) -> f64 {
    let source_width = to_hwp(space_width_px * crate::renderer::DEFAULT_DPI / dpi);
    crate::renderer::hwpunit_to_px(condense_space_savings_hwp(source_width, percent), dpi)
}

fn condensed_line_width_hwp(width_hwp: i32, space_savings_hwp: i32) -> i32 {
    width_hwp - space_savings_hwp
}

/// 낱말 사이 첫 구분 공백은 뒤의 작성 공백과 같은 종료 컷이 아니다.
/// 독립 한컴 Print의 맑은 고딕/HFT 대조에서는 첫 구분 공백이 넘쳐도
/// 다음 공백까지 앞줄에 걸고, 나머지 작성 공백만 다음 줄에서 전진한다.
/// 문단 끝·명시적 개행·앞줄에서 이월된 공백과 개체 슬롯은 기존 계약을 유지한다.
fn first_interword_separator(
    tokens: &[BreakToken],
    token_index: usize,
    text_chars: &[char],
    line_start: usize,
) -> bool {
    let Some(BreakToken::Space {
        idx, inline_width, ..
    }) = tokens.get(token_index)
    else {
        return false;
    };
    if *idx <= line_start
        || *inline_width != 0.0
        || text_chars.get(*idx) != Some(&' ')
        || !text_chars
            .get(idx - 1)
            .is_some_and(|ch| !ch.is_whitespace() && !ch.is_control() && *ch != '\u{FFFC}')
    {
        return false;
    }
    let mut next_index = idx + 1;
    let mut additional_space = false;
    for token in tokens.iter().skip(token_index + 1) {
        match token {
            BreakToken::Space {
                idx, inline_width, ..
            } if *idx == next_index
                && *inline_width == 0.0
                && text_chars.get(*idx) == Some(&' ') =>
            {
                additional_space = true;
                next_index += 1;
            }
            BreakToken::Text {
                start_idx,
                end_idx,
                width,
                ..
            } => {
                return additional_space
                    && *start_idx == next_index
                    && end_idx > start_idx
                    && *width > 0.0;
            }
            _ => return false,
        }
    }
    false
}

/// Hancom absorbs the first overflowing blank at the end of the row, then
/// continues the remaining blanks on the next row (#7168). A visible inline
/// object at that offset must instead move with its space. Both fill paths use
/// this cut so ownership is not guessed separately during projection.
pub(crate) fn overflowing_space_cut(
    line_start: usize,
    space_idx: usize,
    width_hwp: i32,
    savings_hwp: i32,
    available_hwp: i32,
    // 공백 앞에 놓인 개체의 끝(개체가 없으면 None)과 그 시점까지의 condense 절감.
    inline_object_end: Option<(i32, i32)>,
) -> Option<usize> {
    if condensed_line_width_hwp(width_hwp, savings_hwp) <= available_hwp {
        None
    } else if inline_object_end.is_none_or(|(object_end_hwp, object_savings_hwp)| {
        // [#7840] 개체 자체는 줄 끝에 걸 수 없지만, 개체가 상자 안에 들어가면 넘치는 것은
        // 뒤따르는 공백뿐이고 그 공백은 다른 공백처럼 줄 끝에 건다 — 156465345 꼬리말:
        // 로고 셋이 48112 HU 로 48190 상자 안에 들지만 마지막 공백 432 HU 까지 더해
        // 넘친다고 판정해 셋째 로고를 둘째 줄로 내렸다(한/글은 한 줄, x=632.5px).
        condensed_line_width_hwp(object_end_hwp, object_savings_hwp) <= available_hwp
    }) {
        Some(space_idx + 1)
    } else if space_idx > line_start {
        Some(space_idx)
    } else {
        // Oversized first objects still belong to the object overflow policy.
        None
    }
}

// 한컴은 HWPUNIT 정수 양자화 시 미세한 반올림 차이를 허용한다.
// 이 값 이내의 초과는 줄에 포함한다.
//
// 15 는 실측보다 작았다. 한컴이 저장한 조판을 우리 폭 지표로 되재면, 한컴이 **받아들인**
// 줄들이 상자를 38·113·188 HWPUNIT 씩 넘는다(간격 75 HU = 1px — 줄 안 run 수에 따른
// 추정 오차 누적으로 보인다). 줄바꿈은 실제 글꼴이 아니라 엔진의 폭 **추정**으로 정해지므로
// 이 여유가 그 추정 오차를 흡수하는 자리다. 15 에서는 한컴이 담은 줄을 우리가 잘라
// 줄마다 마지막 글자가 밀렸다.
// 실측 스윕(재조판 ↔ 한컴 저장 조판 줄 단위 일치율): 15·40 → 65.0% / **50 → 82.3%** /
// 60~100 → 81.6% / 150 → 79.7% / 300 → 74.4%. 너무 키우면 반대로 과하게 담는다.
//
// 🔴 그 50 은 **본문 폭 38,640 HWPUNIT 짜리 줄에서 잰 값**이다. 오차가 줄 안 run 수를 따라
// 쌓이는 것이므로 여유도 상자 폭에 비례해야 한다. 상수로 두면 폭이 14배 좁은 표 칸
// (2,720 HU)에서 글자 폭의 5.5% 나 되는 **진짜 초과**까지 삼켜, 한컴이 두 줄로 쪼개는 문단이
// 한 줄로 남는다(셀 안 여백을 키운 뒤 재조판). 하한 15 는 종전 상수값이라 어떤 상자도
// 그보다 빡빡해지지 않는다.
const LINE_BREAK_TOLERANCE_MIN_HWP: i32 = 15;
const LINE_BREAK_TOLERANCE_MAX_HWP: i32 = 50;
/// 여유 1 HWPUNIT 당 상자 폭 — 38,640 / 50 ≈ 760.
const LINE_BREAK_TOLERANCE_WIDTH_PER_HWP: i32 = 760;

/// 상자 폭에 비례하는 줄바꿈 여유(HWPUNIT).
#[inline]
fn line_break_tolerance_hwp(box_width_hwp: i32) -> i32 {
    (box_width_hwp.max(0) / LINE_BREAK_TOLERANCE_WIDTH_PER_HWP)
        .clamp(LINE_BREAK_TOLERANCE_MIN_HWP, LINE_BREAK_TOLERANCE_MAX_HWP)
}

/// 이 토큰이 줄 안에서 **새 낱말을 시작**하면, 그 앞 공백들 직전까지의 자연폭.
///
/// 바로 앞 토큰이 이 줄의 공백이 아니면 이어지는 글자이므로 `None` 이다.
/// 이월(#3822) 재확인처럼 채움 상태가 없는 자리에서 토큰으로 다시 계산한다.
fn new_word_natural_before_hwp(
    tokens: &[BreakToken],
    token_idx: usize,
    line_start: usize,
) -> Option<i32> {
    let mut k = token_idx;
    while k > 0 {
        match &tokens[k - 1] {
            BreakToken::Space { idx, .. } if *idx >= line_start => k -= 1,
            _ => break,
        }
    }
    if k == token_idx {
        return None;
    }
    let width = recalc_width_hwp(tokens, k, line_start);
    (width > 0).then_some(width)
}

/// Letter spacing is excluded from the fit test and included in the pen.
///
/// The pen already carries every earlier glyph's letter spacing. The fit
/// comparison omits only the candidate token's trailing letter space—one per
/// candidate, not one per character.
///
/// Dropping it from every character instead — the reading a summary of this
/// divergence invites — is arithmetically the single-shape blindness of
/// `compose_lines`' NO_LS fallback, which measures a paragraph with
/// `char_shapes[0]`'s spacing throughout. Measured, it reproduced the retired
/// cell wrap character for character against Hancom's own PDF and cost 12 tests
/// across six unrelated fixture families. At this stage the suite is unchanged.
///
/// Negative spacing is legal, so the sign is not fixed. For non-negative 자간
/// the candidate becomes narrower; under compressed 자간 the omission makes
/// the candidate wider and the fit stricter (`76076_regulatory_analysis` runs
/// `-0.16…-1.76` px).
/// Forced to 0 under an active character grid, which is inert here: every
/// corpus section has `char_grid == 0`.
/// [#7418] 이 글자 모양의 ASCII 구두점을 영문 슬롯으로 재는가
/// ([`ResolvedCharStyle::ascii_punct_latin_slot`]).
///
/// [`ResolvedCharStyle::ascii_punct_latin_slot`]: crate::renderer::style_resolver::ResolvedCharStyle::ascii_punct_latin_slot
fn punct_latin_slot(styles: &ResolvedStyleSet, style_id: u32) -> bool {
    styles
        .char_styles
        .get(style_id as usize)
        .is_some_and(|style| style.ascii_punct_latin_slot)
}

fn fit_test_letter_spacing_trim_hwp(letter_spacing_px: &[f64], token_end_idx: usize) -> i32 {
    if token_end_idx == 0 {
        return 0;
    }
    letter_spacing_px
        .get(token_end_idx - 1)
        .map(|spacing| to_hwp(*spacing))
        .unwrap_or(0)
}

/// 원문 문자별 실제 글리프 자간이다. 선언된 글꼴 크기 비율과 구분한다.
/// 줄 채움과 최종 정렬이 동일한 표시 문자·슬롯·측정 함수를 소비한다.
fn resolved_letter_spacing_px(
    chars: &[char],
    offsets: &[u32],
    shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    space: SpaceMetric,
    literal_figure_spaces: &[usize],
) -> Vec<f64> {
    match try_resolved_letter_spacing_px(
        chars,
        offsets,
        shapes,
        styles,
        space,
        literal_figure_spaces,
        &Unbounded,
    ) {
        Ok(values) => values,
        Err(never) => match never {},
    }
}

fn try_resolved_letter_spacing_px<S: Storage>(
    text_chars: &[char],
    char_offsets: &[u32],
    char_shapes: &[CharShapeRef],
    styles: &ResolvedStyleSet,
    space_metric: SpaceMetric,
    literal_figure_spaces: &[usize],
    storage: &S,
) -> Result<Vec<f64>, S::Error> {
    let mut lang = 0usize;
    let metric_scope = ParagraphMetricScope::try_new(text_chars, styles, storage)?
        .with_space_metric(space_metric)
        .with_literal_figure_spaces(literal_figure_spaces);
    let mut values = storage.vec(text_chars.len())?;
    for (idx, ch) in text_chars.iter().enumerate() {
        let utf16_pos = char_offsets.get(idx).copied().unwrap_or(idx as u32);
        let style_id = find_active_char_shape(char_shapes, utf16_pos);
        // [#7418] 영문 슬롯으로 재는 구두점은 자간도 영문 슬롯 값이다(`char_width_decision`).
        let char_lang = char_lang_slot(*ch, &mut lang, punct_latin_slot(styles, style_id));
        let spacing_lang = super::punctuation_slots::metric_slot(*ch, char_lang, styles, style_id);
        // 자간이 없는 대부분의 문자에서는 스타일 복제와 재측정을 피한다.
        if resolved_letter_spacing(styles, style_id, spacing_lang) == 0.0 {
            values.push(0.0);
            continue;
        }
        let style = metric_scope.try_style(styles, style_id, char_lang, idx, storage)?;
        values.push(glyph_letter_spacing_advance(
            ch.encode_utf8(&mut [0; 4]),
            &style,
        ));
    }
    Ok(values)
}

fn resolved_paragraph_letter_spacing(
    para: &Paragraph,
    chars: &[char],
    styles: &ResolvedStyleSet,
    space: SpaceMetric,
) -> Vec<f64> {
    match try_resolved_paragraph_letter_spacing(para, chars, styles, space, &Unbounded) {
        Ok(values) => values,
        Err(never) => match never {},
    }
}

fn try_resolved_paragraph_letter_spacing<S: Storage>(
    para: &Paragraph,
    text_chars: &[char],
    styles: &ResolvedStyleSet,
    space_metric: SpaceMetric,
    storage: &S,
) -> Result<Vec<f64>, S::Error> {
    let mut values = try_resolved_letter_spacing_px(
        text_chars,
        &para.char_offsets,
        &para.char_shapes,
        styles,
        space_metric,
        &para.literal_figure_spaces,
        storage,
    )?;
    for (position, value) in &para.layout_field_values {
        if let Some(spacing) = values.get_mut(*position) {
            let shape = para.char_shape_id_at(*position).unwrap_or(0);
            let lang = value.chars().next().map(detect_lang_category).unwrap_or(0);
            *spacing = resolved_letter_spacing(styles, shape, lang);
        }
    }
    Ok(values)
}

/// fit test 에 쓰는 후보 폭. 펜이 전진하는 폭과 **다른 값**이다.
///
/// [#5678] 종전에는 두 값이 다 `i32` 라 호출부가 아무거나 넘길 수 있었고, 실제로
/// 한 자리만 자간을 뺀 값을 넘겼다. 자간이 0 인 문단에서는 두 값이 같아 어떤 테스트도
/// 차이를 잡지 못했다. 이제 원시 정수는 이 함수에 들어가지 못하고, 호출부는 생성자
/// 이름으로 어느 쪽인지 밝혀야 한다.
///
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct FitWidthHwp(i32);

impl FitWidthHwp {
    /// 후보 토큰의 마지막 글자 뒤 자간을 뺀 폭. 실사용 fill 이 쓰는 값이다.
    ///
    /// 줄 끝에 오는 글자의 뒤 자간은 그려지지 않으므로 들어가는지 따질 때 빼고 잰다.
    /// 펜은 전체 폭만큼 전진한다.
    fn trimmed(token_width_hwp: i32, letter_spacing_px: &[f64], token_end_idx: usize) -> Self {
        Self(token_width_hwp - fit_test_letter_spacing_trim_hwp(letter_spacing_px, token_end_idx))
    }

    /// 커닝 경계쌍 보정을 fit 판정 폭에 더한다 (#4439 커닝 세션과의 병합점).
    /// 펜 전진 폭에는 더하지 않는다 — fit 판정 전용 축이다.
    fn with_pair_adjustment(self, adjustment_hwp: i32) -> Self {
        Self(self.0 + adjustment_hwp)
    }
}

/// [#7418] 목록 마커를 얹은 줄 나눔 상자: `(가용폭에서 뺄 양, 들여쓰기)`.
/// 마커가 없으면 문단 들여쓰기 그대로다.
fn list_marker_breaker_box(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    indent_px: f64,
) -> (f64, f64) {
    crate::renderer::layout::list_marker_geometry(para, styles)
        .map_or((0.0, indent_px), |geometry| geometry.breaker_box(indent_px))
}

/// 토큰이 줄에 들어가는가 — 문단 `condense`(공백 최소값) 규칙 포함.
///
/// [#7418] 한/글은 공백을 condense% 까지 줄여 **이미 시작한 낱말**의 글자를 더 담는다.
/// 그러나 **새 낱말은 앞 줄이 자연폭으로 상자보다 좁을 때만** 시작한다 — 이미 공백을
/// 줄여야 하거나 자연폭으로 꽉 찬 줄에는 새 낱말을 들이지 않는다.
/// `new_word_natural_before_hwp` 는 이 토큰이 새 낱말을 시작할 때 그 앞 공백 직전까지의
/// 자연폭이다(이어지는 글자면 `None`).
///
/// 독립 근거는 한/글 2024 출력이다. condense 0·15·30·50·75, 낱말 길이, 글자/낱말 단위,
/// 글꼴(맑은 고딕·함초롬바탕·한양신명조), 본문/표 칸을 바꾼 합성 문단의 줄 끊음을 이 규칙이
/// 전부 재현한다(본문 208/208, 칸 211/211). 앞 줄이 상자를 **꼭 채운** 경우를 허용하면(≤)
/// 칸 문단이 148/211 로 떨어진다. 종전의 "남은 틈 2.5em 이상일 때만 condense" 문턱은
/// 68/208 줄만 맞았다.
fn text_token_fits_line_hwp(
    current_width_hwp: i32,
    token_width: FitWidthHwp,
    space_savings_hwp: i32,
    effective_width_hwp: i32,
    new_word_natural_before_hwp: Option<i32>,
) -> bool {
    text_token_fits_in_line_with_tolerance_hwp(
        current_width_hwp,
        token_width,
        space_savings_hwp,
        effective_width_hwp,
        new_word_natural_before_hwp,
        line_break_tolerance_hwp(effective_width_hwp),
    )
}

fn text_token_fits_in_line_with_tolerance_hwp(
    current_width_hwp: i32,
    token_width: FitWidthHwp,
    space_savings_hwp: i32,
    effective_width_hwp: i32,
    new_word_natural_before_hwp: Option<i32>,
    tolerance_hwp: i32,
) -> bool {
    let natural_candidate = current_width_hwp + token_width.0;
    let condensed_candidate = condensed_line_width_hwp(natural_candidate, space_savings_hwp);
    let limit_hwp = effective_width_hwp + tolerance_hwp;
    if natural_candidate <= limit_hwp {
        return true;
    }
    // 공백을 줄여야 들어가는 경우 — 줄바꿈 여유(자연폭 추정 오차 흡수용)를 얹지 않는다.
    // 한/글은 줄인 폭이 상자를 넘으면 받지 않는다: 합성 문단에서 상자를 5·30 HWPUNIT
    // 넘는 줄(여유 50 안)과 80168 49쪽 `…투자ㆍ운` + `용`(여유 31 안)을 모두 거절한다.
    if condensed_candidate > effective_width_hwp {
        return false;
    }
    !new_word_natural_before_hwp.is_some_and(|w| w >= effective_width_hwp)
}

/// Greedy line-fill continuation.
///
/// A visible-text boundary does not always identify the next token: a long
/// `Text` token can continue after an emitted row. Keep the complete state so
/// callers can fill one interval at a time without rediscovering a boundary.
#[derive(Debug, Clone)]
struct FillCursor {
    token_index: usize,
    fallback_char_idx: Option<usize>,
    initial_start_idx: usize,
    line_start_idx: usize,
    lw: i32,
    line_space_savings: i32,
    line_max_fs: f64,
    is_first_line: bool,
    last_break_token_idx: Option<usize>,
    last_break_char_idx: usize,
    width_at_last_break: i32,
    space_savings_at_last_break: i32,
    fs_at_last_break: f64,
    /// [#7418] 마지막으로 소비한 토큰이 이 줄의 공백이면, 그 공백 묶음 직전까지의 자연폭.
    /// 다음 글자 토큰이 새 낱말을 시작하는지와 그때 줄이 자연폭 안인지를 판정한다.
    word_gap_natural_hwp: Option<i32>,
    /// 물리 프레임의 폭이 확정되면 추정 메트릭의 초과 허용을 얹지 않는다.
    allow_metric_tolerance: bool,
    /// 등간격 탭 격자가 속한 단/셀 좌표계의 현재 줄 원점.
    tab_grid_origin_px: Option<f64>,
    finished: bool,
    emitted_any: bool,
}

impl FillCursor {
    fn new(initial_start_idx: usize, initial_is_first_line: bool) -> Self {
        Self {
            token_index: 0,
            fallback_char_idx: None,
            initial_start_idx,
            line_start_idx: initial_start_idx,
            lw: 0,
            line_space_savings: 0,
            line_max_fs: 0.0,
            is_first_line: initial_is_first_line,
            last_break_token_idx: None,
            last_break_char_idx: 0,
            width_at_last_break: 0,
            space_savings_at_last_break: 0,
            fs_at_last_break: 0.0,
            word_gap_natural_hwp: None,
            allow_metric_tolerance: true,
            tab_grid_origin_px: None,
            finished: false,
            emitted_any: false,
        }
    }

    fn replay_from_boundary(tokens: &[BreakToken], boundary: usize, first_line: bool) -> Self {
        let mut cursor = Self::new(boundary, first_line);
        cursor.token_index = tokens.partition_point(|token| match token {
            BreakToken::Text { end_idx, .. } => *end_idx <= boundary,
            BreakToken::DiscretionaryHyphen { idx, .. }
            | BreakToken::Space { idx, .. }
            | BreakToken::Tab { idx, .. }
            | BreakToken::LineBreak { idx } => *idx < boundary,
        });
        if let Some(BreakToken::Text { start_idx, .. }) = tokens.get(cursor.token_index) {
            if boundary > *start_idx {
                cursor.fallback_char_idx = Some(boundary);
            }
        }
        cursor
    }
}

/// [#7702] 줄 나눔이 탭을 전진하는 규칙. 그리기(`text_measurement` 의 탭 전진)와 같은 규칙이다 —
/// 문단 탭 정지는 **단 시작 기준 절대 위치**이고, 정지를 다 지나면 기본 등간격 탭도 단 기준이다.
///
/// 종전 줄 나눔은 탭 정지를 무시하고 줄 시작부터 기본 간격으로만 쟀다. 그래서 문단 왼쪽
/// 여백이나 사용자 탭 정지가 있으면 줄 나눔이 잰 탭 폭과 그려지는 탭 폭이 달랐다
/// (HWP5-nopassword 14쪽: 여백 12.65px · 탭 정지 3328HU 에서 그리기 31.7px, 줄 나눔 47.9px).
///
/// 오른쪽·가운데 탭은 뒤 글의 폭을 알아야 자리가 정해지므로 종전대로 줄 시작 기준 기본
/// 간격으로 잰다.
#[derive(Clone, Copy)]
struct TabFill<'a> {
    default_width_px: f64,
    stops: &'a [crate::renderer::TabStop],
    auto_tab_right: bool,
    /// 첫 줄·다음 줄의 줄 상자 시작 (단 시작 기준 px) — 문단 왼쪽 여백 + 그 줄의 들여쓰기.
    line_origin_px: [f64; 2],
    available_width_px: f64,
}

impl<'a> TabFill<'a> {
    fn default_only(default_width_px: f64) -> Self {
        Self {
            default_width_px,
            stops: &[],
            auto_tab_right: false,
            line_origin_px: [0.0, 0.0],
            available_width_px: 0.0,
        }
    }

    fn for_paragraph(
        para_style: Option<&'a ResolvedParaStyle>,
        indent_px: f64,
        available_width_px: f64,
    ) -> Self {
        let Some(style) = para_style else {
            return Self::default_only(0.0);
        };
        Self {
            default_width_px: style.default_tab_width,
            stops: &style.tab_stops,
            auto_tab_right: style.auto_tab_right,
            line_origin_px: [
                style.margin_left + indent_px.max(0.0),
                style.margin_left + (-indent_px).max(0.0),
            ],
            available_width_px,
        }
    }

    fn default_width(&self) -> f64 {
        if self.default_width_px > 0.0 {
            self.default_width_px
        } else {
            48.0
        }
    }

    /// 줄 안 위치 `lw_hwp` 의 탭이 끝나는 줄 안 위치(HWPUNIT).
    fn next_hwp(&self, lw_hwp: i32, first_line: bool, origin_override: Option<f64>) -> i32 {
        let lw_px = lw_hwp as f64 / 75.0;
        let origin = origin_override.unwrap_or(self.line_origin_px[usize::from(!first_line)]);
        let (position, tab_type, _) = crate::renderer::layout::find_next_tab_stop(
            origin + lw_px,
            self.stops,
            self.default_width(),
            self.auto_tab_right,
            self.available_width_px,
            // 그리기의 `text_start_offset`(문단 왼쪽 여백 + 그 줄의 들여쓰기)과 같은 값이다.
            origin,
        );
        match tab_type {
            0 | 3 => to_hwp(position - origin).max(lw_hwp),
            _ => to_hwp(((lw_px / self.default_width()).floor() + 1.0) * self.default_width()),
        }
    }
}

/// 내어쓰기 자동 탭의 문단 기준 도착점을 줄 채우기 토큰에 전달한다.
fn apply_auto_left_tab_targets(
    tokens: &mut [BreakToken],
    style: Option<&super::super::style_resolver::ResolvedParaStyle>,
) {
    let target = style
        .filter(|style| style.auto_tab_left)
        .map(|style| -style.indent)
        .filter(|target| *target > 0.0);
    for token in tokens {
        if let BreakToken::Tab {
            auto_left_target, ..
        } = token
        {
            *auto_left_target = target;
        }
    }
}

/// Fill all scalar intervals through the resumable greedy continuation.
fn fill_lines(
    tokens: &[BreakToken],
    text_chars: &[char],
    available_width_px: f64,
    indent_px: f64,
    tabs: TabFill<'_>,
    korean_break_unit: u8,
    condense_min_space: u8,
    letter_spacing_px: &[f64],
    initial_start_idx: usize,
    initial_is_first_line: bool,
    allow_metric_tolerance: bool,
    kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
) -> Vec<LineBreakResult> {
    match try_fill_lines(
        tokens,
        text_chars,
        available_width_px,
        indent_px,
        tabs,
        korean_break_unit,
        condense_min_space,
        letter_spacing_px,
        initial_start_idx,
        initial_is_first_line,
        allow_metric_tolerance,
        kerning,
        &Unbounded,
    ) {
        Ok(lines) => lines,
        Err(never) => match never {},
    }
}

fn try_fill_lines<S: Storage>(
    tokens: &[BreakToken],
    text_chars: &[char],
    available_width_px: f64,
    indent_px: f64,
    tabs: TabFill<'_>,
    korean_break_unit: u8,
    condense_min_space: u8,
    letter_spacing_px: &[f64],
    initial_start_idx: usize,
    initial_is_first_line: bool,
    allow_metric_tolerance: bool,
    mut kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
    storage: &S,
) -> Result<Vec<LineBreakResult>, S::Error> {
    let mut cursor = FillCursor::new(initial_start_idx, initial_is_first_line);
    cursor.allow_metric_tolerance = allow_metric_tolerance;
    let mut results = Vec::new();

    while let Some(interval) = fill_one_interval(
        tokens,
        text_chars,
        available_width_px,
        indent_px,
        tabs,
        korean_break_unit,
        condense_min_space,
        letter_spacing_px,
        &mut cursor,
        kerning.as_deref_mut(),
    ) {
        storage.push(&mut results, interval.line)?;
    }

    Ok(results)
}

/// Fill at most one logical row and retain the greedy continuation state.
fn fill_one_interval(
    tokens: &[BreakToken],
    text_chars: &[char],
    available_width_px: f64,
    indent_px: f64,
    tabs: TabFill<'_>,
    korean_break_unit: u8,
    condense_min_space: u8,
    letter_spacing_px: &[f64],
    cursor: &mut FillCursor,
    mut kerning: Option<&mut crate::renderer::kerning::KerningParagraphBreakSession<'_, '_, '_>>,
) -> Option<FilledInterval> {
    let allow_metric_tolerance = cursor.allow_metric_tolerance;
    let fits_physical_line = |current, token, savings, width, word| {
        text_token_fits_in_line_with_tolerance_hwp(
            current,
            token,
            savings,
            width,
            word,
            if allow_metric_tolerance {
                line_break_tolerance_hwp(width)
            } else {
                0
            },
        )
    };
    if cursor.finished {
        return None;
    }

    if tokens.is_empty() {
        cursor.finished = true;
        cursor.emitted_any = true;
        return Some(FilledInterval {
            line: LineBreakResult {
                start_idx: cursor.initial_start_idx,
                end_idx: cursor.initial_start_idx,
                max_font_size: 0.0,
                has_line_break: false,
            },
            termination: FillTermination::ParagraphEnd,
        });
    }

    let eff_w = |first: bool| -> i32 {
        if indent_px > 0.0 {
            if first {
                to_hwp((available_width_px - indent_px).max(1.0))
            } else {
                to_hwp(available_width_px)
            }
        } else if indent_px < 0.0 {
            if first {
                to_hwp(available_width_px)
            } else {
                to_hwp((available_width_px + indent_px).max(1.0))
            }
        } else {
            to_hwp(available_width_px)
        }
    };

    loop {
        if cursor.token_index >= tokens.len() {
            cursor.finished = true;
            let last_end = tokens
                .last()
                .map(|token| match token {
                    BreakToken::Text { end_idx, .. } => *end_idx,
                    BreakToken::DiscretionaryHyphen { idx, .. }
                    | BreakToken::Space { idx, .. }
                    | BreakToken::Tab { idx, .. }
                    | BreakToken::LineBreak { idx } => *idx + 1,
                })
                .unwrap_or(text_chars.len());

            if cursor.line_start_idx <= last_end {
                cursor.emitted_any = true;
                return Some(FilledInterval {
                    line: LineBreakResult {
                        start_idx: cursor.line_start_idx,
                        end_idx: last_end,
                        max_font_size: cursor.line_max_fs,
                        has_line_break: false,
                    },
                    termination: FillTermination::ParagraphEnd,
                });
            }

            if !cursor.emitted_any {
                cursor.emitted_any = true;
                return Some(FilledInterval {
                    line: LineBreakResult {
                        start_idx: cursor.initial_start_idx,
                        end_idx: text_chars.len(),
                        max_font_size: 0.0,
                        has_line_break: false,
                    },
                    termination: FillTermination::ParagraphEnd,
                });
            }
            return None;
        }

        let ti = cursor.token_index;
        match &tokens[ti] {
            BreakToken::DiscretionaryHyphen {
                idx,
                width,
                max_font_size,
            } => {
                let size = cursor.line_max_fs.max(*max_font_size);
                if *idx > cursor.line_start_idx
                    && fits_physical_line(
                        cursor.lw,
                        FitWidthHwp(to_hwp(*width)),
                        cursor.line_space_savings,
                        eff_w(cursor.is_first_line),
                        None,
                    )
                {
                    cursor.last_break_token_idx = Some(ti);
                    cursor.last_break_char_idx = *idx + 1;
                    // 전진은 0이다. 다음 줄로 넘길 때 표시 하이픈 폭을 빼지 않는다.
                    cursor.width_at_last_break = cursor.lw;
                    cursor.space_savings_at_last_break = cursor.line_space_savings;
                    cursor.fs_at_last_break = size;
                }
                cursor.line_max_fs = size;
                cursor.token_index += 1;
            }
            BreakToken::LineBreak { idx } => {
                let result = LineBreakResult {
                    start_idx: cursor.line_start_idx,
                    end_idx: *idx + 1,
                    max_font_size: cursor.line_max_fs,
                    has_line_break: true,
                };
                cursor.line_start_idx = *idx + 1;
                cursor.lw = 0;
                cursor.line_space_savings = 0;
                cursor.line_max_fs = 0.0;
                cursor.is_first_line = false;
                cursor.last_break_token_idx = None;
                cursor.token_index += 1;
                cursor.emitted_any = true;
                return Some(FilledInterval {
                    line: result,
                    termination: FillTermination::ForcedBreak,
                });
            }
            BreakToken::Tab {
                idx,
                max_font_size,
                auto_left_target,
            } => {
                cursor.word_gap_natural_hwp = None;
                let origin_override = cursor.tab_grid_origin_px.map(|origin| {
                    origin
                        + if (indent_px > 0.0 && cursor.is_first_line)
                            || (indent_px < 0.0 && !cursor.is_first_line)
                        {
                            indent_px.abs()
                        } else {
                            0.0
                        }
                });
                let next_tab_hwp = auto_left_target
                    .filter(|target| cursor.is_first_line && to_hwp(*target) > cursor.lw)
                    .map(to_hwp)
                    .unwrap_or_else(|| {
                        tabs.next_hwp(cursor.lw, cursor.is_first_line, origin_override)
                    });
                if *max_font_size > cursor.line_max_fs {
                    cursor.line_max_fs = *max_font_size;
                }

                if next_tab_hwp > eff_w(cursor.is_first_line) && cursor.line_start_idx < *idx {
                    let result = if cursor.last_break_token_idx.is_some() {
                        let result = LineBreakResult {
                            start_idx: cursor.line_start_idx,
                            end_idx: cursor.last_break_char_idx,
                            max_font_size: cursor.fs_at_last_break,
                            has_line_break: false,
                        };
                        cursor.line_start_idx = cursor.last_break_char_idx;
                        cursor.lw -= cursor.width_at_last_break;
                        cursor.line_space_savings -= cursor.space_savings_at_last_break;
                        result
                    } else {
                        let result = LineBreakResult {
                            start_idx: cursor.line_start_idx,
                            end_idx: *idx,
                            max_font_size: cursor.line_max_fs,
                            has_line_break: false,
                        };
                        cursor.line_start_idx = *idx;
                        cursor.lw = 0;
                        cursor.line_space_savings = 0;
                        cursor.line_max_fs = *max_font_size;
                        result
                    };
                    cursor.is_first_line = false;
                    cursor.last_break_token_idx = None;
                    cursor.lw = tabs.next_hwp(
                        cursor.lw,
                        cursor.is_first_line,
                        cursor
                            .tab_grid_origin_px
                            .map(|origin| origin + (-indent_px).max(0.0)),
                    );
                    cursor.token_index += 1;
                    cursor.emitted_any = true;
                    return Some(FilledInterval {
                        line: result,
                        termination: FillTermination::IntervalFull,
                    });
                }

                cursor.last_break_token_idx = Some(ti);
                cursor.last_break_char_idx = *idx;
                cursor.width_at_last_break = cursor.lw;
                cursor.space_savings_at_last_break = cursor.line_space_savings;
                cursor.fs_at_last_break = cursor.line_max_fs;
                cursor.lw = next_tab_hwp;
                cursor.token_index += 1;
            }
            BreakToken::Space {
                idx,
                width,
                condense_base,
                max_font_size,
                inline_width,
            } => {
                let previous_line_max_fs = cursor.line_max_fs;
                if *max_font_size > cursor.line_max_fs {
                    cursor.line_max_fs = *max_font_size;
                }
                let space_hwp = to_hwp(*width);
                // [#7418] 줄 맨 앞 공백은 condense 로 줄지 않는다.
                let leading = space_is_line_leading(text_chars, cursor.line_start_idx, *idx);
                let space_savings = if leading {
                    0
                } else {
                    condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space)
                };
                if let Some(cut) = overflowing_space_cut(
                    cursor.line_start_idx,
                    *idx,
                    cursor.lw + space_hwp,
                    cursor.line_space_savings + space_savings,
                    eff_w(cursor.is_first_line),
                    (*inline_width > 0.0)
                        .then(|| (cursor.lw + to_hwp(*inline_width), cursor.line_space_savings)),
                )
                .filter(|_| {
                    !first_interword_separator(tokens, ti, text_chars, cursor.line_start_idx)
                }) {
                    let absorbed = cut > *idx;
                    // [#7418] 줄 끝에 건 공백이 문단의 마지막 글자면 문단이 여기서 끝난다 —
                    // 종전에는 글자 없는 빈 행을 하나 더 게시했다. 한/글은 넘친 공백 **하나**만
                    // 줄 끝에 걸고 그 뒤 공백은 새 줄로 넘긴다(42자+공백 2 → 1줄, 공백 3 → 2줄;
                    // `trailing_space_synthetic`). 그래서 뒤에 공백이 더 남은 경우는 종전대로 끊는다.
                    if absorbed && ti + 1 == tokens.len() {
                        cursor.finished = true;
                        cursor.emitted_any = true;
                        cursor.token_index = tokens.len();
                        return Some(FilledInterval {
                            line: LineBreakResult {
                                start_idx: cursor.line_start_idx,
                                end_idx: cut,
                                max_font_size: cursor.line_max_fs,
                                has_line_break: false,
                            },
                            termination: FillTermination::ParagraphEnd,
                        });
                    }
                    let line = LineBreakResult {
                        start_idx: cursor.line_start_idx,
                        end_idx: cut,
                        max_font_size: if absorbed {
                            cursor.line_max_fs
                        } else {
                            previous_line_max_fs
                        },
                        has_line_break: false,
                    };
                    cursor.line_start_idx = cut;
                    cursor.lw = if absorbed { 0 } else { space_hwp };
                    // 넘어간 공백은 새 줄의 맨 앞 공백이다.
                    cursor.line_space_savings = 0;
                    cursor.line_max_fs = if absorbed { 0.0 } else { *max_font_size };
                    cursor.is_first_line = false;
                    cursor.last_break_token_idx = None;
                    cursor.word_gap_natural_hwp = None;
                    cursor.token_index += 1;
                    cursor.emitted_any = true;
                    // The terminal separator was consumed by this row. The
                    // cursor is at paragraph end, not at a new empty line.
                    // An authored final LineBreak follows its separate path.
                    let at_end = absorbed && cursor.token_index == tokens.len();
                    cursor.finished = at_end;
                    return Some(FilledInterval {
                        line,
                        termination: if at_end {
                            FillTermination::ParagraphEnd
                        } else {
                            FillTermination::IntervalFull
                        },
                    });
                }
                cursor.last_break_token_idx = Some(ti);
                cursor.last_break_char_idx = *idx;
                cursor.width_at_last_break = cursor.lw;
                cursor.space_savings_at_last_break = cursor.line_space_savings;
                cursor.fs_at_last_break = cursor.line_max_fs;
                if cursor.word_gap_natural_hwp.is_none() && !leading {
                    cursor.word_gap_natural_hwp = Some(cursor.lw);
                }
                cursor.lw += space_hwp;
                cursor.line_space_savings += space_savings;
                cursor.token_index += 1;
            }
            BreakToken::Text {
                start_idx,
                end_idx,
                base_width,
                max_font_size,
                base_char_widths,
                ..
            } => {
                // [#7418] 바로 앞이 이 줄의 공백이었으면 이 토큰이 새 낱말을 시작한다.
                let new_word_natural = cursor
                    .word_gap_natural_hwp
                    .take()
                    .filter(|_| *start_idx > cursor.line_start_idx);
                if let Some(next_char_idx) = cursor.fallback_char_idx {
                    debug_assert!(*start_idx <= next_char_idx && next_char_idx <= *end_idx);
                    let mut ci = next_char_idx;
                    while ci < *end_idx {
                        let rel_idx = ci - *start_idx;
                        let char_w = base_char_widths
                            .get(rel_idx)
                            // 한 글자 토큰의 폭은 이미 같은 글리프·속성으로 측정됐다.
                            // 빈 세부 배열을 반각 추정으로 바꾸면 앞선 fit 거절을
                            // 뒤집어 넓은 기호나 보충 평면 문자를 넘치는 줄에 남긴다.
                            .copied()
                            .or_else(|| (*end_idx == *start_idx + 1).then_some(*base_width))
                            .map(to_hwp)
                            .unwrap_or_else(|| {
                                let ch = text_chars[ci];
                                let char_w_px = if is_cjk_char(ch) {
                                    cursor.line_max_fs.max(12.0)
                                } else {
                                    cursor.line_max_fs.max(12.0) * 0.5
                                };
                                to_hwp(char_w_px)
                            });
                        let current_width = eff_w(cursor.is_first_line);
                        let candidate_base = cursor.lw + char_w;
                        let candidate_width = if let Some(session) = kerning.as_deref_mut() {
                            candidate_base
                                + to_hwp(
                                    session
                                        .boundary_pair_adjustment(cursor.line_start_idx, ci + 1)?,
                                )
                        } else {
                            candidate_base
                        };
                        if candidate_width > current_width && ci > cursor.line_start_idx {
                            let result = LineBreakResult {
                                start_idx: cursor.line_start_idx,
                                end_idx: ci,
                                max_font_size: cursor.line_max_fs,
                                has_line_break: false,
                            };
                            cursor.line_start_idx = ci;
                            cursor.lw = char_w;
                            cursor.is_first_line = false;
                            cursor.fallback_char_idx = Some(ci + 1);
                            cursor.emitted_any = true;
                            return Some(FilledInterval {
                                line: result,
                                termination: FillTermination::IntervalFull,
                            });
                        }
                        cursor.lw += char_w;
                        ci += 1;
                    }
                    cursor.fallback_char_idx = None;
                    cursor.token_index += 1;
                    continue;
                }

                if break_before_text_token(
                    text_chars,
                    *start_idx,
                    cursor.line_start_idx,
                    korean_break_unit,
                ) {
                    cursor.last_break_token_idx = Some(ti - 1);
                    cursor.last_break_char_idx = *start_idx;
                    cursor.width_at_last_break = cursor.lw;
                    cursor.space_savings_at_last_break = cursor.line_space_savings;
                    cursor.fs_at_last_break = cursor.line_max_fs;
                }
                if *max_font_size > cursor.line_max_fs {
                    cursor.line_max_fs = *max_font_size;
                }

                let w_hwp = to_hwp(*base_width);
                let effective_width = eff_w(cursor.is_first_line);
                // 전진폭은 유지하며 일반 자동 줄 경계 비교에서만 후보의 끝 자간을 뺀다.
                // 작성된 줄바꿈 또는 문단 끝의 압축 자간은 전진폭으로 판정한다.
                // 음수 자간을 되돌리면 이미 상자 안에 담긴 마지막 글자만 다음 줄로
                // 밀리고 작성된 줄바꿈 앞에 빈약한 추가 줄이 생긴다. 실제 전진폭
                // 초과와 일반 자동 줄바꿈의 마지막 자간 판정은 그대로 검사한다.
                // 문단 끝 공백은 마지막 가시 글자의 압축 자간 계약을 바꾸지 않는다.
                // 공백의 실제 이월·보존은 Space 분기가 결정한다. 개체가 차지한 공백과
                // 탭은 건너뛰지 않아 뒤의 실제 배치 소유를 잃지 않는다.
                let at_written_line_end = tokens[ti + 1..]
                    .iter()
                    .find(|token| {
                        !matches!(token, BreakToken::Space { inline_width, .. } if *inline_width == 0.0)
                    })
                    .is_none_or(|token| matches!(token, BreakToken::LineBreak { .. }));
                let w_hwp_fit = if at_written_line_end
                    && fit_test_letter_spacing_trim_hwp(letter_spacing_px, *end_idx) < 0
                    && cursor.lw + w_hwp
                        <= effective_width + line_break_tolerance_hwp(effective_width)
                {
                    FitWidthHwp(w_hwp)
                } else {
                    FitWidthHwp::trimmed(w_hwp, letter_spacing_px, *end_idx)
                };
                let pair_adjustment_hwp = if let Some(session) = kerning.as_deref_mut() {
                    to_hwp(session.boundary_pair_adjustment(cursor.line_start_idx, *end_idx)?)
                } else {
                    0
                };
                let token_fits = fits_physical_line(
                    cursor.lw,
                    w_hwp_fit.with_pair_adjustment(pair_adjustment_hwp),
                    cursor.line_space_savings,
                    effective_width,
                    new_word_natural,
                );

                // 단일 문자 CJK/한글 토큰의 줄바꿈 가능 지점 처리
                // 이 글자를 포함한 후 break point 갱신 (end_idx 사용)
                // → 초과 시 이 글자까지 L0에 포함하고 다음 토큰부터 다음 줄
                //
                // **One predicate governs.** This used to ask its own question —
                // the condensed width against the box, without
                // `condense_pull_allowed` — so a glyph the fit test refused could
                // still be registered as a legal line end, and the emitted row
                // runs to the registered point, which put the refused glyph on
                // the line anyway. Measured on `76076_regulatory_analysis` p81
                // (`직접비용 근거설명`, box 36572 HWPUNIT): the fit test refuses
                // at pen 35566 + 1400 = 36966 > 36572, while the recorder
                // admitted the same glyph on 36966 − 980 = 35708 ≤ 36587. Sharing
                // `text_token_fits_line_hwp` makes all six rows of that cell
                // character-identical to the HWP 2024 PDF.
                let tail_all_line_start_forbidden = text_chars[*start_idx + 1..*end_idx]
                    .iter()
                    .all(|c| is_line_start_forbidden(*c));
                if tail_all_line_start_forbidden && *start_idx > cursor.line_start_idx && token_fits
                {
                    // 글자 모드의 후행 금칙 흡수분도 같은 "줄 끝 자리"로 본다.
                    //
                    // 한컴은 줄 끝 금칙 문자를 상자 밖에 매달지 않고 **그 줄 안에** 넣는다
                    // (실측: 정렬줄 중 금칙으로 끝나는 21줄 전부가 상자 안, 줄머리 금칙 0건).
                    // 종전 `== 1` 가드는 흡수가 만든 2글자 묶음(`력·`)을 폭 판정에 통과하고도
                    // 줄 끝 후보에서 배제해, 줄이 묶음 **앞** 한 글자로 되감겼다 — 원본이
                    // `…상호 협력·` 로 끝내는 자리에서 우리는 `…상호 협` 으로 끝나 두 글자를 잃었다.
                    // 1글자 토큰은 아래 슬라이스가 비어 `all()` 이 참이라 종전 동작 그대로다.
                    let c = text_chars[*start_idx];
                    let allow_break = can_break_after_text_token(c, korean_break_unit);
                    if allow_break {
                        cursor.last_break_token_idx = Some(ti);
                        cursor.last_break_char_idx = *end_idx; // 이 글자 다음 (이 글자 포함)
                        cursor.width_at_last_break = cursor.lw + w_hwp; // 이 글자 폭 포함
                        cursor.space_savings_at_last_break = cursor.line_space_savings;
                        cursor.fs_at_last_break = cursor.line_max_fs;
                    }
                }
                if !token_fits {
                    if *start_idx > cursor.line_start_idx {
                        if let Some(break_token_idx) = cursor.last_break_token_idx {
                            let result = LineBreakResult {
                                start_idx: cursor.line_start_idx,
                                end_idx: cursor.last_break_char_idx,
                                max_font_size: cursor.fs_at_last_break,
                                has_line_break: false,
                            };
                            let mut next_start = cursor.last_break_char_idx;
                            while next_start < text_chars.len() && text_chars[next_start] == ' ' {
                                next_start += 1;
                            }
                            cursor.line_start_idx = next_start;
                            cursor.lw = recalc_width_hwp(tokens, ti, next_start);
                            cursor.line_space_savings = recalc_space_savings_hwp(
                                tokens,
                                ti,
                                next_start,
                                condense_min_space,
                            );
                            cursor.line_max_fs = *max_font_size;
                            cursor.is_first_line = false;
                            cursor.last_break_token_idx = None;

                            // 현재 단일 CJK/한글 토큰 자체가 break point였던 기존 경로는
                            // 이미 위 결과에 포함됐으므로 동작을 바꾸지 않는다.
                            if break_token_idx == ti {
                                cursor.lw += w_hwp;
                                cursor.token_index += 1;
                                cursor.emitted_any = true;
                                return Some(FilledInterval {
                                    line: result,
                                    termination: FillTermination::IntervalFull,
                                });
                            }

                            // [#3822] 이전 break 뒤로 옮긴 현재 토큰이 새 줄에도
                            // 들어가는지 다시 확인한다. 종전에는 토큰 전체 폭을 무조건
                            // 더하고 continue하여, 긴 영문·숫자 토큰의 글자 단위 fallback을
                            // 건너뛰었다.
                            // [#5678] 주 판정과 같은 피연산자(`w_hwp_fit`)를 쓴다. 종전에는
                            // 이 자리만 `w_hwp` 를 넘겨, 같은 토큰이 한 반복 안에서 두 방식으로
                            // 측정됐다 — 자간이 0 이 아닌 문단에서만 갈리므로 어떤 테스트도
                            // 이 차이를 잡지 못했다. 펜은 여기서도 전체 폭을 그대로 전진한다.
                            if fits_physical_line(
                                cursor.lw,
                                w_hwp_fit.with_pair_adjustment(
                                    if let Some(session) = kerning.as_deref_mut() {
                                        to_hwp(session.boundary_pair_adjustment(
                                            cursor.line_start_idx,
                                            *end_idx,
                                        )?)
                                    } else {
                                        0
                                    },
                                ),
                                cursor.line_space_savings,
                                eff_w(false),
                                new_word_natural_before_hwp(tokens, ti, cursor.line_start_idx),
                            ) {
                                cursor.lw += w_hwp;
                                cursor.token_index += 1;
                                cursor.emitted_any = true;
                                return Some(FilledInterval {
                                    line: result,
                                    termination: FillTermination::IntervalFull,
                                });
                            }

                            cursor.line_space_savings = 0;
                            cursor.last_break_token_idx = None;
                            cursor.fallback_char_idx = Some(*start_idx);
                            cursor.emitted_any = true;
                            return Some(FilledInterval {
                                line: result,
                                termination: FillTermination::IntervalFull,
                            });
                        }
                    }

                    // 토큰에 저장된 개별 글자 폭을 HWPUNIT로 변환
                    cursor.line_space_savings = 0;
                    cursor.last_break_token_idx = None;
                    cursor.fallback_char_idx = Some(*start_idx);
                    continue;
                }

                cursor.lw += w_hwp;
                cursor.token_index += 1;
            }
        }
    }
}

/// Frozen scalar implementation used only to prove cursor equivalence.
#[cfg(test)]
fn fill_lines_before_cursor(
    tokens: &[BreakToken],
    text_chars: &[char],
    available_width_px: f64,
    indent_px: f64,
    default_tab_width: f64,
    korean_break_unit: u8,
    condense_min_space: u8,
    initial_start_idx: usize,
    initial_is_first_line: bool,
) -> Vec<LineBreakResult> {
    if tokens.is_empty() {
        return vec![LineBreakResult {
            start_idx: initial_start_idx,
            end_idx: initial_start_idx,
            max_font_size: 0.0,
            has_line_break: false,
        }];
    }

    let tab_w_hwp = to_hwp(if default_tab_width > 0.0 {
        default_tab_width
    } else {
        48.0
    });
    let tab_w_px = if default_tab_width > 0.0 {
        default_tab_width
    } else {
        48.0
    };
    let mut results = Vec::new();
    let mut line_start_idx = initial_start_idx;
    let mut lw = 0i32; // HWPUNIT 정수 누적
    let mut line_space_savings = 0i32;
    let mut line_max_fs = 0.0f64;
    let mut is_first_line = initial_is_first_line;

    let mut last_break_token_idx: Option<usize> = None;
    let mut last_break_char_idx: usize = 0;
    let mut width_at_last_break = 0i32;
    let mut space_savings_at_last_break = 0i32;
    let mut fs_at_last_break = 0.0f64;

    let eff_w = |first: bool| -> i32 {
        if indent_px > 0.0 {
            if first {
                to_hwp((available_width_px - indent_px).max(1.0))
            } else {
                to_hwp(available_width_px)
            }
        } else if indent_px < 0.0 {
            if first {
                to_hwp(available_width_px)
            } else {
                to_hwp((available_width_px + indent_px).max(1.0))
            }
        } else {
            to_hwp(available_width_px)
        }
    };

    for (ti, token) in tokens.iter().enumerate() {
        match token {
            BreakToken::DiscretionaryHyphen {
                idx,
                width,
                max_font_size,
            } => {
                line_max_fs = line_max_fs.max(*max_font_size);
                if *idx > line_start_idx
                    && lw + to_hwp(*width) - line_space_savings <= eff_w(is_first_line)
                {
                    last_break_token_idx = Some(ti);
                    last_break_char_idx = *idx + 1;
                    width_at_last_break = lw;
                    space_savings_at_last_break = line_space_savings;
                    fs_at_last_break = line_max_fs;
                }
            }
            BreakToken::LineBreak { idx } => {
                results.push(LineBreakResult {
                    start_idx: line_start_idx,
                    end_idx: *idx + 1,
                    max_font_size: line_max_fs,
                    has_line_break: true,
                });
                line_start_idx = *idx + 1;
                lw = 0;
                line_space_savings = 0;
                line_max_fs = 0.0;
                is_first_line = false;
                last_break_token_idx = None;
            }
            BreakToken::Tab {
                idx, max_font_size, ..
            } => {
                // 탭 계산은 px로 수행 후 HWPUNIT 변환 (정밀도 유지)
                let lw_px = lw as f64 / 75.0;
                let next_tab_px = ((lw_px / tab_w_px).floor() + 1.0) * tab_w_px;
                let next_tab_hwp = to_hwp(next_tab_px);
                if *max_font_size > line_max_fs {
                    line_max_fs = *max_font_size;
                }

                if next_tab_hwp > eff_w(is_first_line) && line_start_idx < *idx {
                    if let Some(_) = last_break_token_idx {
                        results.push(LineBreakResult {
                            start_idx: line_start_idx,
                            end_idx: last_break_char_idx,
                            max_font_size: fs_at_last_break,
                            has_line_break: false,
                        });
                        line_start_idx = last_break_char_idx;
                        lw = lw - width_at_last_break;
                        line_space_savings -= space_savings_at_last_break;
                    } else {
                        results.push(LineBreakResult {
                            start_idx: line_start_idx,
                            end_idx: *idx,
                            max_font_size: line_max_fs,
                            has_line_break: false,
                        });
                        line_start_idx = *idx;
                        lw = 0;
                        line_space_savings = 0;
                        line_max_fs = *max_font_size;
                    }
                    is_first_line = false;
                    last_break_token_idx = None;
                    let lw_px2 = lw as f64 / 75.0;
                    let next_tab2 = ((lw_px2 / tab_w_px).floor() + 1.0) * tab_w_px;
                    lw = to_hwp(next_tab2);
                } else {
                    last_break_token_idx = Some(ti);
                    last_break_char_idx = *idx;
                    width_at_last_break = lw;
                    space_savings_at_last_break = line_space_savings;
                    fs_at_last_break = line_max_fs;
                    lw = next_tab_hwp;
                }
            }
            BreakToken::Space {
                idx,
                width,
                condense_base,
                max_font_size,
                ..
            } => {
                if *max_font_size > line_max_fs {
                    line_max_fs = *max_font_size;
                }
                last_break_token_idx = Some(ti);
                last_break_char_idx = *idx;
                width_at_last_break = lw;
                space_savings_at_last_break = line_space_savings;
                fs_at_last_break = line_max_fs;
                let space_hwp = to_hwp(*width);
                lw += space_hwp;
                if !space_is_line_leading(text_chars, line_start_idx, *idx) {
                    line_space_savings +=
                        condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space);
                }
            }
            BreakToken::Text {
                start_idx,
                end_idx,
                width,
                max_font_size,
                ref char_widths,
                ..
            } => {
                if break_before_text_token(
                    text_chars,
                    *start_idx,
                    line_start_idx,
                    korean_break_unit,
                ) {
                    last_break_token_idx = Some(ti - 1);
                    last_break_char_idx = *start_idx;
                    width_at_last_break = lw;
                    space_savings_at_last_break = line_space_savings;
                    fs_at_last_break = line_max_fs;
                }
                if *max_font_size > line_max_fs {
                    line_max_fs = *max_font_size;
                }

                let w_hwp = to_hwp(*width);

                // 단일 문자 CJK/한글 토큰의 줄바꿈 가능 지점 처리
                // 이 글자를 포함한 후 break point 갱신 (end_idx 사용)
                // → 초과 시 이 글자까지 L0에 포함하고 다음 토큰부터 다음 줄
                let effective_width = eff_w(is_first_line);
                let new_word_natural = new_word_natural_before_hwp(tokens, ti, line_start_idx);
                let token_fits = text_token_fits_line_hwp(
                    lw,
                    FitWidthHwp(w_hwp),
                    line_space_savings,
                    effective_width,
                    new_word_natural,
                );
                // Same single predicate as the live fill — see the note there.
                let tail_all_line_start_forbidden = text_chars[*start_idx + 1..*end_idx]
                    .iter()
                    .all(|c| is_line_start_forbidden(*c));
                // 위 `fill_one_interval` 과 같은 계약(흡수 묶음도 줄 끝 후보).
                if tail_all_line_start_forbidden && *start_idx > line_start_idx && token_fits {
                    let c = text_chars[*start_idx];
                    let allow_break = can_break_after_text_token(c, korean_break_unit);
                    if allow_break {
                        last_break_token_idx = Some(ti);
                        last_break_char_idx = *end_idx; // 이 글자 다음 (이 글자 포함)
                        width_at_last_break = lw + w_hwp; // 이 글자 폭 포함
                        space_savings_at_last_break = line_space_savings;
                        fs_at_last_break = line_max_fs;
                    }
                }
                if !text_token_fits_line_hwp(
                    lw,
                    FitWidthHwp(w_hwp),
                    line_space_savings,
                    effective_width,
                    new_word_natural,
                ) {
                    if *start_idx > line_start_idx {
                        if let Some(break_token_idx) = last_break_token_idx {
                            results.push(LineBreakResult {
                                start_idx: line_start_idx,
                                end_idx: last_break_char_idx,
                                max_font_size: fs_at_last_break,
                                has_line_break: false,
                            });
                            let mut next_start = last_break_char_idx;
                            while next_start < text_chars.len() && text_chars[next_start] == ' ' {
                                next_start += 1;
                            }
                            line_start_idx = next_start;
                            lw = recalc_width_hwp(tokens, ti, next_start);
                            line_space_savings = recalc_space_savings_hwp(
                                tokens,
                                ti,
                                next_start,
                                condense_min_space,
                            );
                            line_max_fs = *max_font_size;
                            is_first_line = false;
                            last_break_token_idx = None;

                            // 현재 단일 CJK/한글 토큰 자체가 break point였던 기존 경로는
                            // 이미 위 결과에 포함됐으므로 동작을 바꾸지 않는다.
                            if break_token_idx == ti {
                                lw += w_hwp;
                                continue;
                            }

                            // [#3822] 이전 break 뒤로 옮긴 현재 토큰이 새 줄에도
                            // 들어가는지 다시 확인한다. 종전에는 토큰 전체 폭을 무조건
                            // 더하고 continue하여, 긴 영문·숫자 토큰의 글자 단위 fallback을
                            // 건너뛰었다.
                            if text_token_fits_line_hwp(
                                lw,
                                FitWidthHwp(w_hwp),
                                line_space_savings,
                                eff_w(false),
                                new_word_natural_before_hwp(tokens, ti, line_start_idx),
                            ) {
                                lw += w_hwp;
                                continue;
                            }
                        }
                    }
                    // 토큰에 저장된 개별 글자 폭을 HWPUNIT로 변환
                    let cw_hwp: Vec<i32> = char_widths.iter().map(|w| to_hwp(*w)).collect();
                    let (results_part, remaining_w, remaining_fs) = char_level_break_hwp(
                        text_chars,
                        *start_idx,
                        *end_idx,
                        &mut line_start_idx,
                        lw,
                        line_max_fs,
                        eff_w(is_first_line),
                        eff_w(false),
                        is_first_line,
                        &cw_hwp,
                    );
                    for r in results_part {
                        results.push(r);
                        is_first_line = false;
                    }
                    lw = remaining_w;
                    line_space_savings = 0;
                    line_max_fs = remaining_fs;
                    last_break_token_idx = None;
                    continue;
                } else {
                    lw += w_hwp;
                }
            }
        }
    }

    let last_end = tokens
        .last()
        .map(|t| match t {
            BreakToken::Text { end_idx, .. } => *end_idx,
            BreakToken::DiscretionaryHyphen { idx, .. }
            | BreakToken::Space { idx, .. }
            | BreakToken::Tab { idx, .. }
            | BreakToken::LineBreak { idx } => *idx + 1,
        })
        .unwrap_or(text_chars.len());

    if line_start_idx <= last_end {
        results.push(LineBreakResult {
            start_idx: line_start_idx,
            end_idx: last_end,
            max_font_size: line_max_fs,
            has_line_break: false,
        });
    }

    if results.is_empty() {
        results.push(LineBreakResult {
            start_idx: initial_start_idx,
            end_idx: text_chars.len(),
            max_font_size: 0.0,
            has_line_break: false,
        });
    }

    results
}

/// 줄 바꿈 지점 이후 토큰의 누적 폭 재계산 (HWPUNIT)
fn recalc_width_hwp(tokens: &[BreakToken], current_token_idx: usize, new_line_start: usize) -> i32 {
    let mut w = 0i32;
    for t in &tokens[..current_token_idx] {
        match t {
            BreakToken::Text {
                start_idx,
                base_width,
                ..
            } if *start_idx >= new_line_start => {
                w += to_hwp(*base_width);
            }
            BreakToken::Space { idx, width, .. } if *idx >= new_line_start => {
                w += to_hwp(*width);
            }
            _ => {}
        }
    }
    w
}

/// 줄 바꿈 지점 이후 공백 압축 가능 폭 재계산 (HWPUNIT)
fn recalc_space_savings_hwp(
    tokens: &[BreakToken],
    current_token_idx: usize,
    new_line_start: usize,
    condense_min_space: u8,
) -> i32 {
    let mut w = 0i32;
    // [#7418] 줄 맨 앞 공백(첫 글자 토큰 앞)은 줄지 않는다.
    let mut line_has_text = false;
    for t in &tokens[..current_token_idx] {
        match t {
            BreakToken::Space {
                idx, condense_base, ..
            } if *idx >= new_line_start && line_has_text => {
                w += condense_space_savings_hwp(to_hwp(*condense_base), condense_min_space);
            }
            BreakToken::Text { start_idx, .. } if *start_idx >= new_line_start => {
                line_has_text = true;
            }
            _ => {}
        }
    }
    w
}

/// 긴 단어 폴백: 글자 단위 분할 (HWPUNIT)
/// char_widths_hwp: 토큰 내 각 글자의 HWPUNIT 폭 (None이면 휴리스틱)
#[cfg(test)]
fn char_level_break_hwp(
    text_chars: &[char],
    token_start: usize,
    token_end: usize,
    line_start_idx: &mut usize,
    mut lw: i32,
    line_max_fs: f64,
    first_line_w: i32,
    normal_w: i32,
    mut is_first_line: bool,
    char_widths_hwp: &[i32], // 토큰 내 글자별 HWPUNIT 폭
) -> (Vec<LineBreakResult>, i32, f64) {
    let mut results = Vec::new();
    let mut current_w = if is_first_line {
        first_line_w
    } else {
        normal_w
    };

    for ci in token_start..token_end {
        let rel_idx = ci - token_start;
        let char_w = if rel_idx < char_widths_hwp.len() {
            char_widths_hwp[rel_idx]
        } else {
            let ch = text_chars[ci];
            let char_w_px = if is_cjk_char(ch) {
                line_max_fs.max(12.0)
            } else {
                line_max_fs.max(12.0) * 0.5
            };
            to_hwp(char_w_px)
        };

        if lw + char_w > current_w && ci > *line_start_idx {
            results.push(LineBreakResult {
                start_idx: *line_start_idx,
                end_idx: ci,
                max_font_size: line_max_fs,
                has_line_break: false,
            });
            *line_start_idx = ci;
            lw = char_w;
            is_first_line = false;
            current_w = normal_w;
        } else {
            lw += char_w;
        }
    }

    (results, lw, line_max_fs)
}

/// 문단이 참조하는 글자모양 중 가장 큰 글꼴 크기(px). 글자모양이 없으면 None.
///
/// 글자가 없는 문단(글자처럼 취급되는 표·그림만 든 문단)은 줄에 글자 폭이 없어 `max_font_size` 가
/// 0 으로 떨어지고, 그러면 줄간격 기준이 12px 하드코딩으로 내려간다. 한컴은 그 문단의
/// 글자모양 높이를 그대로 줄간격 기준으로 쓴다(실측: 14pt 문단 표 줄 spacing 912 HU, 12px 폴백은 585).
fn paragraph_font_size_px(para: &Paragraph, styles: &ResolvedStyleSet) -> Option<f64> {
    para.char_shapes
        .iter()
        .filter_map(|cs| styles.char_styles.get(cs.char_shape_id as usize))
        .map(|style| style.font_size)
        .filter(|fs| *fs > 0.0)
        .fold(None, |acc: Option<f64>, fs| {
            Some(acc.map_or(fs, |a| a.max(fs)))
        })
}

/// 표시되지 않는 문단 끝 문자도 마지막 줄의 글자모양 높이를 소유한다.
/// 문자 수는 확장 제어를 포함한 원본 UTF-16 축이므로 표시 문자열 길이로 대신하지 않는다.
pub(crate) fn paragraph_end_font_size_px(para: &Paragraph, styles: &ResolvedStyleSet) -> f64 {
    let Some(end_pos) = para.char_count.checked_sub(1) else {
        return 0.0;
    };
    let id = find_active_char_shape(&para.char_shapes, end_pos);
    styles
        .char_styles
        .get(id as usize)
        .map(|style| style.font_size)
        .unwrap_or(0.0)
}

/// 비-글자취급 개체(표·그림·도형)의 기준 문자 위치(텍스트 문자 인덱스)와 그 문자의 글꼴 크기(px).
///
/// 개체가 글자처럼 흐르지 않아도 기준 문자는 문단 텍스트의 한 글자이고, 한컴은 그 글자의
/// 글자모양을 줄 높이에 넣는다. 한컴 저장본에서 첫 줄의 개체 기준 문자 글자모양이 그 줄의
/// 다른 글자보다 클 때 저장 줄 높이는 언제나 기준 문자 쪽 크기다(`samples/`·10k 코퍼스 HWP
/// 표본 스캔 11/11, 반례 0 — 예: 1600/1200 → 1600, 2000/1400 → 2000). 기준 문자가 더 작으면
/// 텍스트 크기가 남는다(71건). 글자처럼 취급하는 개체는 개체 높이로 줄을 만드는 별도 경로가
/// 소유한다.
fn floating_anchor_char_font_sizes(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
) -> Vec<(usize, f64)> {
    match floating_anchor_char_font_sizes_with_storage(para, styles, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn floating_anchor_char_font_sizes_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    storage: &S,
) -> Result<Vec<(usize, f64)>, S::Error> {
    Ok({
        if para.controls.is_empty() || para.char_shapes.is_empty() {
            return Ok(Vec::new());
        }
        let text_positions = para.try_control_text_positions(storage)?;
        let utf16_positions = para.control_utf16_positions_with_storage(storage)?;
        storage.collect(
            para.controls
                .iter()
                .zip(text_positions)
                .zip(utf16_positions)
                .filter(|((ctrl, _), _)| match ctrl {
                    Control::Table(table) => !table.common.treat_as_char,
                    Control::Picture(pic) => !pic.common.treat_as_char,
                    Control::Shape(shape) => !shape.common().treat_as_char,
                    _ => false,
                })
                .filter_map(|((_, text_pos), utf16_pos)| {
                    let id = find_active_char_shape(&para.char_shapes, utf16_pos);
                    styles
                        .char_styles
                        .get(id as usize)
                        .map(|style| style.font_size)
                        .filter(|fs| *fs > 0.0)
                        .map(|fs| (text_pos, fs))
                }),
        )?
    })
}

/// `range` 줄에 놓인 개체 기준 문자의 가장 큰 글꼴 크기(px). 문단 끝 기준 문자는 마지막 줄 소속이다.
fn floating_anchor_font_size_px(
    anchors: &[(usize, f64)],
    range: Range<usize>,
    is_last_line: bool,
    text_len: usize,
) -> f64 {
    anchors
        .iter()
        .filter(|(pos, _)| range.contains(pos) || (is_last_line && *pos == text_len))
        .map(|(_, fs)| *fs)
        .fold(0.0, f64::max)
}

/// [#8167] 글자처럼 취급한 도형이 줄에서 차지하는 상자(HU) — 도형 크기에 바깥 여백을 더한다.
/// 한/글 저장 줄은 이 상자 높이를 줄 높이로 쓴다(samples HWPX 의 바깥 여백 있는 글자처럼
/// 사각형 78줄 전부 `vertsize = 높이 + 위 + 아래 여백`). 배치도 같은 상자로 줄 안 폭과
/// 기준선 자리를 센다(`tac_object_outer_margins_px`).
fn tac_shape_box_hu(shape: &crate::model::shape::ShapeObject) -> (i32, i32) {
    let common = shape.common();
    let margin = &common.margin;
    (
        shape.flow_width_hu() + i32::from(margin.left) + i32::from(margin.right),
        shape.flow_height_hu() + i32::from(margin.top) + i32::from(margin.bottom),
    )
}

fn inline_control_line_height_hwp(para: &Paragraph) -> Option<i32> {
    para.controls
        .iter()
        .filter_map(|ctrl| match ctrl {
            Control::Picture(pic) if pic.common.treat_as_char => {
                Some(super::inline_picture_occupied_size_hu(pic).1)
            }
            Control::Shape(shape) if shape.common().treat_as_char => {
                Some(tac_shape_box_hu(shape).1)
            }
            Control::Table(table) if table.common.treat_as_char => Some(table.common.height as i32),
            Control::Equation(eq) if eq.common.treat_as_char => {
                Some(crate::renderer::equation::flow_height_hwp(eq) as i32)
            }
            Control::Form(form) if form.common.treat_as_char => Some(form.height as i32),
            _ => None,
        })
        .filter(|height| *height > 0)
        .max()
}

fn inline_control_size_hwp(ctrl: &Control) -> Option<(i32, i32)> {
    match inline_control_size_hwp_with_storage(ctrl, &crate::storage::Unbounded) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn inline_control_size_hwp_with_storage<S: crate::storage::Storage>(
    ctrl: &Control,
    storage: &S,
) -> Result<Option<(i32, i32)>, S::Error> {
    Ok({
        let (width, height) = match ctrl {
            Control::Picture(pic) if pic.common.treat_as_char => {
                super::inline_picture_occupied_size_hu(pic)
            }
            Control::Shape(shape) if shape.common().treat_as_char => tac_shape_box_hu(shape),
            Control::Table(table) if table.common.treat_as_char => {
                // [#5785 후속] 선언 폭 우선 — 원시 열 합은 행별 구획이 다른 표에서 과대집계된다.
                let width = table.flow_width_hu_with_storage(storage)? as i32;
                (width, table.common.height as i32)
            }
            Control::Equation(eq) if eq.common.treat_as_char => (
                crate::renderer::equation::inline_box::horizontal_metrics(eq).occupied_width_hwp(),
                crate::renderer::equation::flow_height_hwp(eq) as i32,
            ),
            Control::Form(form) if form.common.treat_as_char => {
                (form.width as i32, form.height as i32)
            }
            _ => return Ok(None),
        };

        if width > 0 && height > 0 {
            Some((width, height))
        } else {
            None
        }
    })
}

/// 줄의 점유 상자는 표 본체와 바깥 여백을 함께 포함한다.
/// 별도 줄의 너비 판정과 같은 줄의 높이 발행이 동일한 메트릭을 소비한다.
fn inline_control_occupied_size_hwp(
    control: &Control,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> Option<(i32, i32)> {
    match inline_control_occupied_size_hwp_with_storage(
        control,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn inline_control_occupied_size_hwp_with_storage<S: crate::storage::Storage>(
    control: &Control,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<Option<(i32, i32)>, S::Error> {
    Ok({
        if let Control::Table(table) = control {
            if let Some(measured) =
                super::measured_reflow_inline_table_with_storage(table, styles, dpi, storage)?
            {
                let Some(width) = i32::try_from(table.flow_width_hu_with_storage(storage)?)
                    .ok()
                    .map(|width| {
                        width
                            .saturating_add(i32::from(table.outer_margin_left))
                            .saturating_add(i32::from(table.outer_margin_right))
                    })
                else {
                    return Ok(None);
                };
                let height = px_to_hwpunit(measured.total_height, dpi)
                    .saturating_add(i32::from(table.outer_margin_top))
                    .saturating_add(i32::from(table.outer_margin_bottom));
                return Ok((width > 0 && height > 0).then_some((width, height)));
            }
        }

        let Some((mut width, mut height)) = inline_control_size_hwp_with_storage(control, storage)?
        else {
            return Ok(None);
        };
        if let Control::Table(table) = control {
            // 줄은 실제로 그리는 표를 담는다. 편집으로 셀 내용이 선언 높이를 넘으면 행이
            // 자라고, 행 합이 선언보다 작으면 한/글은 그 행 높이로 그리고 다음 줄을 잇는다
            // (선언 8160HU·행 합 7536HU 결재문서 표, 한/글 2020 Print). 선언값으로 줄을
            // 발행하면 뒤 내용이 그 차이만큼 내려간다.
            let measured = crate::renderer::height_measurer::HeightMeasurer::new(dpi)
                .with_session_edited(true)
                .measure_table_with_storage(table, 0, 0, styles, storage)?;
            // 위/아래 캡션도 인라인 개체가 소유하는 물리 상자다. 표 본체만
            // 발행하면 캡션 글줄에 다음 개체가 놓이고 저장 줄도 그 높이로 굳는다.
            let measured_hu = (measured.total_height * 7200.0 / dpi).round() as i32;
            if measured_hu > 0 {
                height = measured_hu;
            }
            width = width
                .saturating_add(i32::from(table.outer_margin_left))
                .saturating_add(i32::from(table.outer_margin_right));
            height = height
                .saturating_add(i32::from(table.outer_margin_top))
                .saturating_add(i32::from(table.outer_margin_bottom));
        }
        Some((width, height))
    })
}

fn inline_control_spacing_height_hwp(control: &Control) -> Option<i32> {
    match control {
        Control::Equation(equation)
            if equation.common.treat_as_char && equation.common.affect_line_spacing =>
        {
            Some(crate::renderer::equation::flow_height_hwp(equation) as i32)
        }
        _ => None,
    }
}

/// [#7160] 프레임 채움 전용 — **글자처럼 취급 표**도 인라인 토큰으로 싣는다.
///
/// 일반 경로는 표를 `control 배치 경로`에 두려고 제외하지만(#3211), 저장 줄이 없는 host 는
/// 이 채움이 줄 경계의 유일한 소유자다. 표 폭을 안 실으면 줄에 남은 폭보다 넓은 표가
/// 줄바꿈 없이 앞 글자 뒤에 붙는다(`distribution_doc.hwpx` 3쪽 — 표가 본문 오른쪽 밖으로 나간다).
fn flow_inline_controls_with_tac_tables(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> Vec<FlowInlineControl> {
    match flow_inline_controls_with_tac_tables_with_storage(
        para,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn flow_inline_controls_with_tac_tables_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<Vec<FlowInlineControl>, S::Error> {
    Ok({
        let text_len = para.text.chars().count();
        let mut controls = flow_inline_controls_with_storage(para, styles, storage)?;
        for ((control, char_position), utf16_position) in para
            .controls
            .iter()
            .zip(para.try_control_text_positions(storage)?)
            .zip(para.control_utf16_positions_with_storage(storage)?)
        {
            let Control::Table(table) = control else {
                continue;
            };
            if !table.common.treat_as_char || char_position >= text_len {
                continue;
            }
            let Some((width_hwp, height_hwp)) =
                inline_control_occupied_size_hwp_with_storage(control, styles, dpi, storage)?
            else {
                continue;
            };
            storage.push(
                &mut controls,
                FlowInlineControl {
                    char_position,
                    utf16_position,
                    width_hwp,
                    height_hwp,
                    baseline_distance_hwp: None,
                    spacing_height_hwp: inline_control_spacing_height_hwp(control),
                },
            )?;
        }
        storage.bytes(std::mem::size_of_val(controls.as_slice()))?;
        controls.sort_by_key(|control| control.char_position);
        controls
    })
}

#[path = "inline_control_flow.rs"]
mod inline_control_flow;
use inline_control_flow::{flow_inline_controls, flow_inline_controls_with_storage};

fn flow_inline_baseline_hwp(control: &Control, _height_hwp: i32) -> Option<i32> {
    match control {
        // 현재 브랜치의 공통 수식 메트릭을 일반 흐름과 편집 프레임이 함께 소비한다.
        Control::Equation(equation) => {
            let baseline = crate::renderer::equation::flow_metrics_hwp(equation).2;
            (baseline > 0).then_some(baseline)
        }
        _ => None,
    }
}

/// Controls that claim no inline advance and own no layout box of their own.
///
/// Structural section/column markers qualify because the caller's current
/// Frame already embodies their resolved page/column geometry. A field
/// (`ClickHere` and friends) qualifies for a different reason that reaches the
/// same place: it is a *marker pair* around ordinary paragraph text.
/// `inline_control_size_hwp` returns `None` for it, so `flow_inline_controls`
/// never emits a token for it and the fill measures it as nothing.
///
/// Fields have to be in this set, because the alternative is that a body
/// paragraph carrying one has **no layout owner at all**. That is the state
/// `hwp_doc_fill_fields` leaves behind: `set_field_text_at`
/// (`queries/field_query.rs`) replaces the field's text and shifts the stored
/// `LineSeg` offsets, but never calls `reflow_line_segs`, so a paragraph that
/// went from 9 bytes to 5,109 still carries the one record that described the
/// empty form. Nothing downstream re-wraps it if the frame declines to look.
/// **A property, not a list.** This used to enumerate three variants, and the
/// enumeration was the defect: `Bookmark`, `PageNumberPos`, `PageHide`,
/// `HiddenComment` and HWP3's `Hyperlink` are every bit as width-neutral as a
/// `Field`, and a body paragraph carrying one had no layout owner at all — it
/// fell to `compose_lines`' 45-character heuristic with no stored record, or
/// got no repair with a stale one. HWP5/HWPX hyperlinks escaped only by an
/// accident of parsing: `%hlk` becomes a `Control::Field` through a prefix
/// test. Fields were added to the list for exactly this reason once already;
/// the class was the thing to fix.
///
/// The property is: **contributes no inline width, and owns no layout box.**
///
/// - No inline width is `inline_control_size_hwp` returning `None` — the same
///   oracle `flow_inline_controls` uses, so a control the fill would measure as
///   nothing is a control the frame may ignore. That is one source of truth
///   rather than two lists that must be kept in step.
/// - No layout box of its own is the closed set below. It cannot come from the
///   width oracle, because a *floating* Picture, Shape or Table also returns
///   `None` there — they contribute no inline width precisely because they are
///   laid out elsewhere. A body frame carries no exclusion for them
///   (`models_exclusions()` is false), so it must decline and leave them with
///   their established owner; that is what `layout_picture_band` exists for.
///
/// Enumerating the controls that *have* geometry rather than the ones that do
/// not also fails in the safer direction. A control variant nobody has
/// classified is laid out as ordinary text by the frame, which is at worst the
/// same treatment its text would get anyway — where the previous shape left the
/// whole paragraph unowned.
pub(crate) fn control_is_width_neutral_marker(control: &Control) -> bool {
    inline_control_size_hwp(control).is_none() && !control_owns_a_layout_box(control)
}

/// Controls that resolve their own geometry, inline or floating, and therefore
/// have a layout owner that is not this frame.
///
/// `Header`/`Footer`/`Footnote`/`Endnote` are nested flows with their own
/// frames; the rest carry a `CommonObjAttr` box. `Footnote`/`Endnote` also
/// occupy a flow slot (`Control::is_logical_inline`).
fn control_owns_a_layout_box(control: &Control) -> bool {
    matches!(
        control,
        Control::Table(_)
            | Control::Shape(_)
            | Control::Picture(_)
            | Control::Equation(_)
            | Control::Form(_)
            | Control::Header(_)
            | Control::Footer(_)
            | Control::Footnote(_)
            | Control::Endnote(_)
    )
}

/// [#6102] 자리차지(TopAndBottom) 비-TAC 표는 자기 레이아웃 상자를 갖지만
/// **줄 폭**은 소비하지 않는다 — 세로 밴드를 예약할 뿐 본문 프레임의 가로
/// 줄바꿈에는 폭-중립이다. 결재문서본문 계열(구역 첫 문단 + 자리차지 표
/// host)의 저장 `textpos` 가 실폭보다 길게 적혀 있을 때, 프레임이 표 컨트롤
/// 때문에 사양하면 검증(admission)조차 못 해 본문 첫 줄이 우단 밖까지
/// 그려진다(36360328 +75px — 한글 2020 은 재래핑한다). 어울림(Square)은
/// 배제 밴드가 줄 폭을 바꾸므로, 그림/도형 float 는 별도 계보
/// (`layout_picture_band`)가 소유하므로 계속 사양한다.
fn control_is_line_width_neutral_float_table(control: &Control) -> bool {
    matches!(control, Control::Table(t)
        if !t.common.treat_as_char
            && matches!(t.common.text_wrap, crate::model::shape::TextWrap::TopAndBottom))
}

/// 자리차지(TopAndBottom)·글 뒤·글 앞 비-TAC 그림·도형은 자기 상자를 부동 개체 소유자가
/// 배치하고, 같은 문단 본문 줄의 **폭**은 바꾸지 않는다 — 표의 같은 계약
/// (`control_is_line_width_neutral_float_table`)과 같은 축이다. 어울림(Square)·
/// Tight·Through 는 배제 밴드가 줄 폭을 바꾸므로 들지 않는다(`layout_picture_band` 소유).
/// 캡션은 개체 상자의 일부라 줄과 무관하다.
pub(crate) fn control_is_line_width_neutral_float_object(control: &Control) -> bool {
    use crate::model::shape::TextWrap;
    let common = match control {
        Control::Picture(picture) => &picture.common,
        Control::Shape(shape) => shape.common(),
        _ => return false,
    };
    !common.treat_as_char
        && matches!(
            common.text_wrap,
            TextWrap::TopAndBottom | TextWrap::BehindText | TextWrap::InFrontOfText
        )
}

/// 글자처럼 취급하지 않은 어울림(Square) 그림·도형 — 그림 밴드 프레임이 받는 부동 개체.
pub(crate) fn control_is_square_float_object(control: &Control) -> bool {
    let common = match control {
        Control::Picture(picture) => &picture.common,
        Control::Shape(shape) => shape.common(),
        _ => return false,
    };
    !common.treat_as_char && matches!(common.text_wrap, crate::model::shape::TextWrap::Square)
}

/// [#8399] 본문 줄에 배제 밴드를 거는 개체 — 비-TAC 그림(어울림이 아니면 밴드 계산이 사양한다)과
/// 어울림·Tight·Through 비-TAC 도형. [`layout_picture_band`] 가 이 밴드의 유일한 소유자다.
pub(crate) fn control_owns_body_band(control: &Control) -> bool {
    match control {
        Control::Picture(picture) => !picture.common.treat_as_char,
        Control::Shape(shape) => {
            crate::renderer::float_placement::shape_wraps_beside_text(shape.common())
        }
        _ => false,
    }
}

/// [#8399] 줄 조각 `(column_start, segment_width)` 가 문단 상자보다 깎였는가(HWPUNIT).
///
/// 밴드 소유자가 낸 줄([`Paragraph::layout_float_band`])도 개체와 겹치지 않는 줄은 문단 상자
/// 그대로다 — 그 줄은 평범한 줄 배치를 따르고, 깎인 줄만 저장 줄 상자로 그린다. 허용 오차는
/// 격자 스냅(4HU)보다 넉넉하고 글자 한 칸보다 작다.
pub(crate) fn row_is_carved_from_box(
    column_start: i32,
    segment_width: i32,
    paragraph_box: &Range<i32>,
) -> bool {
    const BOX_TOLERANCE_HU: u32 = 200;
    segment_width > 0
        && (column_start.abs_diff(paragraph_box.start) > BOX_TOLERANCE_HU
            || column_start
                .saturating_add(segment_width)
                .abs_diff(paragraph_box.end)
                > BOX_TOLERANCE_HU)
}

/// 어울림(Square)·Tight·Through 비-TAC 도형. 이 배제 밴드는 [`layout_picture_band`] 가 편집과
/// XML 로드에서 줄로 발행한다(#8399). 줄이 하나도 없는 host(밴드가 본문 줄과 겹치지 않아 발행할 것이
/// 없던 경우)는 렌더 프레임이 전폭으로 채운다 — 이 도형 때문에 사양하면 같은 문단의 글자처럼 개체가
/// 줄 높이를 잃어 편집 직후·HWP 저장본과 HWPX 저장본의 배치가 갈린다(#8282).
pub(crate) fn control_is_float_shape_beside_text(control: &Control) -> bool {
    matches!(control, Control::Shape(shape)
        if crate::renderer::float_placement::shape_wraps_beside_text(shape.common()))
}

/// 글자 전진폭을 다시 측정한 수식의 첫 소유 줄만 저장 캐시 경계로 삼는다.
/// 상자 높이가 이미 현재 값이어도 같은 재측정 증거를 소비하며 저장 폭은 보존한다.
/// 앞쪽의 정상 줄과 각주 앵커까지 함께 재조판하면 무관한 문단 배치가 바뀐다.
pub(super) fn remeasured_equation_start_row(para: &Paragraph) -> Option<usize> {
    let positions = super::find_render_inline_control_positions(para);
    para.controls
        .iter()
        .enumerate()
        .filter_map(|(index, control)| {
            let Control::Equation(equation) = control else {
                return None;
            };
            if !equation.common.treat_as_char
                || (crate::renderer::equation::flow_width_hwp(equation) == equation.common.width
                    && !crate::renderer::equation::current_simple_math_advance_was_remeasured(
                        equation,
                    ))
            {
                return None;
            }
            let position = *positions.get(index)?;
            let chars = para.text.chars().count();
            para.line_segs
                .iter()
                .enumerate()
                .rev()
                .find_map(|(row, _)| {
                    let (start, _) = super::utf16_range_to_text_range(
                        &para.char_offsets,
                        para.line_seg_text_start(row),
                        u32::MAX,
                        chars,
                    );
                    (start <= position).then_some(row)
                })
        })
        .min()
}

/// 글앞/글뒤 비-TAC 표는 종이층에 놓여 줄 폭도 세로 밴드도 소비하지 않는다.
/// 저장 줄 없는 문단에서 이 표만 가진 host 의 줄바꿈은 글자 폭이 정한다.
/// 같은 종이층의 글앞/글뒤 그림·도형도 줄 폭에 중립이라 함께 둘 수 있다.
pub(super) fn supports_overlay_table_frame_controls(para: &Paragraph) -> bool {
    let is_overlay = |common: &crate::model::shape::CommonObjAttr| {
        !common.treat_as_char
            && matches!(
                common.text_wrap,
                crate::model::shape::TextWrap::InFrontOfText
                    | crate::model::shape::TextWrap::BehindText
            )
    };
    let mut overlay_tables = 0usize;
    for control in &para.controls {
        match control {
            Control::Table(table) if is_overlay(&table.common) => {
                overlay_tables += 1;
            }
            Control::Picture(pic) if is_overlay(&pic.common) => {}
            Control::Shape(shape) if is_overlay(shape.common()) => {}
            other if control_is_width_neutral_marker(other) => {}
            _ => return false,
        }
    }
    overlay_tables > 0
}

/// 표 없이 글앞/글뒤 그림·도형만 가진 저장 줄 없는 host.
///
/// 같은 종이층 개체라 줄 폭에 중립이다. 개체 없는 저장 줄 없는 문단과 같이 글자만
/// 실제 폭 프레임으로 조판한다.
pub(super) fn supports_overlay_shape_frame_controls(para: &Paragraph) -> bool {
    let is_overlay = |common: &crate::model::shape::CommonObjAttr| {
        !common.treat_as_char
            && matches!(
                common.text_wrap,
                crate::model::shape::TextWrap::InFrontOfText
                    | crate::model::shape::TextWrap::BehindText
            )
    };
    if !para.line_segs.is_empty() {
        return false;
    }
    let mut overlay_objects = 0usize;
    for control in &para.controls {
        match control {
            Control::Picture(pic) if is_overlay(&pic.common) => overlay_objects += 1,
            Control::Shape(shape) if is_overlay(shape.common()) => overlay_objects += 1,
            other if control_is_width_neutral_marker(other) => {}
            _ => return false,
        }
    }
    overlay_objects > 0
}

pub(super) fn supports_cached_body_frame_controls(para: &Paragraph) -> bool {
    let remeasured = remeasured_equation_start_row(para).is_some();
    para.controls.iter().all(|control| {
        control_is_width_neutral_marker(control)
            || control_is_line_width_neutral_float_table(control)
            // Without stored rows, certified non-flow cell paint must not veto
            // the text frame. With stored rows its existing layout owner keeps
            // that geometry; this is not permission to rebuild a saved ladder.
            || (crate::renderer::para_has_no_stored_line_segs(para)
                && crate::model::border_paint::is_cell_frame_paint(control))
            || (remeasured && matches!(control, Control::Equation(eq) if eq.common.treat_as_char))
            || (remeasured && matches!(control, Control::Footnote(_)))
    })
}

/// The picture-band frame intentionally admits only its floating host, the
/// already-supported treat-as-character Equation flow, and width-neutral
/// markers. Other controls have their own layout owners and must leave this
/// transaction untouched.
/// [#7160] NO_LS 문단의 **글자처럼 취급 표** host 도 프레임이 받는다.
///
/// 배포용(ViewText) 문서는 저장 `LINE_SEG` 가 없어 45자 합성 줄바꿈이 유일한 소유자가 된다.
/// 표를 사양하면 그 합성 줄이 그대로 남아 `(단위 : 천원)` 한 줄이 세 줄로 쪼개지고, 표가
/// 자기 줄을 못 얻어 앞 글자 뒤에 붙는다(`distribution_doc.hwpx` 3쪽). TAC 표는 fill 이
/// 인라인 토큰으로 폭을 계상하므로 그림과 같은 축이다.
pub(super) fn supports_tac_table_band_frame_controls(para: &Paragraph) -> bool {
    let mut tac_tables = 0usize;
    for control in &para.controls {
        match control {
            Control::Table(table) if table.common.treat_as_char => tac_tables += 1,
            Control::Picture(picture) if picture.common.treat_as_char => {}
            Control::Equation(equation) if equation.common.treat_as_char => {}
            // 머리말/꼬리말은 본문 바깥의 별도 프레임이다. 본문 줄의 너비·높이를
            // 소비하지 않으므로 NO_LS 인라인 표의 줄 구성에서 사양할 이유가 없다.
            Control::Header(_) | Control::Footer(_) => {}
            other if control_is_width_neutral_marker(other) => {}
            _ => return false,
        }
    }
    tac_tables == 1 || (tac_tables > 1 && crate::renderer::para_has_no_stored_line_segs(para))
}

pub(crate) fn supports_picture_band_frame_controls(para: &Paragraph) -> bool {
    let mut non_tac_pictures = 0usize;
    for control in &para.controls {
        match control {
            Control::Picture(picture) if !picture.common.treat_as_char => {
                non_tac_pictures += 1;
            }
            // 어울림 도형도 어울림 그림과 같은 부동 개체 하나다 — 자기 상자는 도형 소유자가
            // 배치하고, 이 프레임은 같은 문단의 글자·글자처럼 개체 줄을 짠다. 사양하면 저장 줄
            // 없는 문단이 합성 줄로 남아 글자처럼 그림의 줄 높이를 잃는다(#8282).
            square if control_is_square_float_object(square) => {
                non_tac_pictures += 1;
            }
            // 글자처럼 취급 그림은 fill 이 인라인 토큰으로 폭을 계상한다
            // (`inline_control_size_hwp`) — 사양하면 NO_LS 문단에서 인라인
            // 아이콘 폭이 통째로 빠져 후속 텍스트가 아이콘 위에 겹친다.
            Control::Picture(picture) if picture.common.treat_as_char => {}
            Control::Equation(equation) if equation.common.treat_as_char => {}
            other if control_is_width_neutral_marker(other) => {}
            _ => return false,
        }
    }
    non_tac_pictures <= 1
}

/// 저장 줄이 없는 글자처럼 그림 호스트 — 프레임 fill 이 유일한 소유자다.
fn no_ls_inline_picture_host_fill(para: &Paragraph) -> bool {
    para.line_segs.is_empty() && supports_inline_picture_frame_controls(para)
}

// Captioned pictures and floating controls have separate layout owners. A
// caption-free inline picture instead consumes a real slot in this text flow,
// including at the paragraph end and alongside another inline picture.
// 줄 폭을 바꾸지 않는 부동 그림·도형은 자기 상자만 따로 배치되므로 이 흐름의 슬롯을
// 소비하지 않는다 — 투영(`inline_frame_input::project`)도 인라인 크기가 없는 개체를 건너뛴다.
// 사양하면 같은 문단의 글자처럼 그림이 줄 높이를 잃는다(#8271).
fn supports_inline_picture_frame_controls(para: &Paragraph) -> bool {
    para.controls
        .iter()
        .any(|control| matches!(control, Control::Picture(picture) if picture.common.treat_as_char))
        && para.controls.iter().all(|control| match control {
            Control::Picture(picture) if picture.common.treat_as_char => picture.caption.is_none(),
            float if control_is_line_width_neutral_float_object(float) => true,
            shape if control_is_float_shape_beside_text(shape) => true,
            Control::Picture(_) => false,
            other => control_is_width_neutral_marker(other),
        })
}

// 양식만 있는 빈 문단도 그림과 같은 원시 인라인 슬롯을 프레임에 넘긴다.
// 떠 있는 양식이나 다른 개체의 배치 소유권은 기존 경로에 둔다.
pub(super) fn supports_inline_form_frame_controls(para: &Paragraph) -> bool {
    para.controls
        .iter()
        .any(|control| matches!(control, Control::Form(form) if form.common.treat_as_char))
        && para.controls.iter().all(|control| match control {
            Control::Form(form) => form.common.treat_as_char,
            other => control_is_width_neutral_marker(other),
        })
}

/// 본문 뒤 남은 폭에 놓이지 않는 inline control은 별도 physical line을 가진다.
///
/// 종전 cell reflow는 text token만 줄바꿈한 뒤 첫 LineSeg를 표 높이만큼 키웠다.
/// 그 결과 분할로 폭이 좁아진 셀에서 `text + inline object`가 한 줄로 합쳐졌다.
/// 한컴은 control 위치부터 object 전용 LineSeg를 만들어 다음 physical line으로 보낸다
/// (#4138: 1×2 split 뒤 nested table/picture host). control 자체가 셀 폭을 넘거나,
/// control 앞의 실제 text 폭과 합쳐 현재 줄의 폭을 넘는 경우만 대상으로 한다.
/// 같은 줄에 들어가는 작은 object와 복수 control 문단의 기존 reflow는 건드리지 않는다.
///
/// 돌려주는 값은 (개체 글자 위치, 개체 원시 위치, 개체 줄 높이, 뒤 글자를 다음 줄로 넘기는지)다.
fn inline_control_requires_own_line(
    para: &Paragraph,
    occupied_controls: &[(usize, u32, i32, i32)],
    text_chars: &[char],
    line_breaks: &[LineBreakResult],
    available_width_px: f64,
    indent_px: f64,
    reflow_is_first_line: bool,
    styles: &ResolvedStyleSet,
    space_metric: SpaceMetric,
) -> Option<(usize, u32, i32, bool)> {
    let text_len = para.text.chars().count();
    let mut candidates = occupied_controls
        .iter()
        .copied()
        .filter(|(position, _, _, _)| *position > 0 && *position <= text_len);
    let (position, utf16_start, control_width, height) = candidates.next()?;
    // 여러 inline control은 일반 placement가 순서를 보존해야 하므로 이 좁은
    // single-control 계약 밖이다.
    if candidates.next().is_some() {
        return None;
    }

    // 같은 text offset에서 새 줄이 시작되면 control은 그 줄의 선두에 놓인다.
    // 그렇지 않으면 control 직전 text가 실제로 속한 줄을 선택한다. 마지막 글자
    // 뒤의 control은 마지막 text line에 속한다.
    let (line_idx, line) = line_breaks
        .iter()
        .enumerate()
        .find(|(_, line)| line.start_idx == position)
        .or_else(|| {
            line_breaks
                .iter()
                .enumerate()
                .rfind(|(_, line)| line.start_idx < position && position <= line.end_idx)
        })?;
    let is_first_line = reflow_is_first_line && line_idx == 0;
    let available_hwp = if indent_px > 0.0 && is_first_line {
        to_hwp((available_width_px - indent_px).max(1.0))
    } else if indent_px < 0.0 && !is_first_line {
        to_hwp((available_width_px + indent_px).max(1.0))
    } else {
        to_hwp(available_width_px)
    };
    let scope = ParagraphMetricScope::new(text_chars, styles)
        .with_space_metric(space_metric)
        .with_literal_figure_spaces(&para.literal_figure_spaces);
    let width_of = |range: Range<usize>| {
        let text: String = text_chars[range.clone()].iter().collect();
        to_hwp(measure_token_width(
            &scope,
            &text,
            range.start,
            &para.char_offsets,
            &para.char_shapes,
            styles,
            0,
            &[],
        ))
    };
    let prefix_width = width_of(line.start_idx..position);

    let tolerance_hwp = line_break_tolerance_hwp(available_hwp);
    if control_width <= available_hwp + tolerance_hwp
        && prefix_width + control_width <= available_hwp + tolerance_hwp
    {
        return None;
    }
    // 개체 줄은 첫 줄이 아니다. 개체 옆에 들어가지 않는 뒤 글자는 개체 줄 다음 줄에서
    // 시작한다. 줄 끝 공백은 줄을 넘기지 않는다.
    let row_hwp = if indent_px < 0.0 {
        to_hwp((available_width_px + indent_px).max(1.0))
    } else {
        to_hwp(available_width_px)
    };
    let suffix_end = (position..line.end_idx)
        .rfind(|&i| !text_chars[i].is_whitespace())
        .map_or(position, |i| i + 1);
    let suffix_row = suffix_end > position
        && control_width + width_of(position..suffix_end)
            > row_hwp + line_break_tolerance_hwp(row_hwp);
    Some((position, utf16_start, height, suffix_row))
}

fn char_index_to_utf16_offset(para: &Paragraph, char_index: usize) -> u32 {
    if let Some(offset) = para.char_offsets.get(char_index) {
        return *offset;
    }

    // char_offsets에는 visible text 앞의 control stream gap도 반영된다. 따라서
    // 끝의 빈 physical line(예: trailing Shift+Enter)을 단순 text 길이로 매핑하면
    // SectionDef/ColumnDef가 앞선 문단에서 21이어야 할 start가 5로 되돌아간다.
    // 마지막 visible char의 실제 stream offset을 기준으로 종단을 계산한다.
    // 탭은 한 scalar지만 PARA_TEXT에서 8유닛이다. 한 유닛만 더하면 문단 끝 뒤 줄 조각이
    // 탭 제어 문자 가운데서 시작하고, 한/글은 그 저장본을 손상된 문서로 보고 열지 않는다.
    para.char_offsets
        .last()
        .zip(para.text.chars().last())
        .map(|(offset, ch)| *offset + Paragraph::char_stream_len(ch))
        .unwrap_or_else(|| {
            // 합성 문단처럼 char_offsets가 비어 있으면 char_index(Unicode scalar
            // index)를 UTF-16 code-unit 위치로 직접 환산한다. 단순 `as u32`는
            // 보충 평면 문자를 1 unit으로 세어 후행 줄의 start를 당긴다.
            para.text
                .chars()
                .take(char_index)
                .map(Paragraph::char_stream_len)
                .sum()
        })
}

/// A physical line begins before the inline objects owned by its first scalar.
/// Visible character offsets point after their control gaps; publishing that
/// offset would leave a leading equation/picture owned by the preceding line.
fn line_start_utf16_offset(
    para: &Paragraph,
    char_index: usize,
    inline_controls: &[FlowInlineControl],
) -> u32 {
    // 개체 투영 입력(`inline_frame_input`)은 개체를 원시 위치의 U+FFFC 한 scalar로 싣는다.
    // 그 자리표가 문단의 마지막 scalar면 문단 끝은 개체 제어 문자 8유닛 뒤다.
    let end = (char_index > 0 && char_index == para.char_offsets.len())
        .then(|| para.char_offsets[char_index - 1])
        .filter(|&raw| {
            inline_controls.iter().any(|control| {
                control.char_position == char_index - 1 && control.utf16_position == raw
            })
        })
        .map_or_else(
            || char_index_to_utf16_offset(para, char_index),
            |raw| raw + CTRL_CHAR_CODE_UNITS,
        );
    inline_controls
        .iter()
        .filter(|control| control.char_position == char_index)
        .map(|control| control.utf16_position)
        .fold(end, u32::min)
}

/// `baseline_distance` from a row's height — the one expression, so the frame
/// and the edit path cannot publish different baselines for the same paragraph.
///
/// They did: `frame_metrics_for_line` rounded while `make_line_seg` truncated,
/// and `make_line_seg`'s output is written to the file. Any half-point font
/// size split them — 10.5pt gives `1050 * 0.85 = 892.5`, so one published 893
/// and the other 892.
pub(super) fn baseline_distance_hwp(line_height_hwp: i32) -> i32 {
    (line_height_hwp as f64 * 0.85).round() as i32
}

/// 재조판한 줄의 `baseline_distance` 를 문단 세로 정렬점(HWP 5.0 표 44)으로 발행한다.
///
/// 한컴은 세로 정렬이 글꼴 기준(0)이 아니면 기준선 거리 자리에 그 정렬점을 저장한다 —
/// 줄의 글자 높이에서 위 0, 가운데 절반(내림), 아래 전체. 공개 표본 1,205개의 저장 줄
/// 55,800여 개가 개체 유무와 관계없이 이 규칙을 따른다(예외는 표본 한 개의 빈 문단뿐).
/// 줄 구성은 글꼴 기준선으로 계산하므로 저장 직전 이 자리에서 바꾼다. 렌더러는 저장 줄과
/// 같은 값을 받으므로, 편집한 문단과 편집하지 않은 문단이 같은 경로로 그려진다.
pub(super) fn publish_vertical_alignment_baselines(
    para: &mut Paragraph,
    styles: &ResolvedStyleSet,
) {
    let alignment = styles
        .para_styles
        .get(para.para_shape_id as usize)
        .map_or(0, |style| style.vertical_alignment);
    if alignment == 0 {
        return;
    }
    // 기준선만 바꾼다. 줄 경계와 함께 발행된 공백 규칙·출처 표시는 그대로 둔다.
    for row in &mut para.line_segs {
        row.baseline_distance = match alignment {
            1 => 0,
            2 => row.text_height / 2,
            _ => row.text_height,
        };
    }
}

/// 셀 폭 변경 후 확정한 원시 줄 소유에서 수식의 물리 메트릭을 발행한다.
/// 공백 scalar의 줄 끝 제외와 원시 수식 슬롯의 줄 소유는 다르다. paint와 같은
/// 슬롯 질의를 사용하며, affectLineSpacing은 개체 높이를 퍼센트 간격의 기준으로 삼는다.
fn apply_reflowed_equation_row_metrics(
    para: &Paragraph,
    segments: &mut [LineSeg],
    styles: &ResolvedStyleSet,
    spacing_type: LineSpacingType,
    spacing_value: f64,
    dpi: f64,
) {
    let mut equations = vec![Vec::new(); segments.len()];
    for (ci, control) in para.controls.iter().enumerate() {
        let Control::Equation(equation) = control else {
            continue;
        };
        if !equation.common.treat_as_char {
            continue;
        }
        if let Some(line) = super::control_slot_line_index_with_starts(
            para,
            ci,
            segments.iter().map(|seg| seg.text_start),
        ) {
            equations[line].push(equation.as_ref());
        }
    }
    let chars: Vec<_> = para.text.chars().collect();
    for line in 0..segments.len() {
        if equations[line].is_empty() {
            continue;
        }
        let start = segments[line].text_start;
        let end = segments
            .get(line + 1)
            .map_or(u32::MAX, |seg| seg.text_start);
        let mut text_baseline = 0;
        let mut spacing_height = 0;
        for (index, ch) in chars.iter().enumerate() {
            let offset = char_index_to_utf16_offset(para, index);
            if offset < start || offset >= end || *ch == '\u{fffc}' {
                continue;
            }
            let shape = find_active_char_shape(&para.char_shapes, offset);
            let height = font_size_to_line_height(token_line_font_size(styles, shape), dpi);
            spacing_height = spacing_height.max(height);
            if ch.is_whitespace() || ch.is_control() {
                continue;
            }
            text_baseline = text_baseline.max(baseline_distance_hwp(height));
        }
        if spacing_height == 0 {
            spacing_height =
                font_size_to_line_height(paragraph_font_size_px(para, styles).unwrap_or(12.0), dpi);
        }
        let mut equation_baseline = 0;
        let mut affects_spacing = false;
        let seg = &mut segments[line];
        for equation in &equations[line] {
            let (_, height, baseline) = crate::renderer::equation::flow_metrics_hwp(equation);
            let height = height as i32;
            seg.line_height = seg.line_height.max(height);
            seg.text_height = seg.text_height.max(height);
            equation_baseline = equation_baseline.max(baseline);
            if equation.common.affect_line_spacing {
                affects_spacing = true;
                // 같은 줄의 큰 수식이 간격 계산에서 제외돼 있으면 작은 참여
                // 수식 때문에 그 높이까지 간격 기준으로 승격하지 않는다.
                // 줄의 점유 높이·기준선과 간격에 참여하는 높이는 다른 값이다.
                spacing_height = spacing_height.max(height);
            }
        }
        if equation_baseline > 0 {
            seg.baseline_distance = text_baseline.max(equation_baseline);
        }
        if affects_spacing {
            seg.line_spacing =
                compute_line_spacing_hwp(spacing_type, spacing_value, spacing_height, dpi);
        }
    }
}

pub(super) fn apply_inline_control_line_height(seg: &mut LineSeg, height_hwp: i32) {
    if height_hwp > seg.line_height {
        seg.line_height = height_hwp;
        seg.text_height = height_hwp;
        seg.baseline_distance = baseline_distance_hwp(height_hwp);
    }
}

fn apply_inline_control_frame_height(metrics: &mut FrameRowMetrics, height_hwp: i32) {
    if height_hwp > metrics.line_height {
        metrics.line_height = height_hwp;
        metrics.text_height = height_hwp;
        metrics.baseline_distance = baseline_distance_hwp(height_hwp);
    }
}

pub(crate) fn frame_metrics_for_line(
    max_font_size: f64,
    fallback_font_size: f64,
    line_spacing_type: LineSpacingType,
    line_spacing_value: f64,
    dpi: f64,
) -> FrameRowMetrics {
    let font_size = if max_font_size > 0.0 {
        max_font_size
    } else {
        fallback_font_size
    };
    let line_height = font_size_to_line_height(font_size, dpi).max(1);
    FrameRowMetrics {
        vertical_pos: 0,
        line_height,
        text_height: line_height,
        baseline_distance: baseline_distance_hwp(line_height),
        line_spacing: compute_line_spacing_hwp(
            line_spacing_type,
            line_spacing_value,
            line_height,
            dpi,
        ),
    }
}

/// [#7490] 새로 조판한 줄에 한글처럼 `TAG_INDENTATION`(bit 20)을 단다.
///
/// 들여쓰기는 첫 줄에, 내어쓰기는 둘째 줄부터 적용된다(한글 저장본의 줄별 기록과
/// 같다). 렌더러는 이 비트가 꺼진 저장 줄에 들여쓰기를 얹지 않으므로(#6190), 비운 채
/// 발행하면 편집한 문단의 들여쓰기·내어쓰기가 그려지지 않는다.
///
/// 기준은 문단 모양의 `indent` 다. 렌더러가 비트를 보고 얹는 값이 이것이므로, 조판용
/// 지역 `indent_px` 를 넘겨받지 않는다. 한글 기록(`stored`, 조판 전 저장 줄)이 이 규칙과
/// 다르면 기록을 따른다.
/// - 들여쓰기가 있는데 저장 줄의 비트가 모두 꺼져 있으면, 한글이 이 문단에 들여쓰기를
///   적용하지 않은 것이다(#6190 표본). 새 줄도 끈다. 내어쓰기는 둘째 줄이 있어야 이
///   기록을 읽는다. 들여쓰기를 바꾼 문단은 [`restamp_indentation`] 이 기록을 먼저 고친다.
/// - 들여쓰기가 0 인 문단 머리(글머리표·번호·개요) 문단은 한글이 둘째 줄부터 비트를
///   켠다. 저장 줄의 둘째 줄 이후 비트를 잇는다.
fn mark_indented_lines(
    lines: &mut [LineSeg],
    first_line_index: usize,
    para_style: Option<&ResolvedParaStyle>,
    stored: &[LineSeg],
    line_width_hwp: i32,
) {
    stamp_indentation(
        lines,
        first_line_index,
        reflow_indentation_pattern(para_style, stored, line_width_hwp),
    );
    stamp_paragraph_head(lines, first_line_index, para_style);
}

/// 새로 조판한 줄에 한글처럼 `TAG_PARAGRAPH_HEAD`(bit 21)를 단다.
///
/// 한/글(12.30 Mac)은 문단 머리(글머리표·그림 글머리표·번호·개요)가 있는 문단의 첫 줄에만
/// 이 비트를 켜고, 둘째 줄 이후와 머리를 끈 문단에서는 끈다(HWP `PARA_LINE_SEG`·HWPX
/// `flags` 모두). 비트가 꺼진 글머리표 문단은 한/글이 글머리표를 그리지 않는다.
fn stamp_paragraph_head(
    lines: &mut [LineSeg],
    first_line_index: usize,
    para_style: Option<&ResolvedParaStyle>,
) {
    let head = paragraph_has_head(para_style);
    for (line_index, line) in (first_line_index..).zip(lines.iter_mut()) {
        if head && line_index == 0 {
            line.tag |= LineSeg::TAG_PARAGRAPH_HEAD;
        } else {
            line.tag &= !LineSeg::TAG_PARAGRAPH_HEAD;
        }
    }
}

fn paragraph_has_head(para_style: Option<&ResolvedParaStyle>) -> bool {
    para_style.is_some_and(|style| style.head_type != HeadType::None)
}

/// 재조판이 발행할 줄별 들여쓰기 기록. 개체의 줄 폭 판정도 같은 기록을 소비한다.
///
/// [#7816] 줄 폭(`line_width_hwp`, 문단 여백을 뺀 상자)에서 들여쓰기를 빼고 남는 폭이
/// 모자라면([`indent_leaves_line_room_hwp`]) 들여쓰기를 버린다. 한/글 저장 줄의 기록이
/// 있으면 그 기록이 같은 판정의 결과이므로 먼저 따른다.
fn reflow_indentation_pattern(
    para_style: Option<&ResolvedParaStyle>,
    stored: &[LineSeg],
    line_width_hwp: i32,
) -> (bool, bool) {
    let indent = para_style.map_or(0.0, |style| style.indent);
    let indented = |line: &LineSeg| line.tag & LineSeg::TAG_INDENTATION != 0;
    let hancom_record = !stored.is_empty()
        && stored
            .iter()
            .all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
    if hancom_record
        && (indent > 0.0 || (indent < 0.0 && stored.len() > 1))
        && !stored.iter().any(indented)
    {
        (false, false)
    } else if indent == 0.0 && para_style.is_some_and(|style| style.head_type != HeadType::None) {
        (false, hancom_record && stored.iter().skip(1).any(indented))
    } else if !indent_leaves_line_room_hwp(to_hwp(indent), line_width_hwp) {
        (false, false)
    } else {
        (indent > 0.0, indent < 0.0)
    }
}

/// [#7490] 문단 모양이 바뀌어 들여쓰기가 달라졌으면 저장 줄의 bit 20 을 새 들여쓰기로
/// 다시 단다.
///
/// 저장 줄의 비트는 그 줄을 조판할 때의 들여쓰기 기록이다. 옛 기록(모두 꺼짐)을 두면
/// 다음 재조판이 이를 "들여쓰기를 적용하지 않은 문단"으로 읽어 새 들여쓰기를 버린다.
pub(crate) fn restamp_indentation(lines: &mut [LineSeg], old_indent: i32, new_indent: i32) {
    if old_indent != new_indent {
        stamp_indentation(lines, 0, (new_indent > 0, new_indent < 0));
    }
}

/// 첫 줄과 둘째 줄 이후에 각각 bit 20 을 켜거나 끈다.
fn stamp_indentation(lines: &mut [LineSeg], first_line_index: usize, (first, rest): (bool, bool)) {
    for (line_index, line) in (first_line_index..).zip(lines.iter_mut()) {
        if (line_index == 0 && first) || (line_index > 0 && rest) {
            line.tag |= LineSeg::TAG_INDENTATION;
        } else {
            line.tag &= !LineSeg::TAG_INDENTATION;
        }
    }
}

fn apply_resolved_field_tokens(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    inline: &[FlowInlineControl],
    tokens: &mut Vec<BreakToken>,
) {
    match apply_resolved_field_tokens_with_storage(
        para,
        styles,
        inline,
        tokens,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

fn apply_resolved_field_tokens_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    inline: &[FlowInlineControl],
    tokens: &mut Vec<BreakToken>,
    storage: &S,
) -> Result<(), S::Error> {
    {
        if para.layout_field_values.is_empty() {
            return Ok(());
        }
        let mut resolved = Vec::new();
        for token in tokens.drain(..) {
            let field = match &token {
                BreakToken::Space { idx, .. } => Some(*idx),
                BreakToken::Text {
                    start_idx, end_idx, ..
                } if *end_idx == *start_idx + 1 => Some(*start_idx),
                _ => None,
            }
            .and_then(|position| {
                super::resolved_fields::token_width(para, position, styles).map(|(width, size)| {
                    (
                        position,
                        width + inline_width_px_at(inline, position, styles),
                        size,
                    )
                })
            });
            if let Some((position, width, size)) = field {
                storage.push(
                    &mut resolved,
                    BreakToken::Text {
                        start_idx: position,
                        end_idx: position + 1,
                        base_width: width,
                        width,
                        max_font_size: size,
                        base_char_widths: storage.collect([width])?,
                        char_widths: storage.collect([width])?,
                    },
                )?;
            } else {
                storage.push(&mut resolved, token)?;
            }
        }
        *tokens = resolved;
    };
    Ok(())
}

/// Lay out the small scalar/Picture-band paragraph subset through a
/// caller-owned physical frame.
///
/// Every interval returned by one carve belongs to the same physical row. The
/// cursor continues from left to right and the frame does not advance until
/// that complete row has been committed.
pub(crate) fn layout_paragraph_in_frame(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> Option<Vec<LineSeg>> {
    layout_paragraph_in_frame_impl(para, frame, styles, dpi, true, 0, FramePurpose::Body)
}

pub(crate) fn layout_paragraph_in_frame_with_storage<S: Storage>(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<Option<Vec<LineSeg>>, S::Error> {
    try_layout_paragraph_in_frame_impl(
        para,
        frame,
        styles,
        dpi,
        true,
        0,
        FramePurpose::Body,
        storage,
    )
}

/// 일반 본문 수용 조건을 유지하고 원본 선두 번호와 그림 앵커만 조회한다.
pub(crate) fn layout_picture_anchor_in_frame(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> Option<Vec<LineSeg>> {
    layout_paragraph_in_frame_impl(
        para,
        frame,
        styles,
        dpi,
        true,
        0,
        FramePurpose::PictureAnchor,
    )
}

fn layout_paragraph_in_frame_impl(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    allow_kerning: bool,
    start_char: usize,
    purpose: FramePurpose,
) -> Option<Vec<LineSeg>> {
    match try_layout_paragraph_in_frame_impl(
        para,
        frame,
        styles,
        dpi,
        allow_kerning,
        start_char,
        purpose,
        &Unbounded,
    ) {
        Ok(lines) => lines,
        Err(never) => match never {},
    }
}

fn try_layout_paragraph_in_frame_impl<S: Storage>(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    allow_kerning: bool,
    start_char: usize,
    purpose: FramePurpose,
    storage: &S,
) -> Result<Option<Vec<LineSeg>>, S::Error> {
    // [#6102] 폭-중립 자리차지 표 host 도 fill 대상 — 표는 줄 폭을 소비하지
    // 않으므로(자기 레이아웃 소유자가 따로 배치) 텍스트만 재래핑하면 된다.
    // [#7160] 저장 줄이 없는 글자처럼 취급 표 host 는 이 채움이 유일한 소유자다.
    let supported = match purpose {
        FramePurpose::Body => {
            supports_picture_band_frame_controls(para)
                || supports_cached_body_frame_controls(para)
                || supports_inline_form_frame_controls(para)
                || (para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para))
                || (para.line_segs.is_empty() && supports_overlay_table_frame_controls(para))
                || supports_overlay_shape_frame_controls(para)
                || no_ls_inline_picture_host_fill(para)
        }
        FramePurpose::PictureAnchor => picture_anchor_projection::admits(para),
    };
    if !supported {
        return Ok(None);
    }

    let projected = if (para.line_segs.is_empty()
        && (supports_tac_table_band_frame_controls(para)
            || supports_inline_form_frame_controls(para)))
        || no_ls_inline_picture_host_fill(para)
    {
        inline_frame_input::project_with_storage(para, styles, dpi, storage)?
    } else {
        None
    };
    let para = projected.as_ref().map_or(para, |(input, _)| input);
    let mut text_chars = storage.collect(para.text.chars())?;
    // 필드는 공백을 건너뛰는 줄 경계가 아닌 원자 토큰이다. 토큰화 전용
    // 필드 마커로 투영하며 원문과 모델 축은 바꾸지 않는다.
    for (position, _) in &para.layout_field_values {
        if let Some(character) = text_chars.get_mut(*position) {
            *character = '\u{0015}';
        }
    }

    // 문단 끝의 빈 run도 마지막 물리 줄의 글자 상자를 소유한다. 가시 글자와
    // 별개인 종단 CharShapeRef를 보존해야 줄 높이·간격·베이스라인을 프레임의
    // 공통 결과로 게시할 수 있다. 앞선 줄이나 개체 마커의 글꼴에는 적용하지 않는다.
    let paragraph_end_font_size = para
        .char_shapes
        .iter()
        .find(|shape| shape.start_pos == para.char_count.saturating_sub(1))
        .and_then(|shape| styles.char_styles.get(shape.char_shape_id as usize))
        .map_or(0.0, |style| style.font_size);
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    // [#7418·#7436] 목록 마커(글머리표·번호)는 줄 앞을 차지한다. 배치가 마커 기하만큼
    // 줄 시작을 옮기고 가용폭을 줄이므로 채움도 각 행의 첫 구간에서 같은 상자로 줄을 나눈다
    // (`ListMarkerGeometry::breaker_box`). 게시하는 행 기하(구간)는 마커를 포함한 그대로다 —
    // 한/글 저장 행도 마커 자리부터 시작한다.
    let frame_width_hwp = frame.horizontal.end.saturating_sub(frame.horizontal.start);
    let indentation_pattern =
        reflow_indentation_pattern(para_style, &para.line_segs, frame_width_hwp);
    let indent_px = if indentation_pattern == (false, false) {
        0.0
    } else {
        para_style.map_or(0.0, |style| style.indent)
    };
    // 저장 기록이 끄는 것은 문단 들여쓰기뿐이다. 마커의 첫/후속 줄 차이는 유지한다.
    let (marker_hang_px, indent_px) = list_marker_breaker_box(para, styles, indent_px);
    let marker_font_size = list_marker_metrics::include_marker(para, styles, true, 0.0);
    let mut tab_fill = TabFill::for_paragraph(
        para_style,
        indent_px,
        crate::renderer::hwpunit_to_px(
            frame.horizontal.end.saturating_sub(frame.horizontal.start),
            dpi,
        ),
    );
    tab_fill.default_width_px = styles.default_tab_width(tab_fill.default_width_px);
    let english_break_unit = para_style
        .map(|style| style.english_break_unit)
        .unwrap_or(0);
    let korean_break_unit = para_style.map(|style| style.korean_break_unit).unwrap_or(0);
    let condense_min_space = para_style
        .map(|style| style.condense_min_space)
        .unwrap_or(0);
    let line_spacing_type = para_style
        .map(|style| style.line_spacing_type)
        .unwrap_or(LineSpacingType::Percent);
    let line_spacing_value = para_style.map(|style| style.line_spacing).unwrap_or(160.0);
    // Keep Equation width and height ownership with the current scalar
    // `FlowInlineControl` path. A non-TAC Picture deliberately contributes no
    // inline token: it is represented by the caller's exclusion instead.
    let mut inline_controls = if let Some((_, controls)) = projected.as_ref() {
        storage.copy_slice(controls)?
    } else if para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para) {
        // [#7160] 저장 줄이 없는 TAC 표 host 는 표 폭까지 줄 경계 판정에 넣는다.
        flow_inline_controls_with_tac_tables_with_storage(para, styles, dpi, storage)?
    } else {
        flow_inline_controls_with_storage(para, styles, storage)?
    };
    if purpose == FramePurpose::PictureAnchor {
        let prefix = crate::renderer::layout::leading_endnote_prefix_geometry(para, styles, 0);
        if prefix.advance > 0.0 && prefix.height > 0.0 {
            if std::env::var_os("RHWP_PICTURE_ANCHOR_DEBUG").is_some() {
                eprintln!(
                    "PICTURE_ANCHOR_PREFIX advance={:.4} height={:.4} baseline={:.4}",
                    prefix.advance, prefix.height, prefix.baseline,
                );
            }
            // 표시가 전진시키는 첫 본문의 원점을 동일한 inline 채움에 연결한다.
            // 원본 scalar/control offset을 바꾸거나 번호를 문서에 삽입하지 않는다.
            storage.reserve(&mut inline_controls, 1)?;
            inline_controls.push(FlowInlineControl {
                char_position: 0,
                utf16_position: 0,
                width_hwp: px_to_hwpunit(prefix.advance, dpi),
                height_hwp: px_to_hwpunit(prefix.height, dpi),
                baseline_distance_hwp: Some(px_to_hwpunit(prefix.baseline, dpi)),
                spacing_height_hwp: None,
            });
            storage.bytes(std::mem::size_of_val(inline_controls.as_slice()))?;
            inline_controls.sort_by_key(|control| control.char_position);
        }
    }
    // [#3128] 프레임이 들여쓰기 추적을 잃던 자리. 종전에는 여기서 `false` 를 박아
    // 두어, 저장 `LINE_SEG` 가 없는 들여쓴 셀 문단도 글꼴 고유 공백 폭으로 쟀다.
    // 실측: `76076_regulatory_analysis.hwp` 에서 이 술어를 만족하는 문단이 74 개고,
    // 그 전부가 이 경로로 들어온다.
    let space_metric =
        if super::missing_lineseg_indented_cell_has_uniform_metrics_with_tracking(para, styles) {
            SpaceMetric::HalfCell
        } else if frame.kopub_justified_space
            && para_style.is_some_and(|style| style.alignment == Alignment::Justify)
        {
            SpaceMetric::KoPubJustified
        } else {
            SpaceMetric::Stored
        };
    let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
        &text_chars,
        &para.char_offsets,
        &para.char_shapes,
        styles,
        english_break_unit,
        korean_break_unit,
        space_metric,
        &inline_controls,
        para.control_mask & (1 << 0x18) != 0,
        &para.literal_figure_spaces,
        storage,
    )?;
    apply_resolved_field_tokens_with_storage(para, styles, &inline_controls, &mut tokens, storage)?;
    apply_auto_left_tab_targets(&mut tokens, para_style);
    let prepared_kerning = allow_kerning
        .then(|| {
            prepare_paragraph_kerning(para, &text_chars, styles, space_metric, &inline_controls)
        })
        .flatten()
        .and_then(|prepared| {
            apply_paragraph_kerning_to_tokens(&mut tokens, &prepared.measurement).map(|_| prepared)
        });
    let mut kerning_transaction = prepared_kerning
        .as_ref()
        .map(|prepared| prepared.context.layout_session());
    let mut kerning_break_session = prepared_kerning.as_ref().and_then(|prepared| {
        crate::renderer::kerning::KerningParagraphBreakSession::new(
            &para.text,
            &prepared.scalar_styles,
            &prepared.hard_boundaries,
            &prepared.measurement,
            kerning_transaction.as_mut()?,
        )
        .ok()
    });
    // 양쪽정렬의 마지막 가시 줄은 공백 분배 대상이 아니다. 들여쓴 셀의
    // 중간 줄은 기존 반각 채움을 유지하고, 남은 문단 전체가 현재 구간에
    // 들어가는 마지막 줄만 글꼴 공백으로 확정한다. 첫 줄에만 한정하면
    // 다줄 문단 끝의 불필요한 줄바꿈과 다음 페이지 밀림이 남는다.
    // 커닝은 별도 paragraph transaction이 폭을 소유하므로 그 경로는 유지한다.
    let terminal_tokens = (space_metric == SpaceMetric::HalfCell
        && prepared_kerning.is_none()
        && para_style
            .is_some_and(|style| style.alignment == crate::model::style::Alignment::Justify))
    .then(|| {
        let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
            &text_chars,
            &para.char_offsets,
            &para.char_shapes,
            styles,
            english_break_unit,
            korean_break_unit,
            SpaceMetric::Stored,
            &inline_controls,
            para.control_mask & (1 << 0x18) != 0,
            &para.literal_figure_spaces,
            storage,
        )?;
        apply_resolved_field_tokens_with_storage(
            para,
            styles,
            &inline_controls,
            &mut tokens,
            storage,
        )?;
        apply_auto_left_tab_targets(&mut tokens, para_style);
        Ok(tokens)
    })
    .transpose()?;
    let mut letter_spacing_px =
        try_resolved_paragraph_letter_spacing(para, &text_chars, styles, space_metric, storage)?;
    if projected.is_some() {
        for control in &inline_controls {
            letter_spacing_px[control.char_position] = 0.0;
        }
    }
    let fallback_font_size = if para.text.is_empty() {
        para.char_shapes
            .first()
            .and_then(|char_shape| styles.char_styles.get(char_shape.char_shape_id as usize))
            .map(|style| style.font_size)
            .unwrap_or(12.0)
    } else {
        12.0
    };
    // This matches the scalar path's terminal-control behavior: controls not
    // admitted to `FlowInlineControl` because they sit after the last visible
    // character enlarge the first line box without inventing a second width
    // accounting path.
    let terminal_inline_metrics = inline_controls
        .is_empty()
        .then(|| {
            let height_hwp = inline_control_line_height_hwp(para)?;
            let baseline_distance_hwp = para
                .controls
                .iter()
                .filter_map(|control| match control {
                    Control::Equation(equation)
                        if equation.common.treat_as_char
                            && crate::renderer::equation::flow_height_hwp(equation) as i32
                                == height_hwp
                            && equation.baseline > 0 =>
                    {
                        Some(crate::renderer::equation::flow_metrics_hwp(equation).2)
                    }
                    _ => None,
                })
                .max();
            Some((height_hwp, baseline_distance_hwp))
        })
        .flatten();
    let terminal_inline_spacing_height = terminal_inline_metrics.and_then(|_| {
        para.controls
            .iter()
            .filter_map(inline_control_spacing_height_hwp)
            .max()
    });
    // Fresh rows inherit only provenance. Page/column-first, empty, indent,
    // paragraph-head, and FIRST/LAST are properties of the newly projected
    // physical row and must not leak from the cached first row.
    let source_tag = para
        .line_segs
        .first()
        .map(|segment| segment.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY)
        .unwrap_or(LineSeg::TAG_IMPLEMENTATION_PROPERTY);
    let first_row = frame.row_count();
    let frame_checkpoint = frame.try_append_checkpoint(storage)?;
    let mut cursor = FillCursor::replay_from_boundary(&tokens, start_char, start_char == 0);
    // 확정된 물리 구간은 원본 격자 폭 자체가 경계다. 추정 여유를 더하면
    // 4 HU 격자로 내린 칸에도 26 HU 초과 글자가 들어가 격자 계약이 무효화된다.
    cursor.allow_metric_tolerance = false;

    let result = (|| {
        while !cursor.finished {
            let row_frame_checkpoint = frame.try_append_checkpoint(storage)?;
            let cursor_checkpoint = cursor.clone();
            let mut candidate_height = frame_metrics_for_line(
                fallback_font_size,
                fallback_font_size,
                line_spacing_type,
                line_spacing_value,
                dpi,
            )
            .line_height;
            const MAX_ROW_HEIGHT_TRIALS: usize = 8;
            let mut attempted_trials = storage.vec(MAX_ROW_HEIGHT_TRIALS)?;

            loop {
                frame.try_restore_append_checkpoint(&row_frame_checkpoint, storage)?;
                cursor = cursor_checkpoint.clone();
                let intervals =
                    storage.collect(frame.try_carve(candidate_height, storage)?.iter().cloned())?;
                // Asked before filling so a degenerate carve costs no
                // tokenization, but it is the same question
                // `commit_carved_row` asks — one rule, not two.
                if !frame.carved_row_is_usable() {
                    return Ok(None);
                }
                let trial = (
                    frame.top,
                    candidate_height,
                    storage.collect(intervals.iter().cloned())?,
                );
                if attempted_trials.contains(&trial)
                    || attempted_trials.len() == MAX_ROW_HEIGHT_TRIALS
                {
                    return Ok(None);
                }
                attempted_trials.push(trial);

                let mut segments = storage.vec(intervals.len())?;
                // 번호·글머리표도 첫 물리 줄의 글자다. 뒤 줄에는 참여하지 않는다.
                let mut maximum_font_size = if start_char == 0 && frame.row_count() == first_row {
                    marker_font_size
                } else {
                    0.0
                };
                let mut inline_metrics = (frame.row_count() == first_row)
                    .then_some(terminal_inline_metrics)
                    .flatten();
                let mut inline_spacing_height = (frame.row_count() == first_row)
                    .then_some(terminal_inline_spacing_height)
                    .flatten();
                let mut row_terminated = false;
                let interval_width = |index: usize, interval: &std::ops::Range<i32>| {
                    let width = crate::renderer::hwpunit_to_px(
                        interval.end.saturating_sub(interval.start),
                        dpi,
                    );
                    if index == 0 {
                        (width - marker_hang_px).max(1.0)
                    } else {
                        width
                    }
                };
                // 마커는 첫 구간만 소유한다. 낱말 회피도 같은 실제 가용 폭을 비교한다.
                let widest_available_px = intervals
                    .iter()
                    .enumerate()
                    .map(|(index, interval)| interval_width(index, interval))
                    .fold(0.0, f64::max);
                for (interval_index, interval) in intervals.into_iter().enumerate() {
                    let available_width_px = interval_width(interval_index, &interval);
                    // 들여쓰기·내어쓰기는 물리 행의 첫 구간만 소유한다.
                    // 같은 행에서 개체 반대편 구간으로 이어져도 다시 차감하지 않는다.
                    let interval_indent_px = if interval_index == 0 { indent_px } else { 0.0 };
                    // 같은 물리 줄의 다른 구간에 온전한 낱말이 들어가면 그대로 보존한다.
                    // 넓은 구간을 채운 뒤 좁은 옆 구간 때문에 글자 단위로 쪼개지 않는다.
                    if cursor.fallback_char_idx.is_none() {
                        if let Some(BreakToken::Text {
                            base_width,
                            end_idx,
                            ..
                        }) = tokens.get(cursor.token_index)
                        {
                            let word = FitWidthHwp::trimmed(
                                to_hwp(*base_width),
                                &letter_spacing_px,
                                *end_idx,
                            );
                            let fits = |width| {
                                text_token_fits_in_line_with_tolerance_hwp(
                                    0, word, 0, width, None, 0,
                                )
                            };
                            let widest_available = to_hwp(widest_available_px);
                            if available_width_px < widest_available_px
                                && !fits(to_hwp(available_width_px))
                                && fits(widest_available)
                            {
                                let boundary =
                                    char_index_to_utf16_offset(para, cursor.line_start_idx);
                                segments.push(RowSegment::new(
                                    boundary..boundary,
                                    interval,
                                    source_tag | LineSeg::TAG_EMPTY_SEGMENT,
                                ));
                                continue;
                            }
                        }
                    }
                    let tab_grid_origin_px = crate::renderer::hwpunit_to_px(interval.start, dpi)
                        + if interval_index == 0 {
                            marker_hang_px
                        } else {
                            0.0
                        };
                    cursor.tab_grid_origin_px = Some(tab_grid_origin_px);
                    let terminal = terminal_tokens.as_ref().and_then(|terminal_tokens| {
                        let mut replay = FillCursor::replay_from_boundary(
                            terminal_tokens,
                            cursor.line_start_idx,
                            cursor.is_first_line,
                        );
                        replay.allow_metric_tolerance = false;
                        replay.tab_grid_origin_px = Some(tab_grid_origin_px);
                        let filled = fill_one_interval(
                            terminal_tokens,
                            &text_chars,
                            available_width_px,
                            interval_indent_px,
                            tab_fill,
                            korean_break_unit,
                            condense_min_space,
                            &letter_spacing_px,
                            &mut replay,
                            None,
                        )?;
                        (filled.termination == FillTermination::ParagraphEnd)
                            .then_some((filled, replay))
                    });
                    let selected_space_metric = if terminal.is_some() {
                        SpaceMetric::Stored
                    } else {
                        space_metric
                    };
                    let filled = if let Some((filled, replay)) = terminal {
                        cursor = replay;
                        filled
                    } else {
                        let Some(filled) = fill_one_interval(
                            &tokens,
                            &text_chars,
                            available_width_px,
                            interval_indent_px,
                            tab_fill,
                            korean_break_unit,
                            condense_min_space,
                            &letter_spacing_px,
                            &mut cursor,
                            kerning_break_session.as_mut(),
                        ) else {
                            return Ok(None);
                        };
                        filled
                    };
                    let line = &filled.line;
                    maximum_font_size = maximum_font_size.max(line.max_font_size);
                    if filled.termination == FillTermination::ParagraphEnd {
                        maximum_font_size = maximum_font_size.max(paragraph_end_font_size);
                    }
                    // 강제 줄 나눔 글자도 문단 끝 표지처럼 제 줄의 글자 상자를 갖는다(#7685).
                    // 나눔만 남은 줄이 12px 기본값으로 접히면 한/글 정본보다 줄마다
                    // 4.8px 짧다(80168 표 칸 `⏎②…` 첫 줄: 한/글 19.2px 간격).
                    if filled.termination == FillTermination::ForcedBreak {
                        let break_font_size = line
                            .end_idx
                            .checked_sub(1)
                            .and_then(|idx| para.char_shape_id_at(idx))
                            .and_then(|id| styles.char_styles.get(id as usize))
                            .map_or(0.0, |style| style.font_size);
                        maximum_font_size = maximum_font_size.max(break_font_size);
                    }
                    for control in inline_controls.iter().filter(|control| {
                        inline_control_flow::owns_line(control, line, text_chars.len())
                    }) {
                        inline_spacing_height =
                            inline_spacing_height.max(control.spacing_height_hwp);
                        inline_metrics = match inline_metrics {
                            Some((height_hwp, baseline_distance_hwp))
                                if height_hwp > control.height_hwp =>
                            {
                                Some((height_hwp, baseline_distance_hwp))
                            }
                            Some((height_hwp, baseline_distance_hwp))
                                if height_hwp == control.height_hwp =>
                            {
                                Some((
                                    height_hwp,
                                    baseline_distance_hwp.max(control.baseline_distance_hwp),
                                ))
                            }
                            _ => Some((control.height_hwp, control.baseline_distance_hwp)),
                        };
                    }
                    let text_start =
                        if start_char == 0 && frame.row_count() == first_row && segments.is_empty()
                        {
                            0
                        } else {
                            line_start_utf16_offset(para, line.start_idx, &inline_controls)
                        };
                    let text_end = line_start_utf16_offset(para, line.end_idx, &inline_controls)
                        .max(text_start);
                    let mut segment = RowSegment::new(text_start..text_end, interval, source_tag);
                    segment.space_metric = selected_space_metric;
                    segments.push(segment);

                    if filled.termination != FillTermination::IntervalFull {
                        row_terminated = true;
                        break;
                    }
                }

                // 문단 끝까지 채운 물리 줄에서만 종료 문자의 높이를 반영한다.
                // 같은 값으로 carve를 다시 수행해 측정과 실제 배치의 행 높이를 일치시킨다.
                if cursor.finished {
                    maximum_font_size =
                        maximum_font_size.max(paragraph_end_font_size_px(para, styles));
                }
                let mut metrics = frame_metrics_for_line(
                    maximum_font_size,
                    fallback_font_size,
                    line_spacing_type,
                    line_spacing_value,
                    dpi,
                );
                if let Some(height) = inline_spacing_height {
                    // Match scalar reflow: only participating objects enlarge
                    // the line-spacing basis, alongside this row's text strut.
                    metrics.line_spacing = compute_line_spacing_hwp(
                        line_spacing_type,
                        line_spacing_value,
                        metrics.line_height.max(height),
                        dpi,
                    );
                }
                if let Some((height_hwp, baseline_distance_hwp)) = inline_metrics {
                    let inline_owns_row_height = height_hwp > metrics.line_height;
                    apply_inline_control_frame_height(&mut metrics, height_hwp);
                    if inline_owns_row_height {
                        if let Some(baseline_distance_hwp) = baseline_distance_hwp {
                            metrics.baseline_distance = baseline_distance_hwp;
                        }
                    }
                }
                if metrics.line_height != candidate_height {
                    candidate_height = metrics.line_height;
                    continue;
                }

                if row_terminated && segments.len() < frame.current_intervals.len() {
                    let text_start = segments
                        .last()
                        .map(|segment| segment.text_range.end)
                        .unwrap_or(0);
                    for interval in frame.current_intervals[segments.len()..].iter().cloned() {
                        segments.push(RowSegment::new(
                            text_start..text_start,
                            interval,
                            source_tag | LineSeg::TAG_EMPTY_SEGMENT,
                        ));
                    }
                }

                // 반환용 LineSeg 사본만 표시하면 공통 프레임을 다시 읽는 소비자가
                // 들여쓰기를 잃는다. 확정하는 실제 행에도 같은 기록을 보존한다.
                let indented = if frame.row_count() == first_row {
                    indentation_pattern.0
                } else {
                    indentation_pattern.1
                };
                let head = start_char == 0
                    && frame.row_count() == first_row
                    && paragraph_has_head(para_style);
                for (index, segment) in segments.iter_mut().enumerate() {
                    if indented && index == 0 {
                        segment.source_tag |= LineSeg::TAG_INDENTATION;
                    } else {
                        segment.source_tag &= !LineSeg::TAG_INDENTATION;
                    }
                    if head && index == 0 {
                        segment.source_tag |= LineSeg::TAG_PARAGRAPH_HEAD;
                    }
                }
                if frame
                    .try_commit_carved_row(metrics, segments, storage)?
                    .is_none()
                {
                    return Ok(None);
                }
                break;
            }
        }
        // [#7160] 저장 줄이 없는 TAC 표 host 에서만 말미 공백 줄을 앞 줄이 흡수한다 —
        // 표가 자기 줄을 얻으면서 그 앞에 남던 공백 줄이 한/글에는 없다.
        if para.line_segs.is_empty() && supports_tac_table_band_frame_controls(para) {
            frame.try_absorb_whitespace_only_rows(&para.text, first_row, storage)?;
        }
        // 실제 행에 확정한 플래그를 그대로 투영한다. 평탄화한 segment 번호로
        // 첫/후속 줄을 다시 추측하면 같은 물리 행의 뒤 구간에 내어쓰기가 붙는다.
        Ok(Some(frame.try_project_line_segs_since(first_row, storage)?))
    })();

    let kerning_failed = kerning_break_session
        .as_ref()
        .and_then(|session| session.failed_reason())
        .is_some();
    if !matches!(result, Ok(Some(_))) {
        frame.restore_owned_append_checkpoint(frame_checkpoint);
    }
    drop(kerning_break_session);
    drop(kerning_transaction);
    if kerning_failed && result.is_ok() {
        // 한 boundary라도 예산/범위 검증에 실패하면 일부 K1 row를 게시하지
        // 않고 문단 전체를 원래 scalar transaction으로 다시 실행한다.
        return try_layout_paragraph_in_frame_impl(
            para, frame, styles, dpi, false, start_char, purpose, storage,
        );
    }
    result
}

/// The metrics for one stored physical row, computed — never read off the
/// record.
///
/// §1.4.1 recomputes `vertical_pos`, `line_height`, `text_height`,
/// `baseline_distance` and `line_spacing` on both arms and writes them back
/// over the stored values, so the frame must never take them from the file.
/// The row's span is its own `text_start` to the next row's, and its size is
/// the largest char shape active over that span.
///
/// `line_spacing` agrees with HWP's stored value on 98.53% of rows
/// (1,133,166 measured); the residual is §2.14's metricCtx settlement — three
/// independent ceilings — and is characterised, not modelled.
pub(crate) fn stored_row_metrics(
    para: &Paragraph,
    styles: &ResolvedStyleSet,
    dpi: f64,
    row: &[LineSeg],
) -> Option<FrameRowMetrics> {
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    let line_spacing_type = para_style
        .map(|style| style.line_spacing_type)
        .unwrap_or(LineSpacingType::Percent);
    let line_spacing_value = para_style.map(|style| style.line_spacing).unwrap_or(160.0);
    let fallback_font_size = para
        .char_shapes
        .first()
        .and_then(|shape| styles.char_styles.get(shape.char_shape_id as usize))
        .map(|style| style.font_size)
        .unwrap_or(12.0);

    let span_start = row.first()?.text_start;
    let row_end = row.last()?.text_start;
    let span_end = para
        .line_segs
        .iter()
        .map(|segment| segment.text_start)
        .filter(|start| *start > row_end)
        .min()
        .unwrap_or(u32::MAX);
    let active = para
        .char_shapes
        .iter()
        .filter(|shape| shape.start_pos <= span_start)
        .map(|shape| shape.start_pos)
        .max();
    let max_font_size = para
        .char_shapes
        .iter()
        .filter(|shape| {
            (shape.start_pos >= span_start && shape.start_pos < span_end)
                || Some(shape.start_pos) == active
        })
        .filter_map(|shape| styles.char_styles.get(shape.char_shape_id as usize))
        .map(|style| style.font_size)
        .fold(0.0f64, f64::max);

    Some(frame_metrics_for_line(
        list_marker_metrics::include_marker(para, styles, span_start == 0, max_font_size),
        fallback_font_size,
        line_spacing_type,
        line_spacing_value,
        dpi,
    ))
}

/// Resolve a paragraph's stored rows through the caller's frame.
///
/// The stored records are a cache, not frame inputs. The frame always computes
/// the physical-row key `(count, column_start, segment_width)` first and admits
/// the cache only on exact equality. Staleness is an additional invalidator: a
/// geometrically matching record that describes obsolete text is still rebuilt.
pub(crate) fn resolve_stored_line_segs_in_frame(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    legacy_hwp3_stored_geometry: bool,
    miss_policy: StoredRowMissPolicy,
    stale: bool,
    // [#6175] 같은 세로 band의 용지/쪽 기준 어울림 개체 증거(HWPUNIT).
    // 저장 행의 결손 폭과 세로 위치가 함께 맞으면 좁음의 출처가 외부 기하다.
    float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
    known_square_band: bool,
) -> Option<StoredRowResolution> {
    match resolve_stored_line_segs_in_frame_with_storage(
        para,
        frame,
        styles,
        dpi,
        legacy_hwp3_stored_geometry,
        miss_policy,
        stale,
        float_carve_evidence,
        known_square_band,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn resolve_stored_line_segs_in_frame_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    legacy_hwp3_stored_geometry: bool,
    miss_policy: StoredRowMissPolicy,
    stale: bool,
    // [#6175] 같은 세로 band의 용지/쪽 기준 어울림 개체 증거(HWPUNIT).
    // 저장 행의 결손 폭과 세로 위치가 함께 맞으면 좁음의 출처가 외부 기하다.
    float_carve_evidence: &[crate::renderer::float_placement::FloatCarveEvidence],
    known_square_band: bool,
    storage: &S,
) -> Result<Option<StoredRowResolution>, S::Error> {
    let rollback = if S::UNBOUNDED {
        None
    } else {
        Some(frame.try_append_checkpoint(storage)?)
    };
    let resolved = (|| -> Result<Option<StoredRowResolution>, S::Error> {
        Ok({
            // [#6102] 폭-중립 float 표 host 는 본문 프레임 게이트가 이미 통과시킨
            // 문단이다 — picture-band 게이트만으로 사양하면 저장 textpos 의
            // admission 검증이 통째로 빠져 결재문서본문 계열의 첫 줄이 우단 밖으로
            // 넘친다(36360328 +75px, 한글 2020 은 재래핑). 단, 이 계보는 **stale
            // (물리 위반) 증거가 있을 때만** 개입한다 — 증거 없이 admission 불일치
            // 만으로 재래핑하면 종전 무소유였던 float-host 문단의 확정 핀이 흔들린다.
            // 저장 줄이 아예 없으면 보호할 저장 기하가 없다. 폭-중립 표 호스트도
            // 아래 NO_LS fill로 보내 현재 frame의 줄 경계를 계산한다 (#6950).
            // [#7160] 글자처럼 취급 표 host 도 같은 축이다 — 저장 줄이 없으면 아래 NO_LS fill 이
            // 유일한 소유자이고, `inline_control_size_hwp` 가 그 표의 폭을 인라인 토큰으로 계상한다.
            // 거절하면 45자 합성 줄이 그대로 남아 표가 자기 줄을 못 얻는다(distribution_doc 3쪽).
            let tac_table_host_fill = para.line_segs.is_empty()
                && (supports_tac_table_band_frame_controls(para)
                    || supports_overlay_table_frame_controls(para)
                    || supports_overlay_shape_frame_controls(para));
            if !supports_picture_band_frame_controls(para)
                && !tac_table_host_fill
                && !no_ls_inline_picture_host_fill(para)
                && !(para.line_segs.is_empty() && supports_inline_form_frame_controls(para))
            {
                if !supports_cached_body_frame_controls(para)
                    || (!stale && !para.line_segs.is_empty())
                {
                    return Ok(None);
                }
            }

            // NO_LS: there is no stored record to compare, so this is the rebuild case
            // outright and belongs to the frame's fill. The fill tokenizes through
            // `para.char_shapes`, which is the char-shape re-splitting #2632 needed —
            // a mixed-char-shape paragraph must measure the way it renders.
            if para.line_segs.is_empty() {
                return Ok(layout_paragraph_in_frame_with_storage(
                    para, frame, styles, dpi, storage,
                )?
                .map(|_| StoredRowResolution::Reflowed));
            }

            // HWP3-lineage stored rows use a legacy horizontal-origin lane that the
            // common ParaShape does not carry. The first sample16 mismatch is a
            // non-stale row stored at 2500..50024 while the common style resolves a
            // 5000..50024 Frame (margin 5000, hanging indent -2500). HWP3→HWP5 keeps
            // that stored origin too (#1892 round-trip: stored 0..42520 versus Frame
            // 1200..42520), so provenance — not the current container — owns the gate.
            // This is not a cache-key mismatch the common Frame can repair; it lacks
            // jurisdiction. Edited/stale text still takes the fresh fill below, and
            // NO_LS already took the Frame-owned branch above.
            if legacy_hwp3_stored_geometry && !stale {
                return Ok(None);
            }

            // 한 프레임은 다른 단·쪽의 시작을 소유하지 않는다. 저장 분할이 유효한
            // 문단의 전체 사다리를 이 프레임의 캐시와 비교해 거절한 뒤 다시 채우면,
            // 원래 단 경계와 후속 문단의 원점까지 사라진다. 편집·명시적 stale 경로는
            // 현재 프레임의 재조판 계약을 유지한다.
            if !stale
                && !para.stored_text_partition_is_dirty()
                && super::stored_row_fragments::crosses_physical_frame(para)
            {
                return Ok(None);
            }

            // #4755 §1 recomputes a FIRST..LAST split row as one physical row, and the
            // picture-band frame does exactly that because it holds the exclusion that
            // split it. A frame with no exclusions cannot: it carves one full-width
            // interval, so reflowing a split row there flattens it and destroys the
            // stored fragment geometry (#4690 `30098` p3 pi=48 stores `0..3402` and
            // `45305..48188` around a float; a full-width recompute loses the right
            // fragment entirely).
            //
            // An exclusion need not split one physical row into multiple slots. It can
            // leave one narrowed slot for several rows and then end, returning later
            // rows to the full frame width. #4090 pi=45 is exactly that shape: six
            // `0+26319` rows beside a Square table, followed by one `0+48188` row below
            // it. Different single-slot row extents therefore prove the same missing
            // per-band geometry as FIRST..LAST splitting. That is a limit of
            // jurisdiction, not a comparison tolerance — the frame declines rather
            // than claiming rows whose geometry it cannot compute, and the paragraph
            // stays with its established owner.
            //
            // This guard is live and load-bearing: it keeps cache admission and strict
            // reflow from flattening a split row when this frame lacks the exclusion
            // geometry that originally produced it. The multi-slot comparison becomes
            // live when a caller supplies those exclusions.
            if !frame.models_exclusions()
                && stored_rows_require_external_geometry(
                    para,
                    frame,
                    float_carve_evidence,
                    known_square_band,
                )
            {
                return Ok(None);
            }

            // 수식 대체 폭이 달라진 곳부터만 채운다. 앞행은 같은 프레임의 수용 검사와
            // 저장 줄 출처를 통과해야 하며, 실패하면 이 부분 경로는 결과를 남기지 않는다.
            if let Some(start_row) = remeasured_equation_start_row(para) {
                let checkpoint = frame.try_append_checkpoint(storage)?;
                if !para.stored_text_partition_is_dirty()
                    && !stored_rows_require_external_geometry(
                        para,
                        frame,
                        float_carve_evidence,
                        known_square_band,
                    )
                    && (start_row == 0
                        || frame.try_admit_stored_rows_with_storage(
                            &para.line_segs[..start_row],
                            |row| stored_row_metrics(para, styles, dpi, row),
                            storage,
                        )?)
                {
                    let (start_char, _) = super::utf16_range_to_text_range(
                        &para.char_offsets,
                        para.line_seg_text_start(start_row),
                        u32::MAX,
                        para.text.chars().count(),
                    );
                    if try_layout_paragraph_in_frame_impl(
                        para,
                        frame,
                        styles,
                        dpi,
                        true,
                        start_char,
                        FramePurpose::Body,
                        storage,
                    )?
                    .is_some()
                    {
                        return Ok(Some(StoredRowResolution::Reflowed));
                    }
                }
                frame.restore_owned_append_checkpoint(checkpoint);
                return Ok(None);
            }

            let entry_checkpoint = frame.try_append_checkpoint(storage)?;
            let cache_geometry_matches = stored_rows_reproduce_frame_expectation_with_storage(
                para, frame, styles, dpi, storage,
            )?;
            if cache_geometry_matches && !stale {
                return Ok(Some(StoredRowResolution::Stored));
            }

            // Admission commits recomputed rows into the frame. A stale cache must not
            // leave those rows behind before the fresh fill starts. Rejection already
            // restores internally, so this is deliberately idempotent on that arm.
            frame.restore_owned_append_checkpoint(entry_checkpoint);
            if !cache_geometry_matches
                && !stale
                && miss_policy == StoredRowMissPolicy::UnmodelledUnlessStale
            {
                return Ok(None);
            }
            if !cache_geometry_matches {
                report_stored_row_key_mismatch_with_storage(para, frame, styles, dpi, storage)?;
            }

            let mut reflow_input = storage.clone_paragraph(para)?;
            // A rejected row cannot remain the provenance template for fresh rows:
            // placement/empty flags describe the stored physical rows, not this
            // frame's newly carved projection.
            reflow_input.line_segs.clear();
            layout_paragraph_in_frame_with_storage(&reflow_input, frame, styles, dpi, storage)?
                .map(|_| StoredRowResolution::Reflowed)
        })
    })();
    if resolved.is_err() {
        if let Some(checkpoint) = rollback {
            frame.restore_owned_append_checkpoint(checkpoint);
        }
    }
    resolved
}

/// [#6175] 저장 행의 결손 폭이 어울림 개체의 흐름 폭과 같다고 볼 허용 오차(HWPUNIT).
///
/// 개체와 본문 사이의 간격(한컴이 넣는 여백)이 이 안에 든다 — 156655489 실측 284,
/// 156647303 실측 도 같은 자릿수다. 1200HU ≈ 16px 로, 글자 한 칸(약 1000HU)보다
/// 크지 않게 잡아 서로 다른 폭의 개체를 우연히 맞추지 않는다.
const FLOAT_CARVE_MATCH_TOLERANCE_HU: i32 = 1200;

/// A one-unit layout quantum is enough to distinguish a real narrowed lane
/// from a full-width row after integer projection. Keep this local to stored
/// row provenance rather than exposing layout-frame internals.
const UNIFORM_INSET_MIN_DELTA_HU: i32 = 4;

/// Whether the frame's own carve reproduces every stored row — §1.4.1's
/// `(count, horzpos, horzsize)` cache key, computed before reuse.
///
/// Takes the frame by `&mut` and leaves an admitted paragraph's rows committed
/// in it, because that is what makes the answer checkable — a caller that wants
/// the frame's version of an admitted paragraph can `project_line_segs()` it.
/// A rejection restores the entry checkpoint, so the frame is exactly as it was
/// handed in.
///
/// **One reachability limit, stated rather than implied.** The multi-slot
/// FIRST..LAST comparison inside `try_admit_stored_rows` has no production
/// caller and cannot acquire one until float exclusions are wired through:
/// `ParagraphBox::frame` builds every body frame with an empty exclusion list,
/// so `models_exclusions()` is false at the only production call site and the
/// guard above turns split rows away before the comparison sees them. The
/// picture-band frame does hold exclusions, but it clears `line_segs` and
/// reflows rather than comparing. Until a float set reaches a body frame, the
/// multi-slot path is exercised by unit tests only.
pub(crate) fn stored_rows_reproduce_frame_expectation(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
) -> bool {
    match stored_rows_reproduce_frame_expectation_with_storage(
        para,
        frame,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn stored_rows_reproduce_frame_expectation_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    frame: &mut LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<bool, S::Error> {
    Ok({
        frame.try_admit_stored_rows_with_storage(
            &para.line_segs,
            |row| stored_row_metrics(para, styles, dpi, row),
            storage,
        )?
    })
}

/// Report a cache-key mismatch already found by the production admission gate.
///
/// Off unless `RHWP_DIAG_STORED_ROW_KEY` is set, so the production path pays
/// one `var_os` and no allocation. Probes a clone: a report must not be able to
/// move the frame it is reporting on.
fn report_stored_row_key_mismatch(
    para: &Paragraph,
    frame: &LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    match report_stored_row_key_mismatch_with_storage(
        para,
        frame,
        styles,
        dpi,
        &crate::storage::Unbounded,
    ) {
        Ok(value) => value,
        Err(never) => match never {},
    }
}

pub(crate) fn report_stored_row_key_mismatch_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    frame: &LayoutFrame,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<(), S::Error> {
    let _: () = {
        if std::env::var_os("RHWP_DIAG_STORED_ROW_KEY").is_none() {
            return Ok(());
        }
        let mut probe = crate::storage::try_clone(frame, storage)?;
        if !stored_rows_reproduce_frame_expectation_with_storage(
            para, &mut probe, styles, dpi, storage,
        )? {
            eprintln!(
                "DIAG_STORED_ROW_KEY mismatch rows={} stored=[{}]",
                para.line_segs.len(),
                {
                    let mut entries = storage.vec(para.line_segs.len())?;
                    for segment in &para.line_segs {
                        entries.push(storage.display(&format_args!(
                            "{}+{}",
                            segment.column_start, segment.segment_width
                        ))?);
                    }
                    storage.join(&entries, " ")?
                },
            );
        }
    };
    Ok(())
}

/// This mirrors `float_placement::horizontal_range`'s `HorzRelTo::Para`
/// rule: the host's left paragraph margin shifts the object reference, but
/// the right text margin does not shrink it.
fn picture_band_paragraph_reference(
    column_horizontal: &Range<i32>,
    host_margin_left: i32,
) -> Option<Range<i32>> {
    let start = column_horizontal.start.saturating_add(host_margin_left);
    (start < column_horizontal.end).then_some(start..column_horizontal.end)
}

/// Lay out one proven non-TAC Picture/Square band without reading stored
/// `LineSeg` geometry. One `LayoutFrame` remains live from the Picture's
/// source anchor through the first full-width paragraph boundary.
///
/// This is intentionally a fail-closed transaction. It accepts one host
/// Picture, treats only TAC Equations as inline flow, and rejects any
/// paragraph boundary that would require another layout owner.
///
/// Takes the column width in **pixels**, because that is what makes the
/// paragraph box here the same object the body path builds. It used to take
/// HWPUNIT and derive its own horizontal range as
/// `column_width_hwp - px_to_hwpunit(margin_right)`, where `ParagraphBox::body`
/// computes `px_to_hwpunit(column_width_px - margin_right_px)` — one truncation
/// against two. Those disagree by one HWPUNIT often enough to matter, and the
/// geometry pitch turns a one-unit disagreement into **four** whenever it
/// straddles a multiple of the pitch, because flooring `x - 1` where `x ≡ 0`
/// gives `x - 4`. Both routes publish `line_segs` that are persisted, so the
/// same paragraph could be written to disk with two different
/// `segment_width`s depending on whether a float was in its band.
///
/// The *column* box stays a local range rather than becoming a `ParagraphBox`:
/// float placement needs the column's own edges, unindented by paragraph
/// margins ([`picture_band_paragraph_reference`],
/// `float_placement::resolve_picture_exclusion`), and that is not what
/// `ParagraphBox` models. Stretching the type to cover both would put the
/// two coordinate systems back into one object, which is the confusion it
/// exists to prevent.
pub(crate) fn layout_picture_band(
    paragraphs: &[Paragraph],
    host_index: usize,
    column_width_px: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
    // [#6202] 용지 기준(`Paper`/`Page`) 어울림 개체를 재는 데 필요한 본문 상자의 용지 원점.
    paper_origin_px: (f64, f64),
) -> Option<PictureBandLayout> {
    layout_picture_band_impl(
        paragraphs,
        host_index,
        column_width_px,
        styles,
        dpi,
        paper_origin_px,
        false,
    )
}

/// Container flows carry the actual exclusion geometry, so stored rows can be
/// admitted against that frame instead of being treated as full-width text.
pub(crate) fn layout_container_picture_band(
    paragraphs: &[Paragraph],
    host_index: usize,
    column_width_px: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
    admit_stored: bool,
) -> Option<PictureBandLayout> {
    layout_picture_band_impl(
        paragraphs,
        host_index,
        column_width_px,
        styles,
        dpi,
        (0.0, 0.0),
        admit_stored,
    )
}

fn layout_picture_band_impl(
    paragraphs: &[Paragraph],
    host_index: usize,
    column_width_px: f64,
    styles: &ResolvedStyleSet,
    dpi: f64,
    paper_origin_px: (f64, f64),
    admit_stored: bool,
) -> Option<PictureBandLayout> {
    let host = paragraphs.get(host_index)?;
    let column_horizontal = 0..px_to_hwpunit(column_width_px, dpi);
    let margins_for = |paragraph: &Paragraph| {
        let style = styles.para_styles.get(paragraph.para_shape_id as usize);
        (
            style.map(|value| value.margin_left).unwrap_or(0.0),
            style.map(|value| value.margin_right).unwrap_or(0.0),
        )
    };
    // `body_for_style`, like every other body route. An earlier revision used
    // bare `body` here on the argument that the list-origin blocker was a
    // separate decision — that was scope deferral, not a reason, and it left
    // this route publishing a different origin from the edit route for the same
    // list paragraph.
    let box_for = |paragraph: &Paragraph| {
        let paragraph_box = ParagraphBox::body_for_style(
            column_width_px,
            styles.para_styles.get(paragraph.para_shape_id as usize),
            dpi,
        );
        // Supersedes the old `(start < end)` test, and is strictly stronger:
        // that one ran before the geometry pitch, so a base of width 1..3 with
        // a misaligned left edge passed it and then inverted.
        paragraph_box.is_usable().then_some(paragraph_box)
    };
    let host_box = box_for(host)?;
    let host_horizontal = host_box.effective();
    let host_margin_left = px_to_hwpunit(margins_for(host).0, dpi);
    let host_paragraph_horizontal =
        picture_band_paragraph_reference(&column_horizontal, host_margin_left)?;

    // 그림은 한 장만 받는다. [#8399] 어울림 도형은 개수와 관계없이 각자 밴드를 더한다.
    let band_objects: Vec<(usize, &Control)> = host
        .controls
        .iter()
        .enumerate()
        .filter(|(_, control)| control_owns_body_band(control))
        .collect();
    if band_objects.is_empty()
        || band_objects
            .iter()
            .filter(|(_, control)| matches!(control, Control::Picture(_)))
            .count()
            > 1
    {
        return None;
    }

    // A paragraph-relative Picture starts at its control's raw UTF-16 stream
    // position, not necessarily at the first visible character. Lay out a
    // clean, full-width host first so the anchor row has no stored-LineSeg
    // dependency.
    let mut anchor_input = host.clone();
    anchor_input.line_segs.clear();
    let mut anchor_frame = host_box.frame(0);
    let anchor_rows = layout_paragraph_in_frame(&anchor_input, &mut anchor_frame, styles, dpi)?;
    let raw_positions = host.control_utf16_positions();
    let paper = crate::renderer::float_placement::PaperOrigin {
        body_left: px_to_hwpunit(paper_origin_px.0, dpi),
        body_top: px_to_hwpunit(paper_origin_px.1, dpi),
        // 밴드는 host 문단에서 시작한다 — 그 문단의 저장 절대 위치가 로컬 원점이다.
        band_abs_top: host
            .line_segs
            .iter()
            .find(|seg| seg.tag & 0x8000_0000 == 0)
            .map(|seg| seg.vertical_pos)
            .unwrap_or(0),
    };
    let mut exclusions = Vec::with_capacity(band_objects.len());
    for (control_index, control) in band_objects {
        let raw_start = raw_positions.get(control_index).copied()?;
        let anchor_top = anchor_rows
            .iter()
            .rfind(|row| row.text_start <= raw_start)
            .map(|row| row.vertical_pos)?;
        let exclusion = match control {
            Control::Picture(picture) => {
                crate::renderer::float_placement::resolve_picture_exclusion(
                    picture,
                    column_horizontal.clone(),
                    host_paragraph_horizontal.clone(),
                    anchor_top,
                    paper,
                )
            }
            Control::Shape(shape) => crate::renderer::float_placement::resolve_shape_exclusion(
                shape.common(),
                column_horizontal.clone(),
                host_paragraph_horizontal.clone(),
                anchor_top,
                paper,
            ),
            _ => None,
        }?;
        exclusions.push(exclusion);
    }
    let exclusion_end = exclusions
        .iter()
        .map(|exclusion| exclusion.vertical.end)
        .max()?;
    let mut frame = host_box.frame_with(0, exclusions);
    let mut line_segs = Vec::new();
    let mut space_metrics = Vec::new();
    let mut preserved_stored = Vec::new();

    for (paragraph_index, paragraph) in paragraphs.iter().enumerate().skip(host_index) {
        if frame.top >= exclusion_end {
            break;
        }

        let paragraph_style = styles.para_styles.get(paragraph.para_shape_id as usize);
        // [#8399] host 앞의 나눔(구역 첫 문단의 구역 나눔 등)은 밴드가 시작하기 전의 경계다.
        // 밴드 안에서 새 단·쪽을 여는 것은 뒤 문단의 나눔뿐이다.
        let successor = paragraph_index != host_index;
        if (successor && paragraph.column_type != ColumnBreakType::None)
            || paragraph_style.is_some_and(|style| {
                style.spacing_before.abs() > f64::EPSILON
                    || style.spacing_after.abs() > f64::EPSILON
                    || (successor && style.page_break_before)
            })
            || box_for(paragraph)?.effective() != host_horizontal
            || (successor && paragraph.controls.iter().any(control_owns_body_band))
        {
            return None;
        }

        let mut input = paragraph.clone();
        // A picture-band projection is freshly computed implementation state,
        // even when the source paragraph had authentic cached rows. Clearing
        // the cache prevents row-local flags from leaking and keeps vpos ladder
        // repair from treating the fresh zero-origin row as a saved reset.
        let first_row = frame.row_count();
        let preserved = if admit_stored && !crate::renderer::para_has_no_stored_line_segs(paragraph)
        {
            resolve_stored_line_segs_in_frame(
                paragraph,
                &mut frame,
                styles,
                dpi,
                false,
                StoredRowMissPolicy::Reflow,
                paragraph.stored_text_partition_is_dirty(),
                &[],
                true,
            )? == StoredRowResolution::Stored
        } else {
            input.line_segs.clear();
            layout_paragraph_in_frame(&input, &mut frame, styles, dpi)?;
            false
        };
        let paragraph_lines = if preserved {
            paragraph.line_segs.clone()
        } else {
            frame.project_line_segs_since(first_row)
        };
        space_metrics.push(frame.project_space_metrics_since(first_row));
        line_segs.push(paragraph_lines);
        preserved_stored.push(preserved);
    }

    // 구역의 마지막 문단에서 끝난 밴드는 더 깎을 줄이 없다 — 남은 배제 높이는 흐름에 영향이
    // 없다(#8399: 한/글도 마지막 문단만 깎고 끝낸다). 다만 글이 있는 줄을 하나도 깎지 않았으면 밴드가
    // 흐름을 바꾸지 않는다 — 그 문단들의 줄은 평범한 소유자(빈 그림 문단은 #1151)가 낸다.
    let band_closed = frame.top >= exclusion_end
        || (host_index + line_segs.len() == paragraphs.len()
            && paragraphs[host_index..]
                .iter()
                .zip(&line_segs)
                .any(|(paragraph, rows)| {
                    paragraph.text.chars().any(|ch| !ch.is_whitespace())
                        && rows.iter().any(|row| {
                            row_is_carved_from_box(
                                row.column_start,
                                row.segment_width,
                                &host_horizontal,
                            )
                        })
                }));
    (!line_segs.is_empty() && band_closed).then_some(PictureBandLayout {
        paragraph_range: host_index..host_index + line_segs.len(),
        line_segs,
        space_metrics,
        preserved_stored,
    })
}

/// 문단의 line_segs를 텍스트 내용과 **문단 상자**에 맞게 재계산한다.
///
/// 텍스트 편집(삽입/삭제) 후 호출하여 줄 바꿈을 재배치한다.
///
/// 인자는 폭이 아니라 [`ParagraphBox`] 다 — 호출자가 자기 좌표계를 말해야 한다.
/// 폭만 받던 종전 계약은 원점을 잃었고, 그 결과 본문 편집이 `column_start=0`,
/// `segment_width=가용폭` 을 발행해 HWP 의 저장 기록(열 기준 `column_start=여백`)
/// 과도, 렌더 프레임이 깎는 상자와도 어긋났다.
pub(crate) fn reflow_line_segs(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true);
    super::equation_line_metrics::publish_regenerated_rows(para, styles);
}

/// 셀 분할로 저장 폭이 stale해진 문단을 다시 조판한다.
///
/// 한컴은 좁아진 셀에서만 본문 뒤의 inline control을 별도 source line으로 저장한다.
/// 이 규칙을 일반 reflow에 적용하면 원본 문서의 이미 권위적인 control host line까지
/// 분리되어 pagination이 달라진다 (#4138/#2424). 호출자는 split 직후 stale-cell
/// 복구 경로로 한정한다.
pub(crate) fn reflow_line_segs_after_cell_split(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, true, true);
    super::equation_line_metrics::publish_regenerated_rows(para, styles);
}

/// 저장 LINE_SEG가 유효한 셀 텍스트 편집은 수정된 줄 이전의 경계를 그대로 둔다.
///
/// 한컴은 중간 줄의 짧은 edit에서 문단 전체를 다시 나누지 않는다. prefix 경계를 다시
/// 계산하면 뒤 줄의 가용 폭이 인위적으로 커져 실제 HWP 저장본과 다른 다음 줄 전환을 만들 수
/// 있다. 단, prefix가 유효한 token 경계일 때만 보존하며, 합성 문단·첫 줄 edit·inline control은
/// 기존 full reflow로 안전하게 폴백한다.
pub(crate) fn reflow_line_segs_after_cell_text_edit(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
    edit_char_offset: usize,
) -> bool {
    let preserved = reflow_line_segs_impl(
        para,
        paragraph_box,
        styles,
        dpi,
        Some(edit_char_offset),
        false,
        true,
    );
    super::equation_line_metrics::publish_regenerated_rows(para, styles);
    preserved
}

/// 저장 `LINE_SEG` 사다리가 배치 권위를 갖는 구역의 합성 문단을 재조판한다.
///
/// 익명화·부분 편집으로 저장 줄이 빠졌어도 새 개체 줄의 간격 기준은
/// 호스트 글자모양이다. 저장 좌표와의 혼합은 소비 경로에서 구분하며,
/// 쪽수 핀을 맞추기 위해 글자 크기를 고정 기본값으로 낮추지 않는다.
/// 전면 합성 문서는 `reflow_line_segs` 를 쓴다.
pub(crate) fn reflow_line_segs_in_stored_section(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    let _ = reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true);
    super::equation_line_metrics::publish_regenerated_rows(para, styles);
}

fn reflow_line_segs_impl(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
    preserve_prefix_for_edit: Option<usize>,
    split_stale_cell_reflow: bool,
    object_line_font_basis: bool,
) -> bool {
    match try_reflow_line_segs_impl(
        para,
        paragraph_box,
        styles,
        dpi,
        preserve_prefix_for_edit,
        split_stale_cell_reflow,
        object_line_font_basis,
        &Unbounded,
    ) {
        Ok(result) => result,
        Err(never) => match never {},
    }
}

pub(crate) fn try_reflow_line_segs<S: Storage>(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
    storage: &S,
) -> Result<(), S::Error> {
    try_reflow_line_segs_impl(para, paragraph_box, styles, dpi, None, false, true, storage)?;
    super::equation_line_metrics::publish_regenerated_rows(para, styles);
    Ok(())
}

fn try_reflow_line_segs_impl<S: Storage>(
    para: &mut Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
    preserve_prefix_for_edit: Option<usize>,
    split_stale_cell_reflow: bool,
    object_line_font_basis: bool,
    storage: &S,
) -> Result<bool, S::Error> {
    // An impossible box publishes nothing, and this must be the first thing
    // that happens — before the memo invalidation below, which is already a
    // mutation.
    //
    // The render path has refused since it had a box to refuse
    // (`recompose_stored_lines_in_frame`); the edit path never did, so a
    // paragraph whose margins exceed its column reached `make_line_seg` with a
    // negative `seg_width_hwp` and published `segment_width < 0` on every row.
    // That is not a rendering artifact: `segment_width` goes to disk through
    // `serializer::body_text`'s `write_i32` and raw into the HWPX
    // `linesegarray`, so the corrupt extent is written to the file. Both paths
    // now ask `ParagraphBox::is_usable()`, which is where the reasoning for
    // refusing rather than flooring lives.
    //
    // `false` is the right return: it is the "prefix was not preserved" value,
    // so the one consumer that reads it (`reflow_cell_paragraph`) takes its
    // conservative branch.
    if !paragraph_box.is_usable() {
        return Ok(false);
    }
    // [#4677] 줄을 다시 계산하면 이전에 붙여 둔 조판 전용 보강 줄은 사라진다 — 표식을
    // 남겨 두면 실제 줄을 저장에서 잘라 내게 된다.
    para.layout_only_fill_lines = 0;
    let orig = para.line_segs.first().cloned();
    // 상자 하나가 발행 기록과 프레임 둘 다의 출처다 — 종전엔 `segment_width` 를
    // 폭에서, 프레임 상자를 또 폭에서 따로 만들어 둘이 어긋날 수 있었다.
    let published_horizontal = paragraph_box.effective();
    let seg_width_hwp = paragraph_box.width_hwp();
    // [#7418·#7436] 판정 폭에서만 목록 마커 폭을 뺀다 — 프레임 채움
    // (`layout_paragraph_in_frame`)과 같은 계약이다. 게시 폭(`seg_width_hwp`)은 마커 자리를 포함한다.
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    let indent_px = if reflow_indentation_pattern(para_style, &para.line_segs, seg_width_hwp)
        == (false, false)
    {
        0.0
    } else {
        para_style.map_or(0.0, |style| style.indent)
    };
    let (marker_hang_px, indent_px) = list_marker_breaker_box(para, styles, indent_px);
    let available_width_px = (paragraph_box.width_px(dpi) - marker_hang_px).max(1.0);

    if !split_stale_cell_reflow
        && (supports_inline_picture_frame_controls(para)
            || supports_inline_form_frame_controls(para))
    {
        // An edit invalidates the old text/control partition together. Project
        // invisible control slots before filling, rather than measuring text
        // alone and attaching an end-of-paragraph picture during paint. The
        // returned raw UTF-16 rows are consumed by measurement, paint and save.
        let mut input = storage.clone_record(para)?;
        input.line_segs.clear();
        let mut frame = paragraph_box.frame(orig.as_ref().map_or(0, |line| line.vertical_pos));
        if let Some(lines) = try_layout_paragraph_in_frame_impl(
            &input,
            &mut frame,
            styles,
            dpi,
            true,
            0,
            FramePurpose::Body,
            storage,
        )? {
            para.replace_line_segs_with_space_metrics(
                lines,
                frame.try_project_space_metrics_since(0, storage)?,
            );
            return Ok(false);
        }
    }

    // ParaPr의 줄간격 설정 (합성 LineSeg에서 line_spacing 계산에 사용)
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    let ls_type = para_style
        .map(|s| s.line_spacing_type)
        .unwrap_or(LineSpacingType::Percent);
    let ls_value = para_style.map(|s| s.line_spacing).unwrap_or(160.0);

    // 줄별 max_font_size에 따라 line_height/text_height/baseline_distance를 계산
    // 한컴은 줄마다 최대 폰트 크기에 맞게 다른 치수를 사용
    let make_line_seg = |utf16_start: u32, max_font_size: f64| -> LineSeg {
        let max_font_size =
            list_marker_metrics::include_marker(para, styles, utf16_start == 0, max_font_size);
        let fs = if max_font_size > 0.0 {
            max_font_size
        } else {
            12.0
        };
        let line_height_hwp = font_size_to_line_height(fs, dpi);
        let text_height_hwp = line_height_hwp;
        let baseline_distance_hwp = baseline_distance_hwp(line_height_hwp);
        let line_spacing_hwp = compute_line_spacing_hwp(ls_type, ls_value, line_height_hwp, dpi);
        // [Task #1811] 원본 linesegarray 부재(orig=None) 시 합성 seg 에 구현속성
        // 태그를 부여 — vpos 보정 등에서 실제 저장 증거와 구분한다 (컨버터의
        // 합성 lineseg flags=0x8000_0000 관례와 정합).
        let orig_tag = orig
            .as_ref()
            .map(|ls| ls.tag)
            .unwrap_or(LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY);
        LineSeg {
            text_start: utf16_start,
            line_height: line_height_hwp,
            text_height: text_height_hwp,
            baseline_distance: baseline_distance_hwp,
            line_spacing: line_spacing_hwp,
            column_start: published_horizontal.start,
            segment_width: seg_width_hwp,
            tag: if orig_tag != 0 {
                orig_tag
            } else {
                LineSeg::TAG_SINGLE_SEGMENT_LINE
            },
            ..Default::default()
        }
    };

    if para.text.is_empty() {
        // [#4677] 각 인라인 개체의 **UTF-16 오프셋**을 함께 들고 다닌다. lineseg 의
        // `text_start` 는 PARA_TEXT 안의 코드유닛 위치이고 확장 제어문자 하나가 8 유닛을
        // 차지하므로, 컨트롤 인덱스를 그대로 쓰면 둘째 줄이 첫 제어문자 블록 한가운데(=1)를
        // 가리킨다. 한글 2022 는 그런 문서를 열 때 본문을 통째로 버리고 빈 1쪽으로 연다
        // (10k 전수 스윕의 x2h 본문 소실군 — 저장본은 rhwp 재파싱만 통과하는 함정).
        let inline_sizes = storage.collect(
            para.controls
                .iter()
                .scan(0u32, |utf16_pos, ctrl| {
                    let start = *utf16_pos;
                    if ctrl.occupies_ctrl_char_slot() {
                        *utf16_pos += CTRL_CHAR_CODE_UNITS;
                    }
                    Some((start, ctrl))
                })
                .filter_map(|(start, ctrl)| {
                    inline_control_occupied_size_hwp(ctrl, styles, dpi)
                        .map(|occupied| (start, Some(occupied)))
                        .or_else(|| matches!(ctrl, Control::Field(_)).then_some((start, None)))
                }),
        )?;
        if inline_sizes.iter().any(|(_, occupied)| occupied.is_some()) {
            let max_line_width = seg_width_hwp.max(1);
            let mut line_specs: Vec<(u32, i32, i32)> = Vec::new();
            let mut line_start = 0u32;
            let mut line_width = 0i32;
            let mut line_height = 0i32;
            // [#8507] 필드 시작(누름틀 등)은 폭이 없어도 줄의 내용이다. 한/글 2020 은 그 뒤
            // 글자처럼 취급 개체가 남은 폭에 들지 않으면 개체를 다음 줄로 넘기고 필드 줄을
            // 글자 높이의 빈 줄로 남긴다(합성 field_over19: 표 바깥 폭이 줄보다 19HU 넓으면
            // 표가 160%·10pt 빈 줄 1600HU 만큼 아래). 줄 맨 앞 개체는 넘쳐도 그 줄에 둔다.
            let mut line_has_field = false;

            for (utf16_start, occupied) in inline_sizes.iter().copied() {
                let Some((ctrl_width, ctrl_height)) = occupied else {
                    line_has_field = true;
                    continue;
                };
                if (line_width > 0 || line_has_field) && line_width + ctrl_width > max_line_width {
                    storage.push(&mut line_specs, (line_start, line_width, line_height))?;
                    line_start = utf16_start;
                    line_width = 0;
                    line_height = 0;
                    line_has_field = false;
                }
                line_width += ctrl_width;
                line_height = line_height.max(ctrl_height);
            }
            storage.push(&mut line_specs, (line_start, line_width, line_height))?;

            let orig_line_segs = storage.collect(para.line_segs.iter().cloned())?;
            let mut new_line_segs = storage.vec(line_specs.len())?;
            // 개체만 있는 줄도 줄간격 기준은 **그 문단의 글자모양 크기**다. 한컴은 개체 높이를
            // line_height 에만 반영하고 spacing 은 글자 높이로 계산한다(정답지 개체 줄 18/18:
            // 165%·14pt 문단의 표 줄 spacing 912 = 1400×0.65, 160%·10pt 문단의 그림 줄 600 = 1000×0.6).
            // 0.0 을 넘기면 내부 기본 12px(900 HU)로 떨어져 585 가 되고, 쪽마다 327 HU 씩 덜 쌓인다.
            //
            // 음수 Percent 간격은 글자 크기에 대한 줄 전진 감소량이다.
            // 저장 줄 사이의 보충 줄에서도 실제 글자 크기로 환산해야 한다.
            // 양수 간격의 저장-사다리 호환 경로는 이번 압축 간격 보정과 분리한다.
            let negative_percent_spacing =
                matches!(ls_type, LineSpacingType::Percent) && ls_value < 100.0;
            let paragraph_font_px = if object_line_font_basis || negative_percent_spacing {
                paragraph_font_size_px(para, styles).unwrap_or(12.0)
            } else {
                0.0
            };
            for (line_idx, (start_pos, _line_width, height_hwp)) in
                line_specs.into_iter().enumerate()
            {
                let mut seg = make_line_seg(start_pos, paragraph_font_px);
                if let Some(template) = orig_line_segs
                    .get(line_idx)
                    .or_else(|| orig_line_segs.first())
                {
                    seg.line_spacing = template.line_spacing;
                    seg.segment_width = if template.segment_width > 0 {
                        template.segment_width
                    } else {
                        seg_width_hwp
                    };
                    seg.tag = if template.tag != 0 {
                        template.tag
                    } else {
                        seg.tag
                    };
                }
                apply_inline_control_line_height(&mut seg, height_hwp);
                storage.push(&mut new_line_segs, seg)?;
            }

            if split_stale_cell_reflow {
                apply_reflowed_equation_row_metrics(
                    para,
                    &mut new_line_segs,
                    styles,
                    ls_type,
                    ls_value,
                    dpi,
                );
            }
            let mut vpos = orig.as_ref().map(|ls| ls.vertical_pos).unwrap_or(0);
            for seg in &mut new_line_segs {
                seg.vertical_pos = vpos;
                vpos += seg.line_height.saturating_add(seg.line_spacing);
            }
            para.replace_line_segs(new_line_segs);
        } else {
            // 빈 문단도 활성 글자 모양의 크기로 줄을 만든다. 앞 문단 LINE_SEG의
            // 치수를 복사하면 TAC 그림 높이까지 상속되므로 vpos 원점만 보존한다.
            let font_size = paragraph_font_size_px(para, styles).unwrap_or(12.0);
            let mut seg = make_line_seg(0, font_size);
            if let Some(template) = orig.as_ref() {
                seg.vertical_pos = template.vertical_pos;
                // 폭0인 빈 floating table 호스트는 개체 앵커다. 본문 글줄의
                // 가용 폭으로 바꾸면 저장 후 바깥 여백의 소유가 사라진다.
                // TAC와 글자가 있는 호스트는 위의 실제 글줄 경로를 따른다.
                if template.segment_width == 0
                    && matches!(para.controls.as_slice(), [Control::Table(table)]
                        if !table.common.treat_as_char)
                {
                    seg.segment_width = 0;
                }
            }
            if let Some(height_hwp) = inline_control_line_height_hwp(para) {
                apply_inline_control_line_height(&mut seg, height_hwp);
            }
            // 덧말만 든 문단도 글자 있는 줄처럼 덧말 높이·기준선·간격을 쓴다(한컴 12.30 저장 줄).
            if let Some((height_hwp, baseline)) =
                inline_control_flow::empty_text_ruby_row(para, styles)
            {
                if height_hwp > seg.line_height {
                    apply_inline_control_line_height(&mut seg, height_hwp);
                    seg.baseline_distance = baseline;
                    seg.line_spacing = compute_line_spacing_hwp(ls_type, ls_value, height_hwp, dpi);
                }
            }
            mark_indented_lines(
                std::slice::from_mut(&mut seg),
                0,
                para_style,
                &para.line_segs,
                seg_width_hwp,
            );
            para.replace_line_segs(storage.collect([seg])?);
        }
        return Ok(false);
    }

    // The frame owns physical-row recurrence only for an ordinary scalar
    // reflow. Stored-prefix edits, split-cell recovery, empty paragraphs, and
    // inline controls retain their established specialized paths below.
    let frame_eligible = !split_stale_cell_reflow
        && preserve_prefix_for_edit.is_none()
        && !para.text.is_empty()
        && para.controls.is_empty();
    if frame_eligible {
        // 편집 프레임과 렌더 프레임이 이제 같은 상자에서 나온다 — 종전엔 이쪽만
        // `0..seg_width_hwp`(문단 기준, 미스냅)라 열 기준 렌더 프레임과 어긋났다.
        let mut frame =
            paragraph_box.frame(orig.as_ref().map(|line| line.vertical_pos).unwrap_or(0));
        if let Some(projected) = try_layout_paragraph_in_frame_impl(
            para,
            &mut frame,
            styles,
            dpi,
            true,
            0,
            FramePurpose::Body,
            storage,
        )? {
            para.replace_line_segs_with_space_metrics(
                projected,
                frame.try_project_space_metrics_since(0, storage)?,
            );
            return Ok(false);
        }
    }

    let mut text_chars = storage.collect(para.text.chars())?;
    // 필드는 공백을 건너뛰는 줄 경계가 아닌 원자 토큰이다. 토큰화 전용
    // 필드 마커로 투영하며 원문과 모델 축은 바꾸지 않는다.
    for (position, _) in &para.layout_field_values {
        if let Some(character) = text_chars.get_mut(*position) {
            *character = '\u{0015}';
        }
    }

    let text_len = text_chars.len();
    let inline_controls = flow_inline_controls_with_storage(para, styles, storage)?;

    // 문단 스타일에서 들여쓰기 및 줄 나눔 설정 조회 (들여쓰기는 목록 마커를 얹은 값)
    let para_style = styles.para_styles.get(para.para_shape_id as usize);
    let english_break_unit = para_style.map(|s| s.english_break_unit).unwrap_or(0);
    let korean_break_unit = para_style.map(|s| s.korean_break_unit).unwrap_or(0);
    let condense_min_space = para_style.map(|s| s.condense_min_space).unwrap_or(0);

    // 토큰화 → 줄 채움 → LineSeg 생성
    let reflow_space_metric = if split_stale_cell_reflow {
        SpaceMetric::HancomRegenerated
    } else {
        SpaceMetric::Stored
    };
    let mut tokens = try_tokenize_paragraph_with_regenerated_space_metric(
        &text_chars,
        &para.char_offsets,
        &para.char_shapes,
        styles,
        english_break_unit,
        korean_break_unit,
        // 종전 동작 보존: 이 인자가 곧 공백 규칙이었다.
        reflow_space_metric,
        &inline_controls,
        para.control_mask & (1 << 0x18) != 0,
        &para.literal_figure_spaces,
        storage,
    )?;
    apply_resolved_field_tokens_with_storage(para, styles, &inline_controls, &mut tokens, storage)?;
    apply_auto_left_tab_targets(&mut tokens, para_style);
    let prepared_kerning = prepare_paragraph_kerning(
        para,
        &text_chars,
        styles,
        reflow_space_metric,
        &inline_controls,
    )
    .and_then(|prepared| {
        apply_paragraph_kerning_to_tokens(&mut tokens, &prepared.measurement).map(|_| prepared)
    });
    // 저장 LINE_SEG 기반 incremental edit는 앞선 줄을 유지한다. LINE_SEG start가 현재
    // char_offsets와 token 경계 모두에 정확히 대응할 때만 suffix reflow를 허용한다.
    // 그렇지 않으면 (HWPX 합성 boundary, inline control, token 내부 boundary 등) full
    // reflow가 보수적인 경로다.
    let original_line_segs = storage.collect(para.line_segs.iter().cloned())?;
    let token_start_idx = |token: &BreakToken| match token {
        BreakToken::Text { start_idx, .. } => *start_idx,
        BreakToken::DiscretionaryHyphen { idx, .. }
        | BreakToken::Space { idx, .. }
        | BreakToken::Tab { idx, .. }
        | BreakToken::LineBreak { idx } => *idx,
    };
    let mut preserved_prefix = Vec::new();
    let mut reflow_start_idx = 0usize;
    let mut reflow_is_first_line = true;
    let mut token_start = 0usize;
    // `DocumentCore::new_empty()`의 기본 source_format도 Hwp이므로 형식만으로는
    // 합성 test/new-document LineSeg를 native 저장 경계로 오인할 수 없다. 실제 HWP
    // LINE_SEG가 가진 line-height와, 0에서 시작해 엄격히 증가하는 start가 모두
    // 있어야 prefix를 권위 경계로 채택한다. 범위 삭제는 삭제된 여러 줄을 같은
    // start로 접을 수 있으므로 duplicate/역행 경계는 full reflow가 안전하다.
    let has_valid_orig = original_line_segs
        .iter()
        .all(|seg| seg.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0);
    let authoritative_line_seg_prefix = has_valid_orig
        && original_line_segs
            .first()
            .is_some_and(|seg| seg.text_start == 0)
        && original_line_segs
            .windows(2)
            .all(|pair| pair[0].text_start < pair[1].text_start);
    if para.controls.is_empty() && authoritative_line_seg_prefix {
        if let Some(edit_char_offset) = preserve_prefix_for_edit {
            // Delete-at-end는 삭제 뒤 `char_offsets`에 caret 위치가 없지만, 텍스트
            // UTF-16 끝은 정확한 token boundary다. 삭제된 마지막 글자가 있던 줄의
            // 앞줄부터 다시 채워야 5→4 shrink도 표현할 수 있다.
            let edit_is_document_end = edit_char_offset == text_len;
            let edit_utf16 = para
                .char_offsets
                .get(edit_char_offset)
                .copied()
                .or_else(|| edit_is_document_end.then(|| para.text.encode_utf16().count() as u32));
            let affected_line = edit_utf16.and_then(|offset| {
                let line = original_line_segs
                    .iter()
                    .rposition(|seg| seg.text_start <= offset)?;
                if edit_is_document_end && original_line_segs[line].text_start < offset {
                    // 삭제 대상이 들어 있던 마지막 줄도 다시 채워야 직전 줄에
                    // 합쳐질 수 있다. line=0이면 prefix 없이 full reflow한다.
                    line.checked_sub(1)
                } else {
                    Some(line)
                }
            });
            if let Some(affected_line) = affected_line.filter(|line| *line > 0) {
                let reflow_utf16 = original_line_segs[affected_line].text_start;
                let reflow_char_idx = para
                    .char_offsets
                    .iter()
                    .position(|offset| *offset == reflow_utf16);
                let suffix_token_start = reflow_char_idx.and_then(|char_idx| {
                    tokens
                        .iter()
                        .position(|token| token_start_idx(token) == char_idx)
                        .map(|token_idx| (char_idx, token_idx))
                });
                if let Some((char_idx, token_idx)) = suffix_token_start {
                    preserved_prefix =
                        storage.collect(original_line_segs[..affected_line].iter().cloned())?;
                    reflow_start_idx = char_idx;
                    reflow_is_first_line = false;
                    token_start = token_idx;
                }
            }
        }
    }

    let mut kerning_transaction = prepared_kerning
        .as_ref()
        .map(|prepared| prepared.context.layout_session());
    let mut kerning_break_session = prepared_kerning.as_ref().and_then(|prepared| {
        crate::renderer::kerning::KerningParagraphBreakSession::new(
            &para.text,
            &prepared.scalar_styles,
            &prepared.hard_boundaries,
            &prepared.measurement,
            kerning_transaction.as_mut()?,
        )
        .ok()
    });
    let mut line_breaks = try_fill_lines(
        &tokens[token_start..],
        &text_chars,
        available_width_px,
        indent_px,
        TabFill::for_paragraph(para_style, indent_px, available_width_px),
        korean_break_unit,
        condense_min_space,
        &try_resolved_paragraph_letter_spacing(
            para,
            &text_chars,
            styles,
            reflow_space_metric,
            storage,
        )?,
        reflow_start_idx,
        reflow_is_first_line,
        // A split supplies the new cell's physical box, just like Frame fill.
        // The legacy scalar estimate tolerance must not admit a token beyond
        // that box and change the persisted logical row partition.
        !split_stale_cell_reflow,
        kerning_break_session.as_mut(),
        storage,
    )?;
    let kerning_failed = kerning_break_session
        .as_ref()
        .and_then(|session| session.failed_reason())
        .is_some();
    drop(kerning_break_session);
    drop(kerning_transaction);
    if kerning_failed {
        line_breaks = try_fill_lines(
            &tokens[token_start..],
            &text_chars,
            available_width_px,
            indent_px,
            TabFill::for_paragraph(para_style, indent_px, available_width_px),
            korean_break_unit,
            condense_min_space,
            &try_resolved_paragraph_letter_spacing(
                para,
                &text_chars,
                styles,
                reflow_space_metric,
                storage,
            )?,
            reflow_start_idx,
            reflow_is_first_line,
            !split_stale_cell_reflow,
            None,
            storage,
        )?;
    }
    // TAC 표의 호스트를 편집하면 이전 줄 경계는 더 이상 권위가 없다.
    // 표 앞의 실제 텍스트와 표가 남은 폭에 함께 들어가는지 판정하고, 실패하면
    // 표 앵커에서 물리 줄을 발행한다. 배치도 그 줄을 소유 줄로 사용한다 (#7491).
    // 기존 셀 분할 경로와 달리 저장본에서 들여쓰지 않은 본문 표 호스트는 새로
    // 발행할 bit20 기록과 같은 폭을 사용한다 (#6190 편집 후 한컴 PDF).
    let edited_tac_table = supports_tac_table_band_frame_controls(para);
    let table_indent_px = if edited_tac_table
        && reflow_indentation_pattern(para_style, &original_line_segs, seg_width_hwp)
            == (false, false)
    {
        0.0
    } else {
        indent_px
    };
    // 실제 측정한 표 본체와 바깥 여백을 줄 폭과 줄 높이에서 함께 사용한다.
    // 개체 줄은 개체 자신의 원시 위치에서 시작한다. 뒤 글자 위치(`char_offsets`)로
    // 시작하면 저장 줄 경계가 개체 뒤에 놓여 개체가 앞 줄 끝에 남는다.
    let terminal_inline_control = para
        .controls
        .iter()
        .zip(para.try_control_text_positions(storage)?)
        .any(|(control, position)| position == text_len && control.is_treat_as_char_object());
    let occupied_controls: Vec<_> = if split_stale_cell_reflow
        || edited_tac_table
        || terminal_inline_control
        || inline_controls.is_empty()
    {
        para.controls
            .iter()
            .zip(para.control_text_positions())
            .zip(para.control_utf16_positions())
            .filter_map(|((control, position), utf16_start)| {
                let (width, height) = inline_control_occupied_size_hwp(control, styles, dpi)?;
                Some((position, utf16_start, width, height))
            })
            .collect()
    } else {
        Vec::new()
    };
    // 마지막 글자 뒤의 글자처럼 취급 개체는 뒤 글자가 없어 채움 토큰에 폭이 실리지 않는다
    // (`flow_inline_controls`). 채움이 그 앞에서 줄을 나눌 수 없으므로 표와 같은 개체 줄
    // 판정을 받는다. 판정이 없으면 넓은 그림이 앞 글자와 한 줄에 남아 오른쪽 여백을 넘는다.
    let forced_inline_line =
        (split_stale_cell_reflow || edited_tac_table || terminal_inline_control)
            .then(|| {
                inline_control_requires_own_line(
                    para,
                    &occupied_controls,
                    &text_chars,
                    &line_breaks,
                    available_width_px,
                    table_indent_px,
                    reflow_is_first_line,
                    styles,
                    reflow_space_metric,
                )
            })
            .flatten();
    let floating_anchors = floating_anchor_char_font_sizes_with_storage(para, styles, storage)?;
    let preserved_prefix_len = preserved_prefix.len();
    let mut new_line_segs: Vec<LineSeg> = preserved_prefix;
    for (line_idx, lb) in line_breaks.iter().enumerate() {
        storage.reserve(&mut new_line_segs, 3)?;
        let utf16_start = if new_line_segs.is_empty() {
            0 // 첫 번째 줄의 text_start는 항상 0 (문단 시작)
        } else {
            match forced_inline_line {
                Some((position, control_start, ..)) if position == lb.start_idx => control_start,
                _ => line_start_utf16_offset(para, lb.start_idx, &inline_controls),
            }
        };
        let fs = if lb.max_font_size > 0.0 {
            lb.max_font_size
        } else {
            paragraph_font_size_px(para, styles).unwrap_or(12.0)
        };
        // 줄 안에 놓인 비-글자취급 개체의 기준 문자도 그 줄의 글자다.
        let fs = fs.max(floating_anchor_font_size_px(
            &floating_anchors,
            lb.start_idx..lb.end_idx,
            lb.end_idx == text_len,
            text_len,
        ));
        let fs = if line_idx + 1 == line_breaks.len() {
            fs.max(paragraph_end_font_size_px(para, styles))
        } else {
            fs
        };
        let mut text_seg = make_line_seg(utf16_start, fs);
        // A control assigned its own row after this text prefix owns that
        // row's height only. A terminal anchor can also equal text_len; the
        // general last-line ownership rule must not reserve it in both rows.
        let control_after_text = forced_inline_line.is_some_and(|(position, ..)| {
            position > lb.start_idx
                && (position < lb.end_idx
                    || (position == lb.end_idx && line_idx + 1 == line_breaks.len()))
        });
        if forced_inline_line.is_some_and(|(position, ..)| position == lb.start_idx) {
            let (_, _, height_hwp, _) = forced_inline_line.expect("checked inline control");
            apply_inline_control_line_height(&mut text_seg, height_hwp);
        }
        if let Some(control) = inline_controls
            .iter()
            .filter(|control| {
                inline_control_flow::owns_line(control, lb, text_len)
                    && !(control_after_text
                        && forced_inline_line
                            .is_some_and(|(position, ..)| position == control.char_position))
            })
            // 별도 줄로 분리된 개체 높이는 앞 텍스트 줄에 중복 계상하지 않는다.
            .filter(|control| {
                !forced_inline_line.is_some_and(|(position, start, ..)| {
                    position > lb.start_idx && start == control.utf16_position
                })
            })
            .max_by_key(|control| (control.height_hwp, control.baseline_distance_hwp))
        {
            let inline_owns_row_height = control.height_hwp > text_seg.line_height;
            apply_inline_control_line_height(&mut text_seg, control.height_hwp);
            if inline_owns_row_height {
                if let Some(baseline) = control.baseline_distance_hwp {
                    text_seg.baseline_distance = baseline;
                }
                // 프레임 채움과 같이 줄 간격에 참여하는 개체(덧말 등)는 그 높이로 간격을 잰다.
                if let Some(height) = control.spacing_height_hwp {
                    text_seg.line_spacing = compute_line_spacing_hwp(
                        ls_type,
                        ls_value,
                        text_seg.line_height.max(height),
                        dpi,
                    );
                }
            }
        }
        new_line_segs.push(text_seg);

        // control이 text line 한가운데/끝에 있으면 먼저 text prefix를 확정하고,
        // control offset에서 다음 LineSeg를 삽입한다. 단순히 vector 끝에 붙이면
        // 중간 nested table 뒤의 text가 control보다 앞에서 그려진다.
        if control_after_text {
            let (_, control_start, height_hwp, _) =
                forced_inline_line.expect("checked inline control");
            let mut control_seg = make_line_seg(control_start, fs);
            apply_inline_control_line_height(&mut control_seg, height_hwp);
            new_line_segs.push(control_seg);
        }
        if let Some((position, _, _, true)) = forced_inline_line
            .filter(|(position, ..)| control_after_text || *position == lb.start_idx)
        {
            new_line_segs.push(make_line_seg(
                char_index_to_utf16_offset(para, position),
                fs,
            ));
        }
    }

    if new_line_segs.is_empty() {
        storage.reserve(&mut new_line_segs, 1)?;
        new_line_segs.push(make_line_seg(
            0,
            paragraph_font_size_px(para, styles).unwrap_or(12.0),
        ));
    }

    if forced_inline_line.is_none() && inline_controls.is_empty() {
        for &(position, _, _, height_hwp) in &occupied_controls {
            // 명시적 개행으로 정해진 개체 줄에 높이를 싣는다. 최초 줄에 일괄
            // 적용하면 표 앞 제목이 표 줄로 오인되어 표 뒤로 재배치된다.
            let line_index = line_breaks
                .iter()
                .rposition(|line| line.start_idx <= position)
                .unwrap_or(0);
            if let Some(seg) = new_line_segs.get_mut(preserved_prefix_len + line_index) {
                apply_inline_control_line_height(seg, height_hwp);
            }
        }
    }

    if split_stale_cell_reflow {
        apply_reflowed_equation_row_metrics(
            para,
            &mut new_line_segs,
            styles,
            ls_type,
            ls_value,
            dpi,
        );
    }

    // vertical_pos 누적 계산 (각 줄의 문단 내 Y 오프셋)
    // 원본 첫 LineSeg의 vertical_pos를 보존하여 vpos 체계 연속성 유지
    // (layout.rs의 vpos 보정이 문단 간 vpos 연속성을 가정하므로)
    let mut vpos = if preserved_prefix_len > 0 {
        let last = &new_line_segs[preserved_prefix_len - 1];
        last.vertical_pos
            .saturating_add(last.line_height)
            .saturating_add(last.line_spacing)
    } else {
        orig.as_ref().map(|ls| ls.vertical_pos).unwrap_or(0)
    };
    for i in preserved_prefix_len..new_line_segs.len() {
        new_line_segs[i].vertical_pos = vpos;
        vpos += new_line_segs[i].line_height + new_line_segs[i].line_spacing;
    }
    mark_indented_lines(
        &mut new_line_segs[preserved_prefix_len..],
        preserved_prefix_len,
        para_style,
        &original_line_segs,
        seg_width_hwp,
    );

    let space_metrics =
        storage.collect(new_line_segs.iter().enumerate().map(|(index, line)| {
            let rule = if index < preserved_prefix_len {
                para.line_space_metric(index)
            } else {
                reflow_space_metric
            };
            (line.text_start, rule)
        }))?;
    para.replace_line_segs_with_space_metrics(new_line_segs, space_metrics);
    Ok(preserved_prefix_len > 0)
}

/// 구역 내 문단들의 vertical_pos를 순차적으로 재계산한다.
///
/// `start_para`부터 구역 끝까지 각 문단의 vpos를 이전 문단의 vpos_end 기준으로 재계산.
/// 표 등 특수 문단의 line_height는 보존하고 vpos만 갱신한다.
///
/// [Task #2299] 저장 vpos 리셋(단/쪽 경계 인코딩) 보존: 편집발 재계산이 구역 전체를
/// 선형 누적 좌표로 이어붙이면 다단 zone 의 단-상대 리셋(급감)이 소멸해
/// typeset(#321/#470/#702)·pagination 의 단/쪽 진행 신호가 무력화된다
/// (shortcut.hwp 앞문단 편집 시 col=[0,1]→[0], 7→9쪽). 현재 문단의 저장 first 가
/// 직전 문단의 "이동 전(저장)" end 보다 감소하면 경계 인코딩으로 보고 delta=0 으로
/// 보존한다. 저장 좌표는 밴드 내 정상 흐름에서 단조 증가하므로 감소 감지에 임계가
/// 필요 없다.
///
/// 좌표 갱신은 경계 성격별로 셋으로 나뉜다.
///
/// - **리셋 경계**: delta=0 보존.
/// - **변조 인접 경계**(현재 문단이 편집 대상 `start_para` 이거나 신규
///   문단(`ignore_reset_range`)이거나, 직전 문단이 그중 하나): 직전 이동 후 end 에
///   문단 여백 gap(spacing_after + spacing_before, 셀 recalc `boundary_gaps` 동일
///   산식)을 더해 다시 잇는다. reflow/신규 생성으로 저장 gap 이 소실된 경계라
///   스타일에서 재유도한다. gap 없는 abutment 는 문단 간격을 압축해 near-top
///   리셋(#1086/#1921)의 `prev_vpos_end > 60000` 임계를 무너뜨렸다
///   (SO-SUEOP.hwpx 46→44).
///   단, 편집 문단(`start_para`)에서 이어진 변조 구간 **바로 뒤의 원본 문단**은
///   저장 gap 이 살아 있다 — 그 문단의 저장 first 와 편집 전 저장 end
///   (`start_stored_end`)의 차가 스타일 gap 보다 크고 그 문단이 문단 기준 자리차지
///   개체(비-TAC, 위아래 배치 표·그림·도형)를 소유하면, 초과분은 그 개체가 첫 글줄을
///   민 점유 높이다. 그런 개체가 없는 문단의 초과분(TAC 호스트 th 관례, 편집 합성 줄
///   따위)은 점유가 아니므로 종전대로 버린다. 글자 편집은 이 점유를 바꾸지
///   않으므로 초과분을 보존해 잇는다(#8440 — 버리면 다음 표가 앞 표와 겹친다).
///   초과분이 없거나 음수면 종전대로 스타일 gap 만 쓴다.
/// - **미변조 연속 경계**: 직전 문단의 delta 를 그대로 캐리해 저장(또는 로드 합성
///   #927) 문단 간격을 정확히 보존한다. 스타일 gap 재유도는 저장 gap 과의
///   오차(px 왕복 절삭 ±1HU, 스타일-저장 불일치)를 밴드 전체에 누적시키고 로드
///   합성 gap-less 체인과도 어긋나므로 쓰지 않는다. delta==0 이면 순수 no-op.
///
/// 리셋 감지는 저장 좌표끼리의 비교여야 한다. 직전 문단이 변조 대상이면 그 end 는
/// 저장 좌표가 아니므로(성장 편집이 다음 문단을 가짜 리셋으로 동결시키고,
/// placeholder 는 기준을 붕괴시킨다) reflow 가 보존하는 **first** 로 비교한다.
/// 미변조 경계는 end 기준을 유지한다(연속 0-first 밴드 감지에 필요).
///
/// placeholder 저지선 2종: ① split/insert/paste 가 방금 만든 신규 문단의 vpos=0 은
/// 경계 인코딩이 아니다 — 보존하면 문단마다 가짜 쪽나눔이 생긴다
/// (test_page_boundary_with_incremental_spacing_increase 핀). 호출자가 신규 구간을
/// `ignore_reset_range` 로 지정하면 보존 없이 흐름에 연결한다(셀 경로
/// `recalculate_cell_paragraph_vpos` 의 ignore_reset_at 과 동일 취지, 다중 삽입을
/// 위해 범위형). ② lineseg 부재였다가 on-demand reflow(#177/#927)로 합성된
/// seg(TAG_IMPLEMENTATION_PROPERTY, #1811)도 보존하지 않는다.
///
/// 줄 전진량은 로드 경로(document.rs 의 vpos 체인)와 동일하게 TAC 호스트
/// 줄(lh>th)을 th 기준으로 센다 — lh 기준이면 인라인 개체 호스트의 end 가 저장
/// 후속 first 를 넘어서 가짜 리셋을 만든다.
pub(crate) fn recalculate_section_vpos(
    paragraphs: &mut [Paragraph],
    start_para: usize,
    ignore_reset_range: Option<std::ops::Range<usize>>,
    start_stored_end: Option<i32>,
    styles: &ResolvedStyleSet,
    dpi: f64,
    is_hwp3_variant: bool,
) {
    if paragraphs.is_empty() || start_para >= paragraphs.len() {
        return;
    }

    // 문단 경계 gap (HWPUNIT) = 앞 문단 spacing_after + 뒤 문단 spacing_before.
    // recalculate_cell_paragraph_vpos 의 boundary_gaps 와 동일 산식.
    let boundary_gap = |prev: &Paragraph, curr: &Paragraph| -> i32 {
        let spacing_after = styles
            .para_styles
            .get(prev.para_shape_id as usize)
            .map(|style| style.spacing_after)
            .unwrap_or(0.0);
        let spacing_before = styles
            .para_styles
            .get(curr.para_shape_id as usize)
            .map(|style| style.spacing_before)
            .unwrap_or(0.0);
        let spacing_before =
            crate::renderer::hwp3_variant_flow_spacing_before(spacing_before, is_hwp3_variant);
        px_to_hwpunit(spacing_after + spacing_before, dpi)
    };

    // 줄 전진량 — 로드 경로와 동일한 TAC th-관례. saturating: 조작 파일의 극단
    // spacing/좌표로 i32 가 넘치지 않게 한다 (release wasm 은 overflow-check 가
    // 없어 무음 랩 → 전 문단 오판으로 이어진다).
    let seg_advance = |ls: &LineSeg| -> i32 {
        let height = if ls.line_height > ls.text_height && ls.text_height > 0 {
            ls.text_height
        } else {
            ls.line_height
        };
        height.saturating_add(ls.line_spacing)
    };
    let seg_end = |p: &Paragraph| -> Option<i32> {
        p.line_segs
            .last()
            .map(|ls| ls.vertical_pos.saturating_add(seg_advance(ls)))
    };
    let is_ignored = |pi: usize| {
        ignore_reset_range
            .as_ref()
            .is_some_and(|range| range.contains(&pi))
    };

    // 직전 문단(마지막 비어있지 않은 lineseg 보유 문단) 인덱스.
    // start_para 이전 문단들은 이 호출에서 이동하지 않으므로 현재 좌표가 곧 저장 좌표다.
    let mut prev_idx: Option<usize> = paragraphs[..start_para]
        .iter()
        .rposition(|p| !p.line_segs.is_empty());
    let mut next_vpos = match prev_idx {
        Some(pp) => seg_end(&paragraphs[pp]).unwrap_or(0),
        // 첫 문단: 기존 vpos 유지
        None => paragraphs[start_para]
            .line_segs
            .first()
            .map(|ls| ls.vertical_pos)
            .unwrap_or(0),
    };
    // 리셋 감지 기준 — 직전 문단의 "이동 전(저장)" first/end.
    let mut orig_prev_first: Option<i32> = prev_idx
        .and_then(|pp| paragraphs[pp].line_segs.first())
        .map(|ls| ls.vertical_pos);
    let mut orig_prev_end: Option<i32> = prev_idx.and_then(|pp| seg_end(&paragraphs[pp]));
    // 직전 문단이 이번 편집의 변조 대상이었는가 + 직전 문단에 적용된 delta.
    let mut prev_modified = false;
    let mut prev_delta: i32 = 0;
    // 직전 줄 보유 문단과 현재 문단 사이에 저장 줄이 없는 문단이 있었는가.
    let mut skipped_unlined = false;
    // start_para 에서 이어지는 변조 구간 안인가 — 구간 뒤 첫 원본 문단에서 false 가 된다.
    let mut in_start_run = true;
    // 저장 first 가 앞 문단 end + 스타일 gap 을 넘는 정당한 출처: 그 문단이 소유한
    // 문단 기준 자리차지 개체(비-TAC, 위아래)가 첫 글줄을 개체 아래로 민 경우다.
    // 다른 문단의 초과분(TAC 호스트 th 관례, 편집 합성 줄 따위)은 점유가 아니다.
    let hosts_para_topbottom_object = |p: &Paragraph| {
        p.controls.iter().any(|control| {
            let common = match control {
                Control::Table(table) => &table.common,
                Control::Picture(picture) => &picture.common,
                Control::Shape(shape) => shape.common(),
                Control::Equation(equation) => &equation.common,
                _ => return false,
            };
            crate::renderer::float_placement::is_para_topbottom_float(common)
        })
    };

    for pi in start_para..paragraphs.len() {
        if paragraphs[pi].line_segs.is_empty() {
            skipped_unlined = true;
            continue;
        }

        let para_modified = pi == start_para || is_ignored(pi);
        let current_start = paragraphs[pi].line_segs[0].vertical_pos;
        let is_original_lineseg =
            paragraphs[pi].line_segs[0].tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY == 0;

        // 리셋 감지: 신규 문단(placeholder)·합성 seg 는 제외. 기준은 직전 문단의
        // "저장" 좌표여야 한다 — 직전이 편집 문단(start_para)이면 reflow 로 end 가
        // 이미 변조됐으므로 호출자가 캡처해 준 reflow 이전 저장 end 를 쓰고(성장
        // 편집의 가짜 리셋과 저장-겹침 문서의 정당한 리셋을 모두 정확히 판별),
        // 없으면 reflow 가 보존하는 first 로 보수적으로 비교한다. 신규 문단이
        // 직전이면 placeholder 라 first(=0) 기준. 미변조 경계는 end 기준을
        // 유지한다(연속 0-first 밴드 감지에 필요).
        let prev_stored_bound = if prev_idx == Some(start_para) && !is_ignored(start_para) {
            start_stored_end.or(orig_prev_first)
        } else if prev_modified {
            orig_prev_first
        } else {
            orig_prev_end
        };
        let is_reset = is_original_lineseg
            && !is_ignored(pi)
            && prev_stored_bound.is_some_and(|bound| current_start < bound);

        let delta = if is_reset {
            // 단/쪽 리셋 경계 — 저장 좌표 유지.
            0
        } else if skipped_unlined && !para_modified {
            // 저장 줄 없는 문단의 높이는 조판이 그때 정하고, 그 자리는 이 문단의 저장
            // 좌표에만 남아 있다. 앞 문단 end 의 이동만 옮겨 그 간격을 지킨다.
            let stored_prev_end = if prev_idx == Some(start_para) && !is_ignored(start_para) {
                start_stored_end.or(orig_prev_end)
            } else {
                orig_prev_end
            };
            stored_prev_end.map_or(0, |end| next_vpos - end)
        } else if para_modified || prev_modified {
            // 변조 인접 경계 — 이동 후 흐름에 스타일 여백 gap 으로 다시 잇는다.
            let gap = prev_idx
                .map(|pp| boundary_gap(&paragraphs[pp], &paragraphs[pi]))
                .unwrap_or(0);
            // [#8440] 변조 구간 바로 뒤 원본 문단: 편집 전 저장 경계에서 스타일 gap 을
            // 넘는 점유(자리차지 개체 높이)를 보존한다.
            let occupied = match start_stored_end {
                Some(stored_end)
                    if !para_modified
                        && in_start_run
                        && is_original_lineseg
                        && !is_ignored(start_para)
                        && hosts_para_topbottom_object(&paragraphs[pi]) =>
                {
                    let stored_gap = boundary_gap(&paragraphs[start_para], &paragraphs[pi]);
                    current_start
                        .saturating_sub(stored_end)
                        .saturating_sub(stored_gap)
                        .max(0)
                }
                _ => 0,
            };
            next_vpos.saturating_add(gap).saturating_add(occupied) - current_start
        } else {
            // 미변조 연속 경계 — 직전 delta 캐리로 기존 간격을 정확히 보존.
            prev_delta
        };

        // 다음 문단의 리셋 감지 기준은 "이동 전(저장)" first/end 로 기록한다.
        let orig_first = current_start;
        let orig_end = seg_end(&paragraphs[pi]);

        if delta != 0 {
            // 모든 LineSeg의 vpos를 delta만큼 이동
            for seg in &mut paragraphs[pi].line_segs {
                seg.vertical_pos = seg.vertical_pos.saturating_add(delta);
            }
        }

        // 다음 문단의 시작 vpos 계산 (이동 후 end = 저장 end + delta)
        if let Some(end) = orig_end {
            next_vpos = end.saturating_add(delta);
        }
        orig_prev_first = Some(orig_first);
        orig_prev_end = orig_end;
        prev_modified = para_modified;
        prev_delta = delta;
        prev_idx = Some(pi);
        skipped_unlined = false;
        if !para_modified {
            in_start_run = false;
        }
    }
}

/// [Task #2299] 문단의 흐름 end (마지막 LineSeg 의 vpos + 전진량, TAC th-관례).
/// 편집 호출자가 reflow 이전에 캡처해 `recalculate_section_vpos` 의
/// `start_stored_end` 로 전달하기 위한 헬퍼 — reflow 가 end 를 덮은 뒤에는 저장
/// 좌표를 복원할 수 없다.
pub(crate) fn paragraph_flow_end(para: &Paragraph) -> Option<i32> {
    para.line_segs.last().map(|ls| {
        let height = if ls.line_height > ls.text_height && ls.text_height > 0 {
            ls.text_height
        } else {
            ls.line_height
        };
        ls.vertical_pos
            .saturating_add(height.saturating_add(ls.line_spacing))
    })
}

/// font_size(px)를 LineSeg의 line_height(HWPUNIT)로 변환한다.
/// HWP의 LineSeg.line_height = 폰트 크기 (HWPUNIT).
/// 실증 데이터: 10pt → lh=1000, 12pt → lh=1200, 25pt → lh=2500
fn font_size_to_line_height(font_size_px: f64, dpi: f64) -> i32 {
    // Round, don't truncate. `px_to_hwpunit` is `(px * 7200 / dpi) as i32`,
    // which floors toward zero, and the px it is handed came from a HWPUNIT
    // font size in the first place — so the round trip loses a unit whenever
    // the division is inexact. Measured over 1,133,228 admitted rows, that
    // truncation is 5,012 of the 5,215 `line_height` disagreements against
    // HWP's stored records, every one of them exactly -1.
    round_px_to_hwpunit(font_size_px, dpi)
}

/// `px_to_hwpunit` with round-half-away-from-zero instead of truncation.
fn round_px_to_hwpunit(px: f64, dpi: f64) -> i32 {
    (px * 7_200.0 / dpi).round() as i32
}

/// ParaPr의 줄간격 설정으로부터 LineSeg.line_spacing(HWPUNIT)을 계산한다.
///
/// line_spacing = 현재 줄 하단 → 다음 줄 상단 사이의 추가 간격.
/// Y advance = line_height + line_spacing.
fn compute_line_spacing_hwp(
    ls_type: LineSpacingType,
    ls_value: f64,
    line_height_hwp: i32,
    dpi: f64,
) -> i32 {
    match ls_type {
        LineSpacingType::Percent => {
            // ls_value = 비율값 (예: 160 = 160%)
            // 전체 줄 피치 = line_height * percent / 100
            // line_spacing = 전체 줄 피치 - line_height
            // [#2279] sub-100% 퍼센트는 음수 gap(압축)으로 존중 — 한글은
            // line=60% 를 advance 13.6px(=lh×0.6)로 렌더한다 (36398700 pi20
            // 한글 재저장 anchor 1020HU 실측). 종전 .max(0) 클램프는 fresh
            // 합성을 lh 그대로(+9px/문단) 팽창시켰다.
            // **0% 는 한컴이 실제로 쓰는 값이다.** `secPr`·`colPr`·`pageNum`
            // 만 든 구역정의 첫 문단에 `PERCENT 0` 을 주어 advance 0(높이 없음)으로 만든다.
            // 한글 저장본도 `spacing = -vertsize` 로 같은 값을 적는다(실측 26/26 일치,
            // 본 문서 paraPr 43: vertsize 1500 · spacing −1500 · 다음 문단 vertpos 0).
            // 종전 `> 0.0` 가드가 이를 결손으로 보고 0 으로 깎아 **재조판 시 본문이 20px
            // 내려갔다**(원본 130.8 ↔ 재조판 150.8px, 변형 4종으로 잔차 0.000 확인).
            // 결손 판정은 음수로 좁힌다 — 미지정 0 은 파서에서 160% 로 채운다.
            if ls_value >= 0.0 {
                // 한컴은 퍼센트 줄간격을 **4 HWPUNIT 배수로** 반올림한다(half away from zero).
                // 165%×1400 → 910 이 아니라 912, 145%×600 → 272, 145%×500 → 224.
                // 코퍼스 101,321줄(개체 없는 문단): 현재식 75.2% ↔ 4배수 스냅 98.9% 일치.
                // 160·140·130·100·200% 는 원래 4 배수라 무변화 — 바뀌는 것은 145·165·105·110·115% 계열뿐.
                let raw = line_height_hwp as f64 * (ls_value - 100.0) / 100.0;
                ((raw.abs() / 4.0 + 0.5).floor() * 4.0 * raw.signum()) as i32
            } else {
                0
            }
        }
        LineSpacingType::Fixed => {
            // ls_value = 고정 줄 피치 (px, resolver가 HWPUNIT→px 변환 완료)
            // line_spacing = 고정값 - line_height
            let fixed_hwp = round_px_to_hwpunit(ls_value, dpi);
            (fixed_hwp - line_height_hwp).max(0)
        }
        LineSpacingType::SpaceOnly => {
            // ls_value = 줄 사이 추가 간격만 (px)
            round_px_to_hwpunit(ls_value, dpi)
        }
        LineSpacingType::Minimum => {
            // 최소값: 콘텐츠가 최소값보다 크면 추가 간격 없음
            let min_hwp = round_px_to_hwpunit(ls_value, dpi);
            (min_hwp - line_height_hwp).max(0)
        }
    }
}

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

    fn collect_one_interval_at_a_time(
        tokens: &[BreakToken],
        text_chars: &[char],
        available_width_px: f64,
        indent_px: f64,
        default_tab_width: f64,
        korean_break_unit: u8,
        condense_min_space: u8,
        initial_start_idx: usize,
        initial_is_first_line: bool,
    ) -> Vec<LineBreakResult> {
        let mut cursor = FillCursor::new(initial_start_idx, initial_is_first_line);
        let mut results = Vec::new();
        while let Some(result) = fill_one_interval(
            tokens,
            text_chars,
            available_width_px,
            indent_px,
            TabFill::default_only(default_tab_width),
            korean_break_unit,
            condense_min_space,
            &[],
            &mut cursor,
            None,
        ) {
            results.push(result.line);
        }
        results
    }

    fn assert_cursor_matches_frozen_scalar(
        tokens: &[BreakToken],
        text_chars: &[char],
        available_width_px: f64,
        indent_px: f64,
        default_tab_width: f64,
        korean_break_unit: u8,
        condense_min_space: u8,
        initial_start_idx: usize,
        initial_is_first_line: bool,
    ) -> Vec<LineBreakResult> {
        let frozen = fill_lines_before_cursor(
            tokens,
            text_chars,
            available_width_px,
            indent_px,
            default_tab_width,
            korean_break_unit,
            condense_min_space,
            initial_start_idx,
            initial_is_first_line,
        );
        let scalar = fill_lines(
            tokens,
            text_chars,
            available_width_px,
            indent_px,
            TabFill::default_only(default_tab_width),
            korean_break_unit,
            condense_min_space,
            &[],
            initial_start_idx,
            initial_is_first_line,
            true,
            None,
        );
        let resumed = collect_one_interval_at_a_time(
            tokens,
            text_chars,
            available_width_px,
            indent_px,
            default_tab_width,
            korean_break_unit,
            condense_min_space,
            initial_start_idx,
            initial_is_first_line,
        );

        assert_eq!(scalar, frozen);
        assert_eq!(resumed, frozen);
        frozen
    }

    fn assert_overflowing_object_space_moves_with_its_visible_object() {
        let chars = ['a', ' ', 'b'];
        let text = |start_idx, end_idx| BreakToken::Text {
            start_idx,
            end_idx,
            base_width: 10.0,
            width: 10.0,
            max_font_size: 12.0,
            base_char_widths: vec![10.0],
            char_widths: vec![10.0],
        };
        let tokens = [
            text(0, 1),
            BreakToken::Space {
                idx: 1,
                width: 20.0,
                condense_base: 20.0,
                max_font_size: 12.0,
                inline_width: 20.0,
            },
            text(2, 3),
        ];
        let lines = collect_one_interval_at_a_time(&tokens, &chars, 25.0, 0.0, 48.0, 0, 0, 0, true);
        assert_eq!(
            lines
                .iter()
                .map(|l| (l.start_idx, l.end_idx))
                .collect::<Vec<_>>(),
            vec![(0, 1), (1, 2), (2, 3)]
        );

        // [#7840] 반례: 개체(12)는 상자(25)에 들고 넘치는 것은 뒤 공백(8)뿐이다. 공백은
        // 줄 끝에 걸고 개체는 이 줄에 남는다.
        let tokens = [
            text(0, 1),
            BreakToken::Space {
                idx: 1,
                width: 20.0,
                condense_base: 8.0,
                max_font_size: 12.0,
                inline_width: 12.0,
            },
            text(2, 3),
        ];
        let lines = collect_one_interval_at_a_time(&tokens, &chars, 25.0, 0.0, 48.0, 0, 0, 0, true);
        assert_eq!(
            lines
                .iter()
                .map(|l| (l.start_idx, l.end_idx))
                .collect::<Vec<_>>(),
            vec![(0, 2), (2, 3)]
        );
    }

    #[test]
    fn cursor_resumes_a_long_text_token_at_each_interval() {
        let text_chars = "abcdefghij".chars().collect::<Vec<_>>();
        let tokens = vec![BreakToken::Text {
            start_idx: 0,
            end_idx: text_chars.len(),
            base_width: 100.0,
            width: 100.0,
            max_font_size: 12.0,
            base_char_widths: vec![10.0; text_chars.len()],
            char_widths: vec![10.0; text_chars.len()],
        }];

        let results = assert_cursor_matches_frozen_scalar(
            &tokens,
            &text_chars,
            25.0,
            0.0,
            48.0,
            0,
            0,
            0,
            true,
        );

        assert_eq!(
            results
                .iter()
                .map(|result| (result.start_idx, result.end_idx, result.has_line_break))
                .collect::<Vec<_>>(),
            vec![
                (0, 2, false),
                (2, 4, false),
                (4, 6, false),
                (6, 8, false),
                (8, 10, false),
            ]
        );
    }

    #[test]
    fn cursor_preserves_scalar_space_tab_and_forced_break_results() {
        // Exercise both ownership cases in the existing space-boundary contract:
        // an overflowing blank can hang, but a visible inline object cannot.
        assert_overflowing_object_space_moves_with_its_visible_object();
        let text_chars = "ab c\td\nxy".chars().collect::<Vec<_>>();
        let tokens = vec![
            BreakToken::Text {
                start_idx: 0,
                end_idx: 2,
                base_width: 20.0,
                width: 20.0,
                max_font_size: 12.0,
                base_char_widths: vec![10.0, 10.0],
                char_widths: vec![10.0, 10.0],
            },
            BreakToken::Space {
                idx: 2,
                width: 5.0,
                condense_base: 5.0,
                max_font_size: 12.0,
                inline_width: 0.0,
            },
            BreakToken::Text {
                start_idx: 3,
                end_idx: 4,
                base_width: 10.0,
                width: 10.0,
                max_font_size: 12.0,
                base_char_widths: vec![10.0],
                char_widths: vec![10.0],
            },
            BreakToken::Tab {
                idx: 4,
                max_font_size: 12.0,
                auto_left_target: None,
            },
            BreakToken::Text {
                start_idx: 5,
                end_idx: 6,
                base_width: 10.0,
                width: 10.0,
                max_font_size: 12.0,
                base_char_widths: vec![10.0],
                char_widths: vec![10.0],
            },
            BreakToken::LineBreak { idx: 6 },
            BreakToken::Text {
                start_idx: 7,
                end_idx: 9,
                base_width: 20.0,
                width: 20.0,
                max_font_size: 12.0,
                base_char_widths: vec![10.0, 10.0],
                char_widths: vec![10.0, 10.0],
            },
        ];

        let actual =
            collect_one_interval_at_a_time(&tokens, &text_chars, 24.0, 0.0, 48.0, 0, 0, 0, true);
        assert_eq!(
            actual
                .iter()
                .map(|l| (l.start_idx, l.end_idx, l.has_line_break))
                .collect::<Vec<_>>(),
            vec![
                (0, 3, false),
                (3, 4, false),
                (4, 5, false),
                (5, 7, true),
                (7, 9, false)
            ]
        );
        let before = fill_lines_before_cursor(&tokens, &text_chars, 24.0, 0.0, 48.0, 0, 0, 0, true);
        assert_ne!(
            actual, before,
            "the frozen filler deferred the overflowing space"
        );
    }
}

#[cfg(test)]
mod frame_reflow_tests {
    use super::*;
    use crate::renderer::layout_frame::{FrameExclusion, FrameExclusionPolicy};
    use crate::renderer::style_resolver::{ResolvedCharStyle, ResolvedParaStyle};

    fn styles(font_sizes: &[f64]) -> ResolvedStyleSet {
        ResolvedStyleSet {
            char_styles: font_sizes
                .iter()
                .map(|font_size| ResolvedCharStyle {
                    font_size: *font_size,
                    ratio: 1.0,
                    ..Default::default()
                })
                .collect(),
            para_styles: vec![ResolvedParaStyle::default()],
            ..Default::default()
        }
    }

    fn paragraph(text: &str, char_shapes: Vec<CharShapeRef>) -> Paragraph {
        Paragraph {
            text: text.to_string(),
            char_offsets: text
                .chars()
                .scan(0u32, |offset, character| {
                    let current = *offset;
                    *offset += character.len_utf16() as u32;
                    Some(current)
                })
                .collect(),
            char_count: text.encode_utf16().count() as u32 + 1,
            char_shapes,
            ..Default::default()
        }
    }

    fn shared_metrics(lines: &[LineSeg]) -> Vec<(i32, i32, i32, i32, i32)> {
        lines
            .iter()
            .map(|line| {
                (
                    line.vertical_pos,
                    line.line_height,
                    line.text_height,
                    line.baseline_distance,
                    line.line_spacing,
                )
            })
            .collect()
    }

    fn line_fields(lines: &[LineSeg]) -> Vec<(u32, i32, i32, i32, i32, i32, i32, i32, u32)> {
        lines
            .iter()
            .map(|line| {
                (
                    line.text_start,
                    line.vertical_pos,
                    line.line_height,
                    line.text_height,
                    line.baseline_distance,
                    line.line_spacing,
                    line.column_start,
                    line.segment_width,
                    line.tag,
                )
            })
            .collect()
    }

    fn frozen_scalar_projection(
        para: &Paragraph,
        available_width_px: f64,
        styles: &ResolvedStyleSet,
        dpi: f64,
    ) -> Vec<LineSeg> {
        let text_chars = para.text.chars().collect::<Vec<_>>();
        let style = styles.para_styles.get(para.para_shape_id as usize);
        let indent_px = style.map(|value| value.indent).unwrap_or(0.0);
        let english_break_unit = style.map(|value| value.english_break_unit).unwrap_or(0);
        let korean_break_unit = style.map(|value| value.korean_break_unit).unwrap_or(0);
        let condense_min_space = style.map(|value| value.condense_min_space).unwrap_or(0);
        let default_tab_width = style.map(|value| value.default_tab_width).unwrap_or(0.0);
        let line_spacing_type = style
            .map(|value| value.line_spacing_type)
            .unwrap_or(LineSpacingType::Percent);
        let line_spacing_value = style.map(|value| value.line_spacing).unwrap_or(160.0);
        let tokens = tokenize_paragraph_with_regenerated_space_metric(
            &text_chars,
            &para.char_offsets,
            &para.char_shapes,
            styles,
            english_break_unit,
            korean_break_unit,
            SpaceMetric::Stored,
            &[],
            para.control_mask & (1 << 0x18) != 0,
            &para.literal_figure_spaces,
        );
        let line_breaks = fill_lines_before_cursor(
            &tokens,
            &text_chars,
            available_width_px,
            indent_px,
            default_tab_width,
            korean_break_unit,
            condense_min_space,
            0,
            true,
        );
        let segment_width = px_to_hwpunit(available_width_px, dpi);
        let source_tag = para
            .line_segs
            .first()
            .map(|line| line.tag)
            .unwrap_or(LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY);
        let mut vertical_pos = para
            .line_segs
            .first()
            .map(|line| line.vertical_pos)
            .unwrap_or(0);

        line_breaks
            .iter()
            .enumerate()
            .map(|(index, line)| {
                let font_size = if line.max_font_size > 0.0 {
                    line.max_font_size
                } else {
                    12.0
                };
                let line_height = font_size_to_line_height(font_size, dpi);
                let line_spacing = compute_line_spacing_hwp(
                    line_spacing_type,
                    line_spacing_value,
                    line_height,
                    dpi,
                );
                let projected = LineSeg {
                    text_start: if index == 0 {
                        0
                    } else {
                        char_index_to_utf16_offset(para, line.start_idx)
                    },
                    vertical_pos,
                    line_height,
                    text_height: line_height,
                    baseline_distance: baseline_distance_hwp(line_height),
                    line_spacing,
                    column_start: 0,
                    segment_width,
                    tag: if source_tag == 0 {
                        LineSeg::TAG_SINGLE_SEGMENT_LINE
                    } else {
                        source_tag
                    },
                };
                vertical_pos += line_height + line_spacing;
                projected
            })
            .collect()
    }

    #[test]
    fn frame_reflow_projects_two_intervals_as_one_physical_row() {
        let styles = styles(&[12.0]);
        let para = paragraph(
            "abcdef ghijkl",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        let mut frame = LayoutFrame::new(
            0..9_000,
            100,
            vec![FrameExclusion {
                horizontal: 3_000..5_000,
                vertical: 0..10_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        let lines = layout_paragraph_in_frame(&para, &mut frame, &styles, 96.0)
            .expect("two usable intervals accept scalar text");

        assert_eq!(lines.len(), 2);
        assert_eq!(
            lines.iter().map(|line| line.text_start).collect::<Vec<_>>(),
            vec![0, 7]
        );
        assert_eq!(
            lines
                .iter()
                .map(|line| (line.column_start, line.segment_width))
                .collect::<Vec<_>>(),
            vec![(0, 3_000), (5_000, 4_000)]
        );
        assert_eq!(shared_metrics(&lines), vec![(100, 900, 900, 765, 540); 2]);
        assert!(lines[0].is_first_segment());
        assert!(!lines[0].is_last_segment());
        assert!(!lines[1].is_first_segment());
        assert!(lines[1].is_last_segment());
        assert_eq!(frame.row_count(), 1);
        assert_eq!(frame.top, 1_540);
    }

    #[test]
    fn frame_reflow_retries_a_taller_row_without_consuming_the_cursor() {
        a_frame_that_expects_the_stored_rows_admits_them_and_skips_the_reflow();
        width_neutrality_is_a_property_of_geometry_not_a_list_of_variants();
        body_stored_route_admits_only_width_neutral_structural_controls();
        hwp3_formatting_rebuild_preserves_legacy_stored_geometry_jurisdiction();
        frame_rejected_rows_reflow_without_propagating_cached_source_flags();
        picture_band_frame_fill_inherits_provenance_not_cached_row_state();
        let styles = styles(&[12.0, 20.0]);
        let para = paragraph(
            "abcdef ghijk",
            vec![
                CharShapeRef {
                    start_pos: 0,
                    char_shape_id: 0,
                },
                CharShapeRef {
                    start_pos: 7,
                    char_shape_id: 1,
                },
            ],
        );
        let mut frame = LayoutFrame::new(
            0..9_000,
            0,
            vec![FrameExclusion {
                horizontal: 4_000..5_000,
                vertical: 1_000..5_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        let lines = layout_paragraph_in_frame(&para, &mut frame, &styles, 96.0)
            .expect("the taller retry restores the first interval's cursor");

        // The 12px trial has one full-width interval below the exclusion. The
        // 20px row reaches it, so retrying from the same cursor must produce
        // the two carved segments rather than an exhausted paragraph.
        assert_eq!(lines.len(), 2);
        assert_eq!(
            lines.iter().map(|line| line.text_start).collect::<Vec<_>>(),
            vec![0, 7]
        );
        assert_eq!(
            lines
                .iter()
                .map(|line| (line.column_start, line.segment_width))
                .collect::<Vec<_>>(),
            vec![(0, 4_000), (5_000, 4_000)]
        );
        assert_eq!(
            shared_metrics(&lines),
            vec![(0, 1_500, 1_500, 1_275, 900); 2]
        );
        assert_eq!(frame.row_count(), 1);
        assert_eq!(frame.top, 2_400);
    }

    fn a_frame_that_expects_the_stored_rows_admits_them_and_skips_the_reflow() {
        let styles = styles(&[12.0]);
        let mut para = paragraph(
            "alpha beta gamma delta",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        para.line_segs = vec![
            LineSeg {
                text_start: 0,
                vertical_pos: 700,
                line_height: 321,
                text_height: 300,
                baseline_distance: 250,
                line_spacing: 17,
                column_start: 1_000,
                segment_width: 4_000,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            },
            LineSeg {
                // This deliberately is not a fresh word boundary. A matching
                // Frame must preserve the cached text partition verbatim.
                text_start: 2,
                vertical_pos: 1_038,
                line_height: 654,
                text_height: 600,
                baseline_distance: 500,
                line_spacing: 23,
                column_start: 1_000,
                segment_width: 4_000,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            },
        ];
        let mut frame = LayoutFrame::new(1_000..5_000, 700, Vec::new());

        // Reuse requires the current frame to reproduce the stored physical-row
        // key exactly. Only then may the cached text partition stand.
        let resolution = resolve_stored_line_segs_in_frame(
            &para,
            &mut frame,
            &styles,
            96.0,
            false,
            StoredRowMissPolicy::Reflow,
            false,
            &[],
            false,
        )
        .expect("a scalar cached paragraph is frame-resolvable");
        assert_eq!(resolution, StoredRowResolution::Stored);
        assert_eq!(frame.row_count(), 2);

        // Geometry is preserved because the carve reproduced it — that is the
        // admission test. Vertical metrics are **not**: §1.4.1 recomputes them
        // on both arms and writes them back over the stored record, so the
        // frame publishes what it computed, not what the file carried. The
        // stored heights here (321/654) are fixture values with no relation to
        // the 12pt char shape the provider measures.
        let projected = frame.project_line_segs();
        assert_eq!(projected.len(), 2);
        assert!(projected
            .iter()
            .zip(&para.line_segs)
            .all(|(row, stored)| row.text_start == stored.text_start
                && row.column_start == stored.column_start
                && row.segment_width == stored.segment_width));
        let computed = frame_metrics_for_line(12.0, 12.0, LineSpacingType::Percent, 160.0, 96.0);
        assert!(projected
            .iter()
            .all(|row| row.line_height == computed.line_height
                && row.line_spacing == computed.line_spacing));
        assert_eq!(
            frame.top,
            700 + 2 * (computed.line_height + computed.line_spacing)
        );
    }

    fn width_neutrality_is_a_property_of_geometry_not_a_list_of_variants() {
        // Every one of these contributes no inline width and owns no layout
        // box, so the frame owns their paragraph. Only `SectionDef`,
        // `ColumnDef` and `Field` used to qualify; a body paragraph carrying
        // any of the others had no layout owner at all.
        for control in [
            Control::SectionDef(Box::default()),
            Control::ColumnDef(Default::default()),
            Control::Field(Default::default()),
            Control::Bookmark(Default::default()),
            Control::PageNumberPos(Default::default()),
            Control::PageHide(Default::default()),
            Control::HiddenComment(Box::default()),
            // HWP3 keeps hyperlinks as their own control. HWP5/HWPX turn `%hlk`
            // into a `Control::Field` by a prefix test, which is the only
            // reason those ever reached the frame.
            Control::Hyperlink(Default::default()),
            Control::AutoNumber(Default::default()),
            Control::NewNumber(Default::default()),
            Control::Unknown(Default::default()),
        ] {
            assert!(
                control_is_width_neutral_marker(&control),
                "{control:?} has no geometry, so the frame must own its paragraph"
            );
        }

        // These resolve their own geometry — inline or floating — so the frame
        // must decline and leave them with their established owner. A body
        // frame carries no exclusion, so claiming a floating object's paragraph
        // would flatten the wrap it cannot see.
        for control in [
            Control::Table(Box::default()),
            Control::Shape(Box::new(crate::model::shape::ShapeObject::Rectangle(
                Default::default(),
            ))),
            Control::Picture(Box::default()),
            Control::Equation(Box::default()),
            Control::Form(Box::default()),
            Control::Header(Box::default()),
            Control::Footer(Box::default()),
            Control::Footnote(Box::default()),
            Control::Endnote(Box::default()),
        ] {
            assert!(
                !control_is_width_neutral_marker(&control),
                "{control:?} owns its own layout box"
            );
        }
    }

    fn body_stored_route_admits_only_width_neutral_structural_controls() {
        let styles = styles(&[12.0]);
        let mut structural = paragraph(
            "section body",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        structural.line_segs = vec![LineSeg {
            vertical_pos: 100,
            line_height: 900,
            text_height: 900,
            baseline_distance: 765,
            line_spacing: 540,
            column_start: 0,
            segment_width: 9_000,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            ..Default::default()
        }];
        structural.controls = vec![
            Control::SectionDef(Box::default()),
            Control::ColumnDef(Default::default()),
        ];
        assert!(supports_cached_body_frame_controls(&structural));
        let mut structural_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
        assert!(matches!(
            resolve_stored_line_segs_in_frame(
                &structural,
                &mut structural_frame,
                &styles,
                96.0,
                false,
                StoredRowMissPolicy::Reflow,
                false,
                &[],
                false,
            ),
            Some(StoredRowResolution::Stored)
        ));
        // Width-neutral markers do not move the carve, so production admission
        // has committed the matching cached row into the frame.
        assert_eq!(structural_frame.row_count(), 1);
        assert_eq!(
            structural_frame
                .project_line_segs()
                .iter()
                .map(|line| (line.column_start, line.segment_width))
                .collect::<Vec<_>>(),
            vec![(0, 9_000)]
        );

        let mut specialized = structural.clone();
        specialized.controls = vec![Control::Table(Box::default())];
        assert!(!supports_cached_body_frame_controls(&specialized));
        let mut specialized_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
        let checkpoint = specialized_frame.clone();
        assert!(resolve_stored_line_segs_in_frame(
            &specialized,
            &mut specialized_frame,
            &styles,
            96.0,
            false,
            StoredRowMissPolicy::Reflow,
            true,
            &[],
            false,
        )
        .is_none());
        assert_eq!(specialized_frame, checkpoint);

        // A Square exclusion can leave one slot per row and still change that
        // slot when the band ends. An exclusion-less body frame cannot infer
        // the missing band from these cached outputs, so varying single-slot
        // geometry is unmodelled rather than a reason to flatten and reflow.
        let mut varying_single_slot = structural.clone();
        varying_single_slot.controls.clear();
        varying_single_slot.line_segs = vec![
            LineSeg {
                text_start: 0,
                column_start: 0,
                segment_width: 4_000,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..structural.line_segs[0].clone()
            },
            LineSeg {
                text_start: 4,
                column_start: 0,
                segment_width: 9_000,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..structural.line_segs[0].clone()
            },
        ];
        let mut scalar_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
        let scalar_checkpoint = scalar_frame.clone();
        assert!(resolve_stored_line_segs_in_frame(
            &varying_single_slot,
            &mut scalar_frame,
            &styles,
            96.0,
            false,
            StoredRowMissPolicy::Reflow,
            false,
            &[],
            false,
        )
        .is_none());
        assert_eq!(scalar_frame, scalar_checkpoint);

        let mut empty_external_carrier = structural.clone();
        empty_external_carrier.text.clear();
        empty_external_carrier.char_offsets.clear();
        empty_external_carrier.char_count = 1;
        empty_external_carrier.controls.clear();
        empty_external_carrier.line_segs = vec![LineSeg {
            text_start: 0,
            column_start: 4_000,
            segment_width: 5_000,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            ..structural.line_segs[0].clone()
        }];
        let mut carrier_frame = LayoutFrame::new(0..9_000, 100, Vec::new());
        let carrier_checkpoint = carrier_frame.clone();
        assert!(resolve_stored_line_segs_in_frame(
            &empty_external_carrier,
            &mut carrier_frame,
            &styles,
            96.0,
            false,
            StoredRowMissPolicy::Reflow,
            false,
            &[],
            false,
        )
        .is_none());
        assert_eq!(carrier_frame, carrier_checkpoint);
    }

    fn hwp3_formatting_rebuild_preserves_legacy_stored_geometry_jurisdiction() {
        use crate::document_core::DocumentCore;
        use std::fs;
        use std::path::Path;

        let path = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("samples/issue1892_hwp3_drawing_group_roundtrip.hwp");
        let bytes = fs::read(&path).unwrap_or_else(|error| panic!("read {path:?}: {error}"));
        let mut core = DocumentCore::from_bytes(&bytes).expect("load HWP3 formatting fixture");
        assert!(
            core.document.layout_profile().legacy_hwp3_stored_geometry(),
            "the HWP3 fixture must retain legacy stored-geometry jurisdiction"
        );

        // Choose a plain, nonempty single-row paragraph. With no controls and
        // no varying slots, only HWP3 lineage can make this mismatching Frame
        // unmodelled; clearing the lineage flag below proves the reversal.
        let (section_index, paragraph_index) = core
            .document
            .sections
            .iter()
            .enumerate()
            .find_map(|(section_index, section)| {
                section
                    .paragraphs
                    .iter()
                    .enumerate()
                    .find(|(_, paragraph)| {
                        !paragraph.text.trim().is_empty()
                            && paragraph.controls.is_empty()
                            && paragraph.line_segs.len() == 1
                            && paragraph.line_segs[0].is_first_segment()
                            && paragraph.line_segs[0].is_last_segment()
                            && paragraph.line_segs[0].segment_width > 2_400
                    })
                    .map(|(paragraph_index, _)| (section_index, paragraph_index))
            })
            .expect("fixture has a plain legacy stored row");
        let stored_before = line_fields(
            &core.document.sections[section_index].paragraphs[paragraph_index].line_segs,
        );

        // Underline is paint-only, but the public formatting lifecycle still
        // calls rebuild_section(). The legacy row itself must remain untouched.
        core.apply_char_format_native(
            section_index,
            paragraph_index,
            0,
            1,
            r#"{"underline":true}"#,
        )
        .expect("apply paint-only format");
        assert_eq!(
            line_fields(
                &core.document.sections[section_index].paragraphs[paragraph_index].line_segs,
            ),
            stored_before
        );
        assert!(core.document.layout_profile().legacy_hwp3_stored_geometry());

        let paragraph = &core.document.sections[section_index].paragraphs[paragraph_index];
        let stored = &paragraph.line_segs[0];
        let frame_horizontal = stored.column_start.saturating_add(1_200)
            ..stored.column_start.saturating_add(stored.segment_width);

        let mut ordinary_frame =
            LayoutFrame::new(frame_horizontal.clone(), stored.vertical_pos, Vec::new());
        assert!(matches!(
            resolve_stored_line_segs_in_frame(
                paragraph,
                &mut ordinary_frame,
                &core.styles,
                96.0,
                false,
                StoredRowMissPolicy::Reflow,
                false,
                &[],
                false,
            ),
            Some(StoredRowResolution::Reflowed)
        ));

        let mut legacy_frame = LayoutFrame::new(frame_horizontal, stored.vertical_pos, Vec::new());
        assert!(
            resolve_stored_line_segs_in_frame(
                paragraph,
                &mut legacy_frame,
                &core.styles,
                96.0,
                true,
                StoredRowMissPolicy::Reflow,
                false,
                &[],
                false,
            )
            .is_none(),
            "untouched HWP3 stored origin remains outside the common Frame's jurisdiction"
        );
    }

    fn frame_rejected_rows_reflow_without_propagating_cached_source_flags() {
        let styles = styles(&[12.0]);
        let mut para = paragraph(
            "abcdef ghijkl",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        para.line_segs = vec![LineSeg {
            text_start: 0,
            vertical_pos: 100,
            line_height: 900,
            text_height: 900,
            baseline_distance: 765,
            line_spacing: 540,
            column_start: 0,
            segment_width: 9_000,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE
                | LineSeg::TAG_FIRST_LINE_OF_PAGE
                | LineSeg::TAG_FIRST_LINE_OF_COLUMN
                | LineSeg::TAG_EMPTY_SEGMENT,
        }];
        let mut frame = LayoutFrame::new(
            0..9_000,
            100,
            vec![FrameExclusion {
                horizontal: 3_000..5_000,
                vertical: 0..10_000,
                policy: FrameExclusionPolicy::BothSides,
            }],
        );

        let resolution = resolve_stored_line_segs_in_frame(
            &para,
            &mut frame,
            &styles,
            96.0,
            false,
            StoredRowMissPolicy::Reflow,
            false,
            &[],
            false,
        )
        .expect("a scalar cached paragraph is frame-resolvable");

        let StoredRowResolution::Reflowed = resolution else {
            panic!("rows differing from the frame expectation must reflow");
        };
        // The frame holds the rows now; projecting is the only way out.
        let lines = frame.project_line_segs();
        assert_eq!(
            lines
                .iter()
                .map(|line| (line.text_start, line.column_start, line.segment_width))
                .collect::<Vec<_>>(),
            vec![(0, 0, 3_000), (7, 5_000, 4_000)]
        );
        assert_eq!(frame.row_count(), 1);
        assert_eq!(frame.top, 1_540);
        let rejected_cache_flags = LineSeg::TAG_FIRST_LINE_OF_PAGE
            | LineSeg::TAG_FIRST_LINE_OF_COLUMN
            | LineSeg::TAG_EMPTY_SEGMENT;
        assert!(lines
            .iter()
            .all(|line| line.tag & rejected_cache_flags == 0));
        assert!(lines
            .iter()
            .all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0));
    }

    fn picture_band_frame_fill_inherits_provenance_not_cached_row_state() {
        let styles = styles(&[12.0]);
        let mut para = paragraph(
            "alpha beta gamma delta epsilon zeta eta theta iota kappa",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        let cached_row_flags = LineSeg::TAG_FIRST_LINE_OF_PAGE
            | LineSeg::TAG_FIRST_LINE_OF_COLUMN
            | LineSeg::TAG_EMPTY_SEGMENT
            | LineSeg::TAG_AUTO_HYPHENATION
            | LineSeg::TAG_INDENTATION
            | LineSeg::TAG_PARAGRAPH_HEAD;
        para.line_segs = vec![LineSeg {
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | cached_row_flags,
            ..Default::default()
        }];

        let fill = |paragraph: &Paragraph| {
            let mut frame = LayoutFrame::new(0..3_000, 0, Vec::new());
            layout_paragraph_in_frame(paragraph, &mut frame, &styles, 96.0)
                .expect("Picture-band fill must produce fresh rows")
        };
        let mut picture_band_input = para;
        picture_band_input.line_segs.clear();
        let synthetic = fill(&picture_band_input);
        assert!(synthetic.len() > 1, "fixture must exercise later rows");
        assert!(synthetic
            .iter()
            .all(|line| line.tag & cached_row_flags == 0));
        assert!(synthetic
            .iter()
            .all(|line| line.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0));
    }

    #[test]
    fn eligible_scalar_reflow_projects_the_frozen_scalar_oracle() {
        let styles = styles(&[12.0]);
        let mut para = paragraph(
            "alpha beta gamma delta epsilon",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        para.line_segs = vec![LineSeg {
            vertical_pos: 321,
            tag: LineSeg::TAG_SINGLE_SEGMENT_LINE | LineSeg::TAG_IMPLEMENTATION_PROPERTY,
            ..Default::default()
        }];
        let mut expected = frozen_scalar_projection(&para, 50.0, &styles, 96.0);
        assert!(expected.len() > 1, "fixture must exercise row recurrence");
        // [#7412] 셀 내용 상자는 한/글 저장본처럼 4 HWPUNIT 격자로 내린 폭(3750 → 3748)을
        // 발행한다. 줄 나눔은 동결 오라클과 같아야 하므로 폭 필드만 격자 값으로 맞춘다.
        for line in &mut expected {
            line.segment_width -= line.segment_width.rem_euclid(4);
        }

        reflow_line_segs(
            &mut para,
            ParagraphBox::content_width_px(50.0, 96.0),
            &styles,
            96.0,
        );

        assert_eq!(line_fields(&para.line_segs), line_fields(&expected));
        assert!(para
            .line_segs
            .iter()
            .all(|line| line.segment_width == 3_748 && line.column_start == 0));
        assert_eq!(para.line_segs[0].vertical_pos, 321);
    }

    #[test]
    fn picture_band_uses_para_reference_not_text_frame_for_right_aligned_picture() {
        use crate::model::image::Picture;
        use crate::model::shape::{HorzAlign, HorzRelTo, TextFlow, TextWrap, VertAlign, VertRelTo};

        const DPI: f64 = 96.0;
        const COLUMN_WIDTH: i32 = 15_000;
        const MARGIN_LEFT: i32 = 1_500;
        const MARGIN_RIGHT: i32 = 3_000;
        const PICTURE_WIDTH: u32 = 3_000;

        let mut styles = styles(&[12.0]);
        styles.para_styles[0].margin_left = crate::renderer::hwpunit_to_px(MARGIN_LEFT, DPI);
        styles.para_styles[0].margin_right = crate::renderer::hwpunit_to_px(MARGIN_RIGHT, DPI);
        let text_frame = MARGIN_LEFT..COLUMN_WIDTH - MARGIN_RIGHT;
        let paragraph_reference = picture_band_paragraph_reference(&(0..COLUMN_WIDTH), MARGIN_LEFT)
            .expect("host left margin leaves a usable Paragraph reference");
        assert_eq!(paragraph_reference, MARGIN_LEFT..COLUMN_WIDTH);
        assert_ne!(text_frame, paragraph_reference);

        let picture = Picture {
            common: crate::model::shape::CommonObjAttr {
                width: PICTURE_WIDTH,
                height: 600,
                text_wrap: TextWrap::Square,
                text_flow: TextFlow::BothSides,
                vert_rel_to: VertRelTo::Para,
                vert_align: VertAlign::Top,
                horz_rel_to: HorzRelTo::Para,
                horz_align: HorzAlign::Right,
                ..Default::default()
            },
            ..Default::default()
        };
        let expected_exclusion = crate::renderer::float_placement::resolve_picture_exclusion(
            &picture,
            0..COLUMN_WIDTH,
            paragraph_reference.clone(),
            0,
            crate::renderer::float_placement::PaperOrigin::default(),
        )
        .expect("supported Paragraph-relative Picture");
        assert_eq!(expected_exclusion.horizontal, 12_000..15_000);

        let mut host = paragraph(
            "x",
            vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
        );
        host.controls.push(Control::Picture(Box::new(picture)));

        let band = layout_picture_band(
            &[host],
            0,
            crate::renderer::hwpunit_to_px(COLUMN_WIDTH, DPI),
            &styles,
            DPI,
            (0.0, 0.0),
        )
        .expect("the one-row Paragraph-relative Picture band");

        assert_eq!(band.paragraph_range, 0..1);
        assert_eq!(band.line_segs[0].len(), 1);
        assert_eq!(band.line_segs[0][0].column_start, text_frame.start);
        assert_eq!(
            band.line_segs[0][0].segment_width,
            text_frame.end - text_frame.start,
            "the right-aligned Para exclusion begins at the text frame's end"
        );
    }

    #[test]
    fn pic2_two_picture_host_is_explicitly_outside_the_one_picture_band_contract() {
        use crate::model::page::ColumnDef;
        use crate::renderer::page_layout::PageLayoutInfo;

        const DPI: f64 = 96.0;
        let bytes = std::fs::read(
            std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("samples/pic2.hwp"),
        )
        .expect("pic2 fixture");
        let document = crate::parse_document(&bytes).expect("parse pic2 fixture");
        let section = &document.sections[0];
        let column_def = section.paragraphs[..=0]
            .iter()
            .flat_map(|paragraph| &paragraph.controls)
            .filter_map(|control| match control {
                Control::ColumnDef(column) => Some(column.clone()),
                _ => None,
            })
            .next_back()
            .unwrap_or_else(ColumnDef::default);
        let page_layout =
            PageLayoutInfo::from_page_def(&section.section_def.page_def, &column_def, DPI);
        let column_width = page_layout.column_areas[0].width;
        let styles = crate::renderer::style_resolver::resolve_styles(&document.doc_info, DPI);

        assert_eq!(
            section.paragraphs[0]
                .controls
                .iter()
                .filter(|control| {
                    matches!(control, Control::Picture(picture) if !picture.common.treat_as_char)
                })
                .count(),
            2,
            "fixture premise: pic2's first paragraph has two floating pictures"
        );
        assert!(
            layout_picture_band(
                &section.paragraphs,
                0,
                column_width,
                &styles,
                DPI,
                (0.0, 0.0)
            )
            .is_none(),
            "two floating pictures are deliberately not a one-picture band"
        );
    }
}

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

    #[test]
    fn trailing_physical_line_preserves_control_stream_end_offset() {
        let mut para = Paragraph {
            text: "가\n".to_string(),
            // visible text 앞에 16 UTF-16 unit의 control stream gap이 있다.
            char_offsets: vec![16, 17],
            ..Default::default()
        };

        reflow_line_segs(
            &mut para,
            ParagraphBox::content_width_px(500.0, 96.0),
            &ResolvedStyleSet::default(),
            96.0,
        );

        assert_eq!(para.line_segs.len(), 2);
        assert_eq!(para.line_segs[1].text_start, 18);
    }

    #[test]
    fn missing_char_offsets_count_supplementary_unicode_as_utf16_units() {
        let para = Paragraph {
            text: "😀\n".to_string(),
            ..Default::default()
        };

        assert_eq!(char_index_to_utf16_offset(&para, 2), 3);
    }
}