rhwp 0.9.1

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
//! 글자모양/문단모양 조회·적용 관련 native 메서드

use super::super::helpers::{
    border_line_type_to_u8_val, build_tab_def_from_json, color_ref_to_css, fill_json_values,
    json_has_border_keys, json_has_tab_keys, parse_char_shape_mods, parse_json_i16_array,
    parse_para_shape_mods,
};
use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::event::DocumentEvent;
use crate::renderer::composer::{
    paragraph_flow_end, recalculate_section_vpos, reflow_line_segs, restamp_indentation,
    ParagraphBox,
};
use crate::renderer::page_layout::PageLayoutInfo;
use crate::renderer::style_resolver::ResolvedStyleSet;

pub(super) fn char_shape_mods_affect_text_flow(mods: &crate::model::style::CharShapeMods) -> bool {
    mods.base_size.is_some()
        || mods.font_ids.is_some()
        || mods.ratios.is_some()
        || mods.spacings.is_some()
        || mods.relative_sizes.is_some()
        || mods.char_offsets.is_some()
}

/// [#4324] `ParaShapeMods` 변경이 줄바꿈(LineSeg 재계산)에 영향을 주는지 판정한다.
/// `char_shape_mods_affect_text_flow`(:16)의 문단모양 대응물 — 형태를 그대로 따른다.
///
/// 전수 조사(reflow_line_segs/fill_lines, composer/line_breaking.rs 가 실제로 읽는
/// 입력만 기준으로 판정, #4324 보고 참고):
/// - `margin_left`/`margin_right`: 호출부가 `available_width = 폭 - margin_left -
///   margin_right`로 사용 가능 폭을 좁힌다(:25-46, reflow_cell_paragraph
///   text_editing.rs:2245-2247).
/// - `indent`: `fill_lines`의 `eff_w()`가 첫 줄(또는 이어줄) 유효 폭을 들여쓰기만큼
///   줄인다(line_breaking.rs:681-696).
/// - `english_break_unit`/`korean_break_unit`: `tokenize_paragraph`/`fill_lines`가 토큰
///   경계 자체(영어 단어/하이픈/글자, 한글 글자 단위 break 허용)를 바꾼다
///   (line_breaking.rs:360, 375, 798).
/// - `line_spacing`/`line_spacing_type`: 원래 게이트 — `reflow_line_segs`가 LineSeg별
///   `line_spacing` 값을 다시 계산하므로 유지한다.
/// - `head_type`/`numbering_id`/`para_level`: 문단 머리(글머리표·번호·개요)는 줄 앞을
///   차지해 첫 구간의 폭을 바꾸고(#7418), 한/글은 머리가 있는 문단의 첫 줄에
///   `TAG_PARAGRAPH_HEAD`(bit 21)를 단다. 다시 짜지 않으면 머리를 켜거나 끈 문단이 옛
///   비트로 저장돼 한/글이 글머리표를 그리지 않거나 남긴다.
///
/// 번호·글머리표의 종류·수준·정의 ID도 공통 목록 영역을 바꾼다.
/// 저장된 기존 줄 캐시로 내보내면 한컴이 마커 없는 배치를 재사용하므로 무효화한다.
///
/// 나머지 필드(alignment, spacing_before/after, widow_orphan,
/// keep_with_next, keep_lines, page_break_before, font_line_height, single_line,
/// auto_space_kr_en/num, vertical_align, tab_def_id, border_fill_id,
/// border_spacing, border_connect, border_ignore_margin)는 `reflow_line_segs`/
/// `fill_lines`가 읽지 않는다 — 정렬은 이미 배치된 줄 안에서의 렌더링 배분일 뿐이고,
/// 문단 테두리/배경은 레이아웃 완료 후 장식 사각형으로만 그려지며(layout.rs
/// render_para_border_groups), 문단 간격·쪽나눔 휴리스틱은 `rebuild_section`이 매번
/// 다시 계산하는 vpos/페이지네이션 단계에서 처리된다. `tab_def_id`는 현재
/// `resolve_single_para_style`이 `default_tab_width`를 4000 HWPUNIT 상수로 고정해
/// 두므로(별개 결함 가능성, 이 이슈 범위 밖) 오늘 시점 코드에서 흐름에 영향이 없다.
pub(super) fn para_shape_mods_affect_text_flow(mods: &crate::model::style::ParaShapeMods) -> bool {
    mods.line_spacing.is_some()
        || mods.line_spacing_type.is_some()
        || mods.margin_left.is_some()
        || mods.margin_right.is_some()
        || mods.indent.is_some()
        || mods.english_break_unit.is_some()
        || mods.korean_break_unit.is_some()
        || mods.head_type.is_some()
        || mods.para_level.is_some()
        || mods.numbering_id.is_some()
}

/// 문단 머리의 기하가 달라지면 외부 소비자의 이전 줄 배치를 재사용하지 않는다.
pub(super) fn marker_shape_changed(
    before: &crate::model::style::ParaShape,
    after: &crate::model::style::ParaShape,
) -> bool {
    before.head_type != after.head_type
        || before.para_level != after.para_level
        || before.numbering_id != after.numbering_id
}

// ID 복원도 적용과 같은 흐름 속성 및 문단 간격만 비교한다.
pub(super) fn cell_para_shape_affects_vpos(
    before: &crate::model::style::ParaShape,
    after: &crate::model::style::ParaShape,
) -> bool {
    marker_shape_changed(before, after)
        || before.line_spacing != after.line_spacing
        || before.line_spacing_type != after.line_spacing_type
        || before.margin_left != after.margin_left
        || before.margin_right != after.margin_right
        || before.indent != after.indent
        || (before.attr1 ^ after.attr1) & (0b111 << 5) != 0 // 영어·한글 줄나눔 단위
        || before.spacing_before != after.spacing_before
        || before.spacing_after != after.spacing_after
}

fn body_paragraph_box_for_para_shape(
    core: &DocumentCore,
    sec_idx: usize,
    para_shape_id: u16,
    styles: &ResolvedStyleSet,
) -> ParagraphBox {
    let Some(section) = core.document.sections.get(sec_idx) else {
        return ParagraphBox::content(0..1);
    };
    let page_def = &section.section_def.page_def;
    let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
    let layout = PageLayoutInfo::from_page_def(page_def, &column_def, core.dpi);
    let col_width = layout
        .column_areas
        .first()
        .map(|a| a.width)
        .unwrap_or(layout.body_area.width);
    let para_style = styles.para_styles.get(para_shape_id as usize);
    ParagraphBox::body_for_style(col_width, para_style, core.dpi)
}

/// [#7490] 병합 undo 로 되살린 문단에 사라졌던 문단의 메타를 돌려준다.
///
/// 새 문단은 앞 문단의 첫 줄 기록(bit 20)을 물려받는다. 돌려준 문단 모양의 들여쓰기가
/// 다르면 [`restamp_indentation`] 으로 기록도 고친다. 그대로 두면 재조판이 옛 기록을
/// "들여쓰기를 적용하지 않은 문단"으로 읽는다.
pub(super) fn restore_para_meta(
    para: &mut crate::model::paragraph::Paragraph,
    meta: crate::model::paragraph::ParaMeta,
    para_shapes: &[crate::model::style::ParaShape],
) {
    let indent = |id: u16| {
        para_shapes
            .get(usize::from(id))
            .map_or(0, |shape| shape.indent)
    };
    let (old_indent, new_indent) = (indent(para.para_shape_id), indent(meta.para_shape_id));
    para.apply_meta(meta);
    restamp_indentation(&mut para.line_segs, old_indent, new_indent);
}

// 폭 변경 재조판은 저장 줄의 vpos·tag를 이어받지 않는다. 문단 흐름을 잇는
// 텍스트 편집 경로와 달리, 새 줄을 조판기가 현재 단 안에 배치하게 한다.
fn reflow_body_paragraph_in_box(
    para: &mut crate::model::paragraph::Paragraph,
    paragraph_box: ParagraphBox,
    styles: &ResolvedStyleSet,
    dpi: f64,
) {
    para.line_segs.clear();
    reflow_line_segs(para, paragraph_box, styles, dpi);
}

impl DocumentCore {
    /// 단 정의를 직접 바꾼 뒤 그 정의를 따르는 본문 범위 `[start, end)`만 다시 접는다.
    ///
    /// 각 문단에 적용되는 단 정의와 직전 페이지네이션의 소속 단 폭을 쓴다. 너비가
    /// 다른 단으로 옮겨 간 문단은 페이지네이션 후 같은 범위를 다시 호출해 새 폭으로
    /// 접을 수 있다. 범위 밖의 본문·셀·주석·머리말 저장 줄은 건드리지 않는다.
    /// 텍스트 편집 이벤트와 캐럿 저장 위치를 만들지 않으며 배치 중에는 쪽 나눔을 미룬다.
    pub fn reflow_body_paragraph_range_native(
        &mut self,
        sec_idx: usize,
        range: std::ops::Range<usize>,
    ) -> Result<(), HwpError> {
        let section = self
            .document
            .sections
            .get(sec_idx)
            .ok_or_else(|| HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)))?;
        if range.start > range.end || range.end > section.paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "본문 문단 범위 {}..{} 범위 초과",
                range.start, range.end
            )));
        }
        if range.is_empty() {
            return Ok(());
        }

        let styles = self.resolve_render_styles();
        let dpi = self.dpi;
        // 어느 저장 줄도 비우기 전에 모든 문단 상자를 검사한다. 문단 여백이 단 폭을
        // 넘는 요청은 기존 저장 줄을 잃거나 범위 일부만 바꾸지 않고 거절한다.
        let boxes: Vec<_> = range
            .clone()
            .map(|para_idx| {
                let column_def = Self::find_column_def_for_paragraph(&section.paragraphs, para_idx);
                let layout =
                    PageLayoutInfo::from_page_def(&section.section_def.page_def, &column_def, dpi);
                let col_idx = self
                    .para_column_map
                    .get(sec_idx)
                    .and_then(|columns| columns.get(para_idx))
                    .copied()
                    .unwrap_or(0) as usize;
                let column = layout
                    .column_areas
                    .get(col_idx)
                    .unwrap_or(&layout.column_areas[0]);
                let para = &section.paragraphs[para_idx];
                let paragraph_box = ParagraphBox::body_for_style(
                    column.width,
                    styles.para_styles.get(para.para_shape_id as usize),
                    dpi,
                );
                if !paragraph_box.is_usable() {
                    return Err(HwpError::RenderError(format!(
                        "본문 문단 {}의 여백이 단 너비를 넘습니다",
                        para_idx
                    )));
                }
                Ok(paragraph_box)
            })
            .collect::<Result<_, _>>()?;
        for (para_idx, paragraph_box) in range.zip(boxes) {
            reflow_body_paragraph_in_box(
                &mut self.document.sections[sec_idx].paragraphs[para_idx],
                paragraph_box,
                &styles,
                dpi,
            );
            self.fit_cell_grid(sec_idx, para_idx, &styles);
        }
        self.refresh_section_native(sec_idx)
    }

    /// 저장 줄을 보존하며 직접 수정한 구역의 스타일·조판·렌더 캐시를 갱신한다.
    /// 단 구분선처럼 줄바꿈 폭이 그대로인 변경에 쓰며 배치 중에는 쪽 나눔을 미룬다.
    pub fn refresh_section_native(&mut self, sec_idx: usize) -> Result<(), HwpError> {
        let section = self
            .document
            .sections
            .get_mut(sec_idx)
            .ok_or_else(|| HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)))?;
        section.raw_stream = None;
        // 기존 rebuild_section과 같은 순서로 파생 상태를 갱신하되 배치는 존중한다.
        self.rebuild_resolved_styles();
        self.flush_cell_format_vpos();
        self.recompose_section(sec_idx);
        self.paginate_if_needed();
        Ok(())
    }

    /// [#7490] 문단 모양 `old_id` 와 `new_id` 의 들여쓰기(HWPUNIT).
    pub(crate) fn para_shape_indents(&self, old_id: u16, new_id: u16) -> (i32, i32) {
        let indent = |id: u16| {
            self.document
                .doc_info
                .para_shapes
                .get(usize::from(id))
                .map_or(0, |shape| shape.indent)
        };
        (indent(old_id), indent(new_id))
    }

    pub fn get_char_properties_at_native(
        &self,
        sec_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        let section = self
            .document
            .sections
            .get(sec_idx)
            .ok_or_else(|| HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)))?;
        let para = section
            .paragraphs
            .get(para_idx)
            .ok_or_else(|| HwpError::RenderError(format!("문단 {} 범위 초과", para_idx)))?;
        Ok(self.build_char_properties_json(para, char_offset))
    }

    /// 셀 내부 문단의 글자 속성 조회 (네이티브)
    pub fn get_cell_char_properties_at_native(
        &self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        let para = self
            .get_cell_paragraph_ref(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )
            .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?;
        Ok(self.build_char_properties_json(para, char_offset))
    }

    /// 캐럿 위치의 문단 속성 조회 (네이티브)
    pub fn get_para_properties_at_native(
        &self,
        sec_idx: usize,
        para_idx: usize,
    ) -> Result<String, HwpError> {
        use crate::model::control::Control;
        use crate::model::style::HeadType;
        let section = self
            .document
            .sections
            .get(sec_idx)
            .ok_or_else(|| HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)))?;
        let Some(para) = section.paragraphs.get(para_idx) else {
            if let Some(src) = self.virtual_endnote_para_source(sec_idx, para_idx) {
                return self.get_para_properties_in_footnote_native(
                    src.section_index,
                    src.para_index,
                    src.control_index,
                    src.note_para_index,
                );
            }
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        };
        let mut json = self.build_para_properties_json(para.para_shape_id, sec_idx);

        // 번호 시작 방식 판별: numbering_id 패턴 기반
        let ps = self.styles.para_styles.get(para.para_shape_id as usize);
        let head_type = ps.map(|s| s.head_type).unwrap_or(HeadType::None);
        if head_type != HeadType::None {
            let cur_nid = ps.map(|s| s.numbering_id).unwrap_or(0);
            // NewNumber 컨트롤 체크
            let new_number = para.controls.iter().find_map(|c| {
                if let Control::NewNumber(nn) = c {
                    Some(nn.number)
                } else {
                    None
                }
            });
            let (mode, start_num) = if let Some(num) = new_number {
                (2, num as u32) // 새 번호 목록 시작 (NewNumber 컨트롤)
            } else {
                // 이전 번호 문단의 numbering_id를 역순 스캔
                let mut prev_nid: Option<u16> = None;
                let mut seen_before = false;
                for pi in (0..para_idx).rev() {
                    let pp = &section.paragraphs[pi];
                    let pps = self.styles.para_styles.get(pp.para_shape_id as usize);
                    let pht = pps.map(|s| s.head_type).unwrap_or(HeadType::None);
                    if pht == HeadType::None {
                        continue;
                    }
                    let pnid = pps.map(|s| s.numbering_id).unwrap_or(0);
                    if prev_nid.is_none() {
                        prev_nid = Some(pnid);
                    }
                    if pnid == cur_nid {
                        seen_before = true;
                        break;
                    }
                }
                match (prev_nid, seen_before) {
                    (Some(pid), _) if pid == cur_nid => (0, 1), // 앞 번호 이어
                    (_, true) => (1, 1),                        // 이전 번호 이어
                    _ => (2, 1),                                // 새 번호 시작
                }
            };
            json.pop(); // 마지막 '}' 제거
            json.push_str(&format!(
                ",\"numberingRestartMode\":{},\"numberingStartNum\":{}}}",
                mode, start_num
            ));
        }

        Ok(json)
    }

    fn virtual_endnote_para_source(
        &self,
        sec_idx: usize,
        para_idx: usize,
    ) -> Option<crate::renderer::pagination::EndnoteParaSource> {
        let body_len = self.document.sections.get(sec_idx)?.paragraphs.len();
        let local_idx = para_idx.checked_sub(body_len)?;
        self.pagination
            .get(sec_idx)?
            .endnote_para_sources
            .get(local_idx)
            // [#7860] 편집 명령은 본문 문단의 미주 주소만 받는다. 표 셀 안 미주는 제외한다.
            .filter(|src| src.cell_path.is_empty())
            .cloned()
    }

    /// 셀 내부 문단의 문단 속성 조회 (네이티브)
    pub fn get_cell_para_properties_at_native(
        &self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
    ) -> Result<String, HwpError> {
        let para = self
            .get_cell_paragraph_ref(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )
            .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?;
        Ok(self.build_para_properties_json(para.para_shape_id, sec_idx))
    }

    /// 글자 속성 JSON 생성 헬퍼
    pub(crate) fn build_char_properties_json(
        &self,
        para: &crate::model::paragraph::Paragraph,
        char_offset: usize,
    ) -> String {
        let char_shape_id = para.char_shape_id_at(char_offset).unwrap_or(0);
        let style = self.styles.char_styles.get(char_shape_id as usize);

        match style {
            Some(cs) => {
                use crate::model::style::UnderlineType;
                use crate::renderer::style_resolver::detect_lang_category;

                // 캐럿 위치 문자의 언어 카테고리를 판별하여 해당 폰트 반환
                let lang_index = para
                    .text
                    .chars()
                    .nth(char_offset)
                    .map(|ch| detect_lang_category(ch))
                    .unwrap_or(0);
                let font_family_raw = cs.font_family_for_lang(lang_index);
                let font_family =
                    crate::renderer::style_resolver::primary_font_name(&font_family_raw);

                let escaped_font = super::super::helpers::json_escape(font_family);
                let underline = !matches!(cs.underline, UnderlineType::None);
                let underline_type_str = match cs.underline {
                    UnderlineType::None => "None",
                    UnderlineType::Bottom => "Bottom",
                    UnderlineType::Top => "Top",
                };

                // raw CharShape에서 추가 속성 읽기
                let raw_cs = self
                    .document
                    .doc_info
                    .char_shapes
                    .get(char_shape_id as usize);
                let base_size = raw_cs.map(|s| s.base_size).unwrap_or(1000);

                // 언어별 글꼴 이름 배열 (원본 폰트명만, 폴백 제외)
                let font_families: Vec<String> = (0..7usize)
                    .map(|i| {
                        let name = cs.font_family_for_lang(i);
                        let primary = crate::renderer::style_resolver::primary_font_name(&name);
                        super::super::helpers::json_escape(primary)
                    })
                    .collect();
                let font_families_json = format!(
                    "[{}]",
                    font_families
                        .iter()
                        .map(|f| format!("\"{}\"", f))
                        .collect::<Vec<_>>()
                        .join(",")
                );

                // 언어별 수치 배열
                let (ratios, spacings, relative_sizes, char_offsets) = match raw_cs {
                    Some(s) => (s.ratios, s.spacings, s.relative_sizes, s.char_offsets),
                    None => ([100u8; 7], [0i8; 7], [100u8; 7], [0i8; 7]),
                };
                let ratios_json = format!(
                    "[{}]",
                    ratios
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let spacings_json = format!(
                    "[{}]",
                    spacings
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let relative_sizes_json = format!(
                    "[{}]",
                    relative_sizes
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let char_offsets_json = format!(
                    "[{}]",
                    char_offsets
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );

                let (
                    shadow_type,
                    shadow_color,
                    shadow_offset_x,
                    shadow_offset_y,
                    outline_type,
                    subscript,
                    superscript,
                    shade_color,
                    emboss,
                    engrave,
                    emphasis_dot,
                    underline_shape,
                    strike_shape,
                    kerning,
                ) = match raw_cs {
                    Some(s) => (
                        s.shadow_type,
                        s.shadow_color,
                        s.shadow_offset_x,
                        s.shadow_offset_y,
                        s.outline_type,
                        s.subscript,
                        s.superscript,
                        s.shade_color,
                        s.emboss,
                        s.engrave,
                        s.emphasis_dot,
                        s.underline_shape,
                        s.strike_shape,
                        s.kerning,
                    ),
                    None => (
                        0, 0xB2B2B2, 0i8, 0i8, 0, false, false, 0xFFFFFF, false, false, 0, 0, 0,
                        false,
                    ),
                };

                // 글자 테두리/배경 정보
                let border_fill_json = self.build_char_border_fill_json(raw_cs);

                format!(
                    concat!(
                        "{{\"fontFamily\":\"{}\",\"fontSize\":{},\"bold\":{},\"italic\":{},",
                        "\"underline\":{},\"underlineType\":\"{}\",\"underlineColor\":\"{}\",",
                        "\"strikethrough\":{},\"strikeColor\":\"{}\",",
                        "\"textColor\":\"{}\",\"shadeColor\":\"{}\",",
                        "\"shadowType\":{},\"shadowColor\":\"{}\",\"shadowOffsetX\":{},\"shadowOffsetY\":{},",
                        "\"outlineType\":{},",
                        "\"subscript\":{},\"superscript\":{},",
                        "\"emboss\":{},\"engrave\":{},",
                        "\"emphasisDot\":{},\"underlineShape\":{},\"strikeShape\":{},\"kerning\":{},",
                        "\"charShapeId\":{},",
                        "\"fontFamilies\":{},",
                        "\"ratios\":{},\"spacings\":{},\"relativeSizes\":{},\"charOffsets\":{},",
                        "{}",
                        "}}"
                    ),
                    escaped_font, base_size, cs.bold, cs.italic,
                    underline, underline_type_str, color_ref_to_css(cs.underline_color),
                    cs.strikethrough, color_ref_to_css(raw_cs.map(|s| s.strike_color).unwrap_or(0)),
                    color_ref_to_css(cs.text_color), color_ref_to_css(shade_color),
                    shadow_type, color_ref_to_css(shadow_color), shadow_offset_x, shadow_offset_y,
                    outline_type,
                    subscript, superscript,
                    emboss, engrave,
                    emphasis_dot, underline_shape, strike_shape, kerning,
                    char_shape_id,
                    font_families_json,
                    ratios_json, spacings_json, relative_sizes_json, char_offsets_json,
                    border_fill_json,
                )
            }
            None => {
                format!(
                    concat!(
                        "{{\"fontFamily\":\"sans-serif\",\"fontSize\":1000,\"bold\":false,\"italic\":false,",
                        "\"underline\":false,\"underlineType\":\"None\",\"underlineColor\":\"#000000\",",
                        "\"strikethrough\":false,\"strikeColor\":\"#000000\",",
                        "\"textColor\":\"#000000\",\"shadeColor\":\"#ffffff\",",
                        "\"shadowType\":0,\"shadowColor\":\"#b2b2b2\",\"shadowOffsetX\":0,\"shadowOffsetY\":0,",
                        "\"outlineType\":0,",
                        "\"subscript\":false,\"superscript\":false,",
                        "\"emboss\":false,\"engrave\":false,",
                        "\"emphasisDot\":0,\"underlineShape\":0,\"strikeShape\":0,\"kerning\":false,",
                        "\"charShapeId\":{},",
                        "\"fontFamilies\":[\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\"],",
                        "\"ratios\":[100,100,100,100,100,100,100],\"spacings\":[0,0,0,0,0,0,0],",
                        "\"relativeSizes\":[100,100,100,100,100,100,100],\"charOffsets\":[0,0,0,0,0,0,0],",
                        "\"borderFillId\":0,",
                        "\"borderLeft\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderRight\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderTop\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderBottom\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1",
                        "}}"
                    ),
                    char_shape_id
                )
            }
        }
    }

    /// charShapeId로 직접 글자 속성 JSON을 빌드 (스타일 상세 조회용)
    pub(crate) fn build_char_properties_json_by_id(&self, char_shape_id: u16) -> String {
        let style = self.styles.char_styles.get(char_shape_id as usize);
        match style {
            Some(cs) => {
                use crate::model::style::UnderlineType;
                // 한글(0) 언어를 기본으로 사용
                let font_family_raw = cs.font_family_for_lang(0);
                let font_family =
                    crate::renderer::style_resolver::primary_font_name(&font_family_raw);
                let escaped_font = super::super::helpers::json_escape(font_family);
                let underline = !matches!(cs.underline, UnderlineType::None);
                let underline_type_str = match cs.underline {
                    UnderlineType::None => "None",
                    UnderlineType::Bottom => "Bottom",
                    UnderlineType::Top => "Top",
                };
                let raw_cs = self
                    .document
                    .doc_info
                    .char_shapes
                    .get(char_shape_id as usize);
                let base_size = raw_cs.map(|s| s.base_size).unwrap_or(1000);
                let font_families: Vec<String> = (0..7usize)
                    .map(|i| {
                        let name = cs.font_family_for_lang(i);
                        let primary = crate::renderer::style_resolver::primary_font_name(&name);
                        super::super::helpers::json_escape(primary)
                    })
                    .collect();
                let font_families_json = format!(
                    "[{}]",
                    font_families
                        .iter()
                        .map(|f| format!("\"{}\"", f))
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let (ratios, spacings, relative_sizes, char_offsets) = match raw_cs {
                    Some(s) => (s.ratios, s.spacings, s.relative_sizes, s.char_offsets),
                    None => ([100u8; 7], [0i8; 7], [100u8; 7], [0i8; 7]),
                };
                let ratios_json = format!(
                    "[{}]",
                    ratios
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let spacings_json = format!(
                    "[{}]",
                    spacings
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let relative_sizes_json = format!(
                    "[{}]",
                    relative_sizes
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let char_offsets_json = format!(
                    "[{}]",
                    char_offsets
                        .iter()
                        .map(|v| v.to_string())
                        .collect::<Vec<_>>()
                        .join(",")
                );
                let (
                    shadow_type,
                    shadow_color,
                    shadow_offset_x,
                    shadow_offset_y,
                    outline_type,
                    subscript,
                    superscript,
                    shade_color,
                    emboss,
                    engrave,
                    emphasis_dot,
                    underline_shape,
                    strike_shape,
                    kerning,
                ) = match raw_cs {
                    Some(s) => (
                        s.shadow_type,
                        s.shadow_color,
                        s.shadow_offset_x,
                        s.shadow_offset_y,
                        s.outline_type,
                        s.subscript,
                        s.superscript,
                        s.shade_color,
                        s.emboss,
                        s.engrave,
                        s.emphasis_dot,
                        s.underline_shape,
                        s.strike_shape,
                        s.kerning,
                    ),
                    None => (
                        0, 0xB2B2B2, 0i8, 0i8, 0, false, false, 0xFFFFFF, false, false, 0, 0, 0,
                        false,
                    ),
                };
                let border_fill_json = self.build_char_border_fill_json(raw_cs);
                format!(
                    concat!(
                        "{{\"fontFamily\":\"{}\",\"fontSize\":{},\"bold\":{},\"italic\":{},",
                        "\"underline\":{},\"underlineType\":\"{}\",\"underlineColor\":\"{}\",",
                        "\"strikethrough\":{},\"strikeColor\":\"{}\",",
                        "\"textColor\":\"{}\",\"shadeColor\":\"{}\",",
                        "\"shadowType\":{},\"shadowColor\":\"{}\",\"shadowOffsetX\":{},\"shadowOffsetY\":{},",
                        "\"outlineType\":{},",
                        "\"subscript\":{},\"superscript\":{},",
                        "\"emboss\":{},\"engrave\":{},",
                        "\"emphasisDot\":{},\"underlineShape\":{},\"strikeShape\":{},\"kerning\":{},",
                        "\"charShapeId\":{},",
                        "\"fontFamilies\":{},",
                        "\"ratios\":{},\"spacings\":{},\"relativeSizes\":{},\"charOffsets\":{},",
                        "{}",
                        "}}"
                    ),
                    escaped_font, base_size, cs.bold, cs.italic,
                    underline, underline_type_str, color_ref_to_css(cs.underline_color),
                    cs.strikethrough, color_ref_to_css(raw_cs.map(|s| s.strike_color).unwrap_or(0)),
                    color_ref_to_css(cs.text_color), color_ref_to_css(shade_color),
                    shadow_type, color_ref_to_css(shadow_color), shadow_offset_x, shadow_offset_y,
                    outline_type,
                    subscript, superscript,
                    emboss, engrave,
                    emphasis_dot, underline_shape, strike_shape, kerning,
                    char_shape_id,
                    font_families_json,
                    ratios_json, spacings_json, relative_sizes_json, char_offsets_json,
                    border_fill_json,
                )
            }
            None => {
                format!(
                    concat!(
                        "{{\"fontFamily\":\"sans-serif\",\"fontSize\":1000,\"bold\":false,\"italic\":false,",
                        "\"underline\":false,\"underlineType\":\"None\",\"underlineColor\":\"#000000\",",
                        "\"strikethrough\":false,\"strikeColor\":\"#000000\",",
                        "\"textColor\":\"#000000\",\"shadeColor\":\"#ffffff\",",
                        "\"shadowType\":0,\"shadowColor\":\"#b2b2b2\",\"shadowOffsetX\":0,\"shadowOffsetY\":0,",
                        "\"outlineType\":0,",
                        "\"subscript\":false,\"superscript\":false,",
                        "\"emboss\":false,\"engrave\":false,",
                        "\"emphasisDot\":0,\"underlineShape\":0,\"strikeShape\":0,\"kerning\":false,",
                        "\"charShapeId\":{},",
                        "\"fontFamilies\":[\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\",\"sans-serif\"],",
                        "\"ratios\":[100,100,100,100,100,100,100],\"spacings\":[0,0,0,0,0,0,0],",
                        "\"relativeSizes\":[100,100,100,100,100,100,100],\"charOffsets\":[0,0,0,0,0,0,0],",
                        "\"borderFillId\":0,",
                        "\"borderLeft\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderRight\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderTop\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderBottom\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1",
                        "}}"
                    ),
                    char_shape_id
                )
            }
        }
    }

    /// 글자 테두리/배경 JSON 헬퍼 — CharShape의 border_fill_id를 참조하여 BorderFill 정보를 JSON 문자열로 반환
    pub(crate) fn build_char_border_fill_json(
        &self,
        raw_cs: Option<&crate::model::style::CharShape>,
    ) -> String {
        let bf_id = raw_cs.map(|s| s.border_fill_id).unwrap_or(0);
        if bf_id == 0 {
            return concat!(
                "\"borderFillId\":0,",
                "\"borderLeft\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                "\"borderRight\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                "\"borderTop\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                "\"borderBottom\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1"
            ).to_string();
        }
        let bf = self
            .document
            .doc_info
            .border_fills
            .get((bf_id - 1) as usize);
        match bf {
            Some(bf) => {
                let dir_names = ["Left", "Right", "Top", "Bottom"];
                let borders_json: Vec<String> = bf.borders.iter().enumerate().map(|(i, b)| {
                    format!(
                        "\"border{}\":{{\"type\":{},\"width\":{},\"color\":\"{}\"}}",
                        dir_names[i],
                        border_line_type_to_u8_val(b.line_type),
                        b.width,
                        color_ref_to_css(b.color),
                    )
                }).collect();
                let (fill_type_str, fill_color, pat_color, pat_type) = fill_json_values(&bf.fill);
                format!(
                    "\"borderFillId\":{},{},\"fillType\":\"{}\",\"fillColor\":\"{}\",\"patternColor\":\"{}\",\"patternType\":{}",
                    bf_id,
                    borders_json.join(","),
                    fill_type_str, fill_color, pat_color, pat_type,
                )
            }
            None => {
                concat!(
                    "\"borderFillId\":0,",
                    "\"borderLeft\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                    "\"borderRight\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                    "\"borderTop\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                    "\"borderBottom\":{\"type\":0,\"width\":0,\"color\":\"#000000\"},",
                    "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1"
                ).to_string()
            }
        }
    }

    /// 문단 속성 JSON 생성 헬퍼
    pub(crate) fn build_para_properties_json(&self, para_shape_id: u16, sec_idx: usize) -> String {
        use crate::model::style::{Alignment, HeadType};
        let ps = self.styles.para_styles.get(para_shape_id as usize);

        // 탭 정의 조회
        let raw_ps = self
            .document
            .doc_info
            .para_shapes
            .get(para_shape_id as usize);
        let tab_def_id = raw_ps.map(|p| p.tab_def_id).unwrap_or(0);
        let tab_def = self.document.doc_info.tab_defs.get(tab_def_id as usize);
        let tab_auto_left = tab_def.map(|td| td.auto_tab_left).unwrap_or(false);
        let tab_auto_right = tab_def.map(|td| td.auto_tab_right).unwrap_or(false);
        let tab_stops_json = tab_def
            .map(|td| {
                td.tabs
                    .iter()
                    .map(|t| {
                        format!(
                            "{{\"position\":{},\"type\":{},\"fill\":{}}}",
                            t.position, t.tab_type, t.fill_type
                        )
                    })
                    .collect::<Vec<_>>()
                    .join(",")
            })
            .unwrap_or_default();
        let default_tab_spacing = self
            .document
            .sections
            .get(sec_idx)
            .map(|s| s.section_def.default_tab_spacing)
            .unwrap_or(4000);

        // 테두리/배경 조회
        let bf_id = raw_ps.map(|p| p.border_fill_id).unwrap_or(0);
        let border_spacing = raw_ps.map(|p| p.border_spacing).unwrap_or([0; 4]);
        let border_fill_json = if bf_id > 0 {
            if let Some(bf) = self
                .document
                .doc_info
                .border_fills
                .get((bf_id - 1) as usize)
            {
                let dir_names = ["Left", "Right", "Top", "Bottom"];
                let borders: Vec<String> = bf
                    .borders
                    .iter()
                    .enumerate()
                    .map(|(i, b)| {
                        format!(
                            "\"border{}\":{{\"type\":{},\"width\":{},\"color\":\"{}\"}}",
                            dir_names[i],
                            border_line_type_to_u8_val(b.line_type),
                            b.width,
                            color_ref_to_css(b.color),
                        )
                    })
                    .collect();
                let (fill_type_str, fill_color, pat_color, pat_type) = fill_json_values(&bf.fill);
                format!(
                    "\"borderFillId\":{},{},\"fillType\":\"{}\",\"fillColor\":\"{}\",\"patternColor\":\"{}\",\"patternType\":{}",
                    bf_id, borders.join(","), fill_type_str, fill_color, pat_color, pat_type,
                )
            } else {
                format!(
                    concat!(
                        "\"borderFillId\":0,",
                        "\"borderLeft\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderRight\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderTop\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderBottom\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1"
                    )
                )
            }
        } else {
            format!(
                concat!(
                    "\"borderFillId\":0,",
                    "\"borderLeft\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                    "\"borderRight\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                    "\"borderTop\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                    "\"borderBottom\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                    "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1"
                )
            )
        };

        // [Task #1037 + para-unit regression] dialog 표시 한컴 정합:
        // - margin/indent 는 raw_ps 직접 사용 (variant_div 미적용)
        // - HWP3 native 만 raw margin_left 가 continuation 라인 position 이므로
        //   한컴 dialog "왼쪽 여백" 을 effective first-line position 으로 보정한다.
        // - HWP5/HWPX 및 HWP3→HWP5 변환본은 raw margin_left 가 dialog 의 왼쪽 여백 의미다.
        let (raw_left_hu, raw_right_hu, raw_indent_hu) = raw_ps
            .map(|r| (r.margin_left, r.margin_right, r.indent))
            .unwrap_or((0, 0, 0));
        // parser_architecture.md §47: 공통 편집 레이어에서 header.version 직접
        // 비교를 새로 만들지 않고 layout_profile() 질의로 판정한다.
        // `version.major==3 && !hwp3_layout()` 은 hwp3_native_layout() 과 동치다:
        // native HWP3 는 format=Hwp3·hwp3_lineage=false·major=3, 변환본은
        // format=Hwp5·hwp3_lineage=true·major=5 이므로 4개 출처 모두 결과가 같다.
        let is_hwp3_native = self.document.layout_profile().hwp3_native_layout();
        let effective_left_hu = if is_hwp3_native {
            raw_left_hu + raw_indent_hu.min(0)
        } else {
            raw_left_hu
        };
        // [Issue #1172] ParaShape margin/indent 의 IR 값은 2× 스케일이다
        // (HWP5 바이너리 원본 스케일, HWPX 도 parser 의 val2x 로 통일 — header.rs).
        // 즉 1pt = 200 HWPUNIT. 한컴 편집기 정답: para-001 margin 2000 → 10.0pt.
        // dialog 표시(px→pt by frontend pxToPt)와 정합하려면 표준 hwpunit_to_px(7200/inch,
        // 1× 가정) 적용 전에 2× 스케일을 1× 로 환산(÷2)해야 한다. (종전: ÷2 누락 → 2배 표시)
        let dialog_margin_left_px = crate::renderer::hwpunit_to_px(effective_left_hu / 2, self.dpi);
        let dialog_margin_right_px = crate::renderer::hwpunit_to_px(raw_right_hu / 2, self.dpi);
        let dialog_indent_px = crate::renderer::hwpunit_to_px(raw_indent_hu / 2, self.dpi);

        match ps {
            Some(ps) => {
                let align_str = match ps.alignment {
                    Alignment::Justify => "justify",
                    Alignment::Left => "left",
                    Alignment::Right => "right",
                    Alignment::Center => "center",
                    Alignment::Distribute => "distribute",
                    Alignment::Split => "split",
                };
                let head_str = match ps.head_type {
                    HeadType::None => "None",
                    HeadType::Outline => "Outline",
                    HeadType::Number => "Number",
                    HeadType::Bullet => "Bullet",
                };
                // 원본 ParaShape에서 attr 비트 추출
                let (a1, a2) = raw_ps.map(|r| (r.attr1, r.attr2)).unwrap_or((0, 0));
                // #2777 정본: breakSetting은 attr1 16-19, autoSpacing은 attr2 4/5.
                let widow_orphan = (a1 >> 16) & 1 != 0;
                let keep_with_next = (a1 >> 17) & 1 != 0;
                let keep_lines = (a1 >> 18) & 1 != 0;
                let page_break_before = (a1 >> 19) & 1 != 0;
                let font_line_height = (a1 >> 22) & 1 != 0;
                let single_line = (a2 & 0x03) != 0;
                let auto_space_kr_en = (a2 >> 4) & 1 != 0;
                let auto_space_kr_num = (a2 >> 5) & 1 != 0;
                let vertical_align = (a1 >> 20) & 0x03;
                let english_break_unit = (a1 >> 5) & 0x03;
                let korean_break_unit = (a1 >> 7) & 0x01;
                let border_connect = (a1 >> 28) & 1 != 0;
                let border_ignore_margin = (a1 >> 29) & 1 != 0;
                format!(
                    concat!(
                        "{{\"alignment\":\"{}\",\"lineSpacing\":{:.1},\"lineSpacingType\":\"{:?}\",",
                        "\"marginLeft\":{:.1},\"marginRight\":{:.1},\"indent\":{:.1},",
                        "\"spacingBefore\":{:.1},\"spacingAfter\":{:.1},\"paraShapeId\":{},",
                        "\"headType\":\"{}\",\"paraLevel\":{},\"numberingId\":{},",
                        "\"widowOrphan\":{},\"keepWithNext\":{},\"keepLines\":{},\"pageBreakBefore\":{},",
                        "\"fontLineHeight\":{},\"singleLine\":{},",
                        "\"autoSpaceKrEn\":{},\"autoSpaceKrNum\":{},\"verticalAlign\":{},",
                        "\"englishBreakUnit\":{},\"koreanBreakUnit\":{},",
                        "\"tabAutoLeft\":{},\"tabAutoRight\":{},\"tabStops\":[{}],\"defaultTabSpacing\":{},",
                        "{},\"borderSpacing\":[{},{},{},{}],",
                        "\"borderConnect\":{},\"borderIgnoreMargin\":{}}}"
                    ),
                    align_str,
                    ps.line_spacing, ps.line_spacing_type,
                    dialog_margin_left_px, dialog_margin_right_px, dialog_indent_px,
                    // spacing_before/after는 원본 HWPUNIT → px (1x) 변환 (Task #9)
                    // ResolvedParaStyle은 /2.0이 적용되어 UI 표시에 부적합
                    raw_ps.map(|r| crate::renderer::hwpunit_to_px(r.spacing_before, self.dpi)).unwrap_or(ps.spacing_before),
                    raw_ps.map(|r| crate::renderer::hwpunit_to_px(r.spacing_after, self.dpi)).unwrap_or(ps.spacing_after),
                    para_shape_id,
                    head_str, ps.para_level, ps.numbering_id,
                    widow_orphan, keep_with_next, keep_lines, page_break_before,
                    font_line_height, single_line,
                    auto_space_kr_en, auto_space_kr_num, vertical_align,
                    english_break_unit, korean_break_unit,
                    tab_auto_left, tab_auto_right, tab_stops_json, default_tab_spacing,
                    border_fill_json,
                    border_spacing[0], border_spacing[1], border_spacing[2], border_spacing[3],
                    border_connect, border_ignore_margin,
                )
            }
            None => {
                format!(
                    concat!(
                        "{{\"alignment\":\"justify\",\"lineSpacing\":160.0,\"lineSpacingType\":\"Percent\",",
                        "\"marginLeft\":0.0,\"marginRight\":0.0,\"indent\":0.0,",
                        "\"spacingBefore\":0.0,\"spacingAfter\":0.0,\"paraShapeId\":{},",
                        "\"headType\":\"None\",\"paraLevel\":0,\"numberingId\":0,",
                        "\"widowOrphan\":false,\"keepWithNext\":false,\"keepLines\":false,\"pageBreakBefore\":false,",
                        "\"fontLineHeight\":false,\"singleLine\":false,",
                        "\"autoSpaceKrEn\":false,\"autoSpaceKrNum\":false,\"verticalAlign\":0,",
                        "\"englishBreakUnit\":0,\"koreanBreakUnit\":0,",
                        "\"tabAutoLeft\":false,\"tabAutoRight\":false,\"tabStops\":[],\"defaultTabSpacing\":{},",
                        "\"borderFillId\":0,",
                        "\"borderLeft\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderRight\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderTop\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"borderBottom\":{{\"type\":0,\"width\":0,\"color\":\"#000000\"}},",
                        "\"fillType\":\"none\",\"fillColor\":\"#ffffff\",\"patternColor\":\"#000000\",\"patternType\":-1,",
                        "\"borderSpacing\":[0,0,0,0],",
                        "\"borderConnect\":false,\"borderIgnoreMargin\":false}}"
                    ),
                    para_shape_id, default_tab_spacing
                )
            }
        }
    }

    /// 글꼴 이름으로 font_id를 조회하거나 새로 생성한다 (네이티브).
    pub fn find_or_create_font_id_native(&mut self, name: &str) -> i32 {
        let font_faces = &self.document.doc_info.font_faces;

        // 한글(0번) 카테고리에서 검색
        if !font_faces.is_empty() {
            for (idx, font) in font_faces[0].iter().enumerate() {
                if font.name == name {
                    return idx as i32;
                }
            }
        }

        // 없으면 7개 전체 카테고리에 동일 이름으로 신규 등록
        let new_font = crate::model::style::Font {
            raw_data: None,
            name: name.to_string(),
            alt_type: 0,
            is_embedded: false,
            bin_item_id_ref: String::new(),
            resolved_bin_data_id: None,
            alt_name: None,
            type_info: None,
            default_name: None,
            subst_font: None,
            native_program: None,
        };

        let font_faces = &mut self.document.doc_info.font_faces;
        // font_faces가 7개 미만이면 확장
        while font_faces.len() < 7 {
            font_faces.push(Vec::new());
        }

        let new_id = font_faces[0].len();
        for lang in 0..7 {
            font_faces[lang].push(new_font.clone());
        }

        // raw_stream 보존: 7개 언어 카테고리에 FACE_NAME surgical insert
        if let Some(ref mut raw) = self.document.doc_info.raw_stream {
            let face_data = crate::serializer::doc_info::serialize_face_name(&new_font);
            let _ = crate::serializer::doc_info::surgical_insert_font_all_langs(raw, &face_data);
        }
        new_id as i32
    }

    /// 특정 언어 카테고리에서 글꼴 이름으로 ID를 찾거나, 없으면 해당 카테고리에만 등록한다.
    pub fn find_or_create_font_id_for_lang(&mut self, lang: usize, name: &str) -> i32 {
        if lang >= 7 {
            return -1;
        }
        let font_faces = &self.document.doc_info.font_faces;
        if font_faces.len() <= lang {
            return -1;
        }

        // 해당 언어 카테고리에서 검색
        for (idx, font) in font_faces[lang].iter().enumerate() {
            if font.name == name {
                return idx as i32;
            }
        }

        // 없으면 해당 카테고리에만 등록 (다른 언어 카테고리 font_faces 길이 맞추기)
        let new_font = crate::model::style::Font {
            raw_data: None,
            name: name.to_string(),
            alt_type: 0,
            is_embedded: false,
            bin_item_id_ref: String::new(),
            resolved_bin_data_id: None,
            alt_name: None,
            type_info: None,
            default_name: None,
            subst_font: None,
            native_program: None,
        };

        let font_faces = &mut self.document.doc_info.font_faces;
        while font_faces.len() < 7 {
            font_faces.push(Vec::new());
        }

        // 모든 카테고리의 길이를 맞추기 위해 전체에 등록
        let new_id = font_faces[lang].len();
        for l in 0..7 {
            if l == lang {
                font_faces[l].push(new_font.clone());
            } else {
                // 다른 카테고리에는 placeholder 등록 (길이 동기화)
                let placeholder = if !font_faces[l].is_empty() {
                    // 첫 번째 폰트를 복제 (기본 글꼴)
                    font_faces[l][0].clone()
                } else {
                    new_font.clone()
                };
                font_faces[l].push(placeholder);
            }
        }

        // raw_stream 보존
        if let Some(ref mut raw) = self.document.doc_info.raw_stream {
            let face_data = crate::serializer::doc_info::serialize_face_name(&new_font);
            let _ = crate::serializer::doc_info::surgical_insert_font_all_langs(raw, &face_data);
        }
        new_id as i32
    }

    /// 글자 서식의 `fontName`(글꼴 이름)을 언어 슬롯별 `font_ids` 로 풀어 `mods` 에 넣는다.
    ///
    /// 호출자가 글꼴 ID 를 미리 알 수 없는 경우(CLI·에이전트)를 위한 축이다. 이름이 문서에 없으면
    /// HTML 붙여넣기와 같은 `find_or_register_font_ids` 로 슬롯마다 등록하고, 등록이 일어나면
    /// DocInfo 패스스루(`raw_stream`)를 무효화해 저장본에 새 글꼴이 실리게 한다.
    /// `fontId`·`fontIds` 와 함께 주면 어느 쪽이 이길지 모호하므로 오류로 돌린다.
    pub(crate) fn resolve_font_name_mods(
        &mut self,
        mods: &mut crate::model::style::CharShapeMods,
    ) -> Result<(), HwpError> {
        let Some(name) = mods.font_name.take() else {
            return Ok(());
        };
        if mods.font_id.is_some() || mods.font_ids.is_some() {
            return Err(HwpError::RenderError(
                "fontName 은 fontId·fontIds 와 함께 쓸 수 없음".to_string(),
            ));
        }
        let before: Vec<usize> = self
            .document
            .doc_info
            .font_faces
            .iter()
            .map(|slot| slot.len())
            .collect();
        let ids = self.find_or_register_font_ids(&name).ok_or_else(|| {
            HwpError::RenderError(format!("글꼴 이름을 등록할 수 없음: {}", name.trim()))
        })?;
        let after = self
            .document
            .doc_info
            .font_faces
            .iter()
            .map(|slot| slot.len());
        if !after.eq(before.iter().copied()) {
            self.document.doc_info.raw_stream_dirty = true;
        }
        mods.font_ids = Some(ids);
        Ok(())
    }

    /// 글자 서식 적용 (네이티브) — 본문 문단
    pub fn apply_char_format_native(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        if sec_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)));
        }
        if para_idx >= self.document.sections[sec_idx].paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        }

        let mut mods = parse_char_shape_mods(props_json);
        self.resolve_font_name_mods(&mut mods)?;
        // border/fill JSON이 있으면 BorderFill 생성/재사용하여 border_fill_id 설정
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }
        let stored_end = paragraph_flow_end(&self.document.sections[sec_idx].paragraphs[para_idx]);
        self.apply_char_mods_to_paragraph(sec_idx, para_idx, start_offset, end_offset, &mods)?;

        // 텍스트 폭/높이에 영향을 주는 글자 모양 변경 시 LineSeg 재계산.
        // 장평/자간은 글꼴 크기처럼 줄나눔과 페이지네이션을 바꾼다.
        if char_shape_mods_affect_text_flow(&mods) {
            let styles = self.resolve_render_styles();
            let section = &self.document.sections[sec_idx];
            let page_def = &section.section_def.page_def;
            let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
            let layout = PageLayoutInfo::from_page_def(page_def, &column_def, self.dpi);
            let col_width = layout
                .column_areas
                .first()
                .map(|a| a.width)
                .unwrap_or(layout.body_area.width);
            let para_shape_id = self.document.sections[sec_idx].paragraphs[para_idx].para_shape_id;
            let para_style = styles.para_styles.get(para_shape_id as usize);
            // 본문: 열 상자.
            let paragraph_box = ParagraphBox::body_for_style(col_width, para_style, self.dpi);
            // Preserve the saved first-row origin while replacing the composed rows.
            reflow_line_segs(
                &mut self.document.sections[sec_idx].paragraphs[para_idx],
                paragraph_box,
                &styles,
                self.dpi,
            );
            self.fit_cell_grid(sec_idx, para_idx, &styles);
            let hwp3 = self.document.layout_profile().hwp3_layout();
            recalculate_section_vpos(
                &mut self.document.sections[sec_idx].paragraphs,
                para_idx,
                None,
                stored_end,
                &styles,
                self.dpi,
                hwp3,
            );
        }

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_paragraph_deferred_in_batch(sec_idx, para_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 글자 서식 ID 직접 복원 (네이티브) — 본문 문단.
    ///
    /// Undo/Redo에서는 `CharProperties` JSON을 다시 적용하지 않고, 적용 전/후
    /// `char_shape_id`를 직접 복원한다. 조회 JSON은 UI 상태 표현용 값이 섞여
    /// 있으므로 history 복원 payload로 재해석하지 않는다.
    pub fn set_char_shape_id_native(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        char_shape_id: u32,
    ) -> Result<String, HwpError> {
        if sec_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)));
        }
        if para_idx >= self.document.sections[sec_idx].paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        }
        if char_shape_id as usize >= self.document.doc_info.char_shapes.len() {
            return Err(HwpError::RenderError(format!(
                "글자 모양 ID {} 범위 초과 (총 {}개)",
                char_shape_id,
                self.document.doc_info.char_shapes.len()
            )));
        }

        let stored_end = paragraph_flow_end(&self.document.sections[sec_idx].paragraphs[para_idx]);
        let styles = self.resolve_render_styles();
        let available_box = {
            let section = &self.document.sections[sec_idx];
            let page_def = &section.section_def.page_def;
            let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
            let layout = PageLayoutInfo::from_page_def(page_def, &column_def, self.dpi);
            let col_width = layout
                .column_areas
                .first()
                .map(|a| a.width)
                .unwrap_or(layout.body_area.width);
            let para_shape_id = section.paragraphs[para_idx].para_shape_id;
            let para_style = styles.para_styles.get(para_shape_id as usize);
            // 본문: 열 상자.
            ParagraphBox::body_for_style(col_width, para_style, self.dpi)
        };

        {
            let para = &mut self.document.sections[sec_idx].paragraphs[para_idx];
            para.apply_char_shape_range(start_offset, end_offset, char_shape_id);
            reflow_line_segs(para, available_box, &styles, self.dpi);
        }
        self.fit_cell_grid(sec_idx, para_idx, &styles);
        let hwp3 = self.document.layout_profile().hwp3_layout();
        recalculate_section_vpos(
            &mut self.document.sections[sec_idx].paragraphs,
            para_idx,
            None,
            stored_end,
            &styles,
            self.dpi,
            hwp3,
        );

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_paragraph_deferred_in_batch(sec_idx, para_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 서식 뮤테이터의 파생 재계산 꼬리 — 배치 여부에 따라 재구성·재페이지네이션을
    /// 지연하거나 즉시 전체 rebuild 로 마친다.
    ///
    /// 배치 중(`begin_batch`~`end_batch`)에는 재구성·재페이지네이션을 `end_batch_native`
    /// 의 paginate() 1회로 미루고 구역만 dirty 로 표시한다 — 셀 텍스트 편집의 지연
    /// 계약(#2424)과 같은 모양이다. 셀 문단은 composed 에 없으므로 재구성 없이 flush
    /// 시점 재처리로 충분하다(본문 문단은 `rebuild_paragraph_deferred_in_batch`).
    /// 새 서식 id 가 doc_info 에 추가됐을 수 있으므로 스타일 해석만 즉시 갱신한다
    /// (O(스타일 수) — 재조판 비용과 무관).
    /// 배치 밖에서는 종전대로 전체 rebuild 이다(#4118).
    ///
    /// 패스스루(raw_stream) 무효화는 #2724 가드가 뮤테이터 본문의 직접 토큰을 요구하므로
    /// 호출자가 하고, 이 헬퍼는 파생 상태 정리만 소유한다.
    pub(crate) fn rebuild_section_deferred_in_batch(&mut self, sec_idx: usize) {
        if self.batch_mode {
            self.rebuild_resolved_styles();
            self.styles.supplemental_metrics = self
                .canvas_metrics
                .as_ref()
                .and_then(super::super::canvas_metrics::CanvasMetricSession::active_snapshot);
            self.mark_section_dirty(sec_idx);
        } else {
            self.rebuild_section(sec_idx);
        }
    }

    /// 본문 문단 서식 뮤테이터의 꼬리 — `rebuild_section_deferred_in_batch` 와 같되,
    /// 배치 중에는 그 문단을 바로 다시 조합한다.
    ///
    /// 본문 문단은 셀과 달리 composed 에 글자 모양 런을 들고 있다. 다시 조합하지 않으면
    /// `end_batch` 의 paginate 가 옛 런으로 재고 그린다. 배치 밖에서는 전체 rebuild 가
    /// 구역을 다시 조합하므로 따로 할 일이 없다.
    pub(crate) fn rebuild_paragraph_deferred_in_batch(&mut self, sec_idx: usize, para_idx: usize) {
        self.rebuild_section_deferred_in_batch(sec_idx);
        if self.batch_mode {
            self.recompose_paragraph(sec_idx, para_idx);
        }
    }

    /// 글자 서식 적용 (네이티브) — 셀 내 문단
    pub fn apply_char_format_in_cell_native(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        // 실패한 주소는 글꼴·테두리를 등록하기 전에 거부한다.
        let base_ids = self
            .get_cell_paragraph_ref(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )
            .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?
            .char_shape_ids_in_range(start_offset, end_offset);
        let mut mods = parse_char_shape_mods(props_json);
        self.resolve_font_name_mods(&mut mods)?;
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }

        // 선택 안의 원본 모양 각각에 속성을 병합한다.
        {
            let ids = self.document.modified_char_shape_ids(base_ids, &mods);

            // 셀 문단에 범위 적용
            let cell_para = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            cell_para.try_map_char_shape_range(start_offset, end_offset, |id| {
                ids.get(&id)
                    .copied()
                    .ok_or_else(|| HwpError::RenderError(format!("글자 모양 변환 ID {id} 누락")))
            })?;
        }

        // 텍스트 폭/높이에 영향을 주는 글자 모양 변경 시 셀 내 LineSeg 재계산.
        //
        // [자체 발견] 예전에는 여기서 페이지 본문 단(column) 폭을 셀 리플로우에 그대로
        // 썼다 — 셀 폭은 보통 그 1/3~1/5 라 텍스트가 한 줄로 뭉쳐졌다 붙었다 하며 셀
        // 경계를 넘어 그려졌다. 같은 파일의 undo 형제 set_char_shape_id_in_cell_native
        // (:1219)는 이미 reflow_cell_paragraph 로 셀/글상자/캡션 폭을 올바르게 계산해서,
        // 서식 적용(do)과 undo 사이에 눈에 보이는 비대칭이 있었다. 그 헬퍼로 통일한다.
        if char_shape_mods_affect_text_flow(&mods) {
            self.reflow_cell_paragraph(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            );
            self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);
            // [#7265] 리플로우가 이 문단의 줄 수·높이를 바꿨으면 **후속 문단의 사다리도**
            // 다시 세워야 한다. 종전에는 이 표시가 없어 글자 크기를 키우면 문단이 두 줄이
            // 되는데 다음 문단은 옛 vpos 에 남아 글자가 포개졌다.
            //
            // #6639 가 문단모양 경로에 세운 지연 기구를 그대로 쓴다 — 저장 RowBreak
            // 원점을 보존하고 배치 경계에서 조각마다 한 번만 돌기 때문이다. 여기서
            // 곧바로 재계산하면 그 원점 보존 계약이 깨진다.
            if let Ok(cell_para) = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            ) {
                cell_para.cell_format_vpos_dirty = true;
            }
            self.pending_cell_format_vpos = true;
        }

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// `applyCharFormatInCell` 의 cellPath 변형 (중첩 표 지원).
    ///
    /// flat 변형은 controlIndex/cellIndex 를 최외곽(cellPath[0]) 축으로 받아 중첩 셀에서
    /// 바깥 셀에 서식을 적용한다. 이 변형은 path 로 최내곽 셀 문단을 해석해 적용하고,
    /// 셀별 리플로우는 rebuild_section 의 전체 재조판이 담당한다(delete_range_in_cell_by_path 동형).
    #[allow(clippy::too_many_arguments)]
    pub fn apply_char_format_in_cell_by_path(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        start_offset: usize,
        end_offset: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        // [#2755] 깊이 1 셀은 flat 형제가 셀 폭 리플로우(paint-only 게이팅 포함)를 담당한다.
        // `apply_char_format_in_cell_native`(:1103)는 char_shape_mods_affect_text_flow 로
        // 게이팅한 뒤에만 reflow_cell_paragraph 를 호출하므로 밑줄/색 변경은 리플로우하지 않는다.
        if path.len() == 1 {
            let (control_idx, cell_idx, cell_para_idx) = path[0];
            return self.apply_char_format_in_cell_native(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
                start_offset,
                end_offset,
                props_json,
            );
        }

        let base_ids = {
            let para = self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path)?;
            para.char_shape_ids_in_range(start_offset, end_offset)
        };
        let mut mods = parse_char_shape_mods(props_json);
        self.resolve_font_name_mods(&mut mods)?;
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }
        let ids = self.document.modified_char_shape_ids(base_ids, &mods);
        {
            let para = self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path)?;
            para.try_map_char_shape_range(start_offset, end_offset, |id| {
                ids.get(&id)
                    .copied()
                    .ok_or_else(|| HwpError::RenderError(format!("글자 모양 변환 ID {id} 누락")))
            })?;
        }
        // [#2755] 깊이 ≥ 2 중첩 셀도 텍스트 흐름에 영향 주는 변경 시 최내곽 셀 폭으로 재래핑한다
        // (apply_char_format_in_cell_native 의 char_shape_mods_affect_text_flow 게이팅과 동형 —
        // 밑줄/색 등 paint-only 변경은 여기서도 리플로우하지 않는다).
        if char_shape_mods_affect_text_flow(&mods) {
            let inner_cpi = path.last().map(|e| e.2).unwrap_or(0);
            self.reflow_cell_paragraph_by_path(sec_idx, parent_para_idx, path, inner_cpi);
            // [#7265] 리플로우가 줄 수·높이를 바꿨으면 후속 문단 사다리도 다시 세운다.
            // #6639 의 지연 기구를 그대로 쓴다 — 저장 RowBreak 원점을 보존하고
            // 배치 경계에서 조각마다 한 번만 돈다.
            if let Ok(cell_para) =
                self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path)
            {
                cell_para.cell_format_vpos_dirty = true;
            }
            self.pending_cell_format_vpos = true;
        }
        let outer_ctrl = path[0].0;
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, outer_ctrl);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// `getCellCharPropertiesAt` 의 cellPath 변형. 커맨드는 charShapeId 만 쓰므로
    /// shape 기준 속성(build_char_properties_json_by_id)으로 충분하다.
    pub fn get_cell_char_properties_at_by_path(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        char_offset: usize,
    ) -> Result<String, HwpError> {
        let char_shape_id = {
            let para = self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path)?;
            para.char_shape_id_at(char_offset).unwrap_or(0)
        };
        Ok(self.build_char_properties_json_by_id(char_shape_id as u16))
    }

    /// `setCharShapeIdInCell` 의 cellPath 변형 (중첩 표 지원, undo용).
    #[allow(clippy::too_many_arguments)]
    pub fn set_char_shape_id_in_cell_by_path(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        start_offset: usize,
        end_offset: usize,
        char_shape_id: u32,
    ) -> Result<String, HwpError> {
        // [#2755] 깊이 1 셀은 flat 형제가 셀 폭 리플로우를 담당한다.
        // `set_char_shape_id_in_cell_native`(:1268)는 (복원 대상 모양의 내용을 알 수 없으므로)
        // 무조건 reflow_cell_paragraph 를 호출한다. undo 복원 경로의 do/undo 대칭을 지킨다.
        if path.len() == 1 {
            let (control_idx, cell_idx, cell_para_idx) = path[0];
            return self.set_char_shape_id_in_cell_native(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
                start_offset,
                end_offset,
                char_shape_id,
            );
        }

        if char_shape_id as usize >= self.document.doc_info.char_shapes.len() {
            return Err(HwpError::RenderError(format!(
                "글자 모양 ID {} 범위 초과 (총 {}개)",
                char_shape_id,
                self.document.doc_info.char_shapes.len()
            )));
        }
        {
            let cell_para = self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path)?;
            cell_para.apply_char_shape_range(start_offset, end_offset, char_shape_id);
        }
        // [#2755] 깊이 ≥ 2 중첩 셀도 최내곽 셀 폭으로 재래핑한다(복원 대상 모양의 내용을 알 수
        // 없으므로 flat set_char_shape_id_in_cell_native 처럼 무조건).
        let inner_cpi = path.last().map(|e| e.2).unwrap_or(0);
        self.reflow_cell_paragraph_by_path(sec_idx, parent_para_idx, path, inner_cpi);
        // [#7265] 리플로우가 줄 수·높이를 바꿨으면 후속 문단 사다리도 다시 세운다.
        // #6639 의 지연 기구를 그대로 쓴다 — 저장 RowBreak 원점을 보존하고
        // 배치 경계에서 조각마다 한 번만 돈다.
        if let Ok(cell_para) = self.get_cell_paragraph_mut_by_path(sec_idx, parent_para_idx, path) {
            cell_para.cell_format_vpos_dirty = true;
        }
        self.pending_cell_format_vpos = true;
        let outer_ctrl = path[0].0;
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, outer_ctrl);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 글자 서식 ID 직접 복원 (네이티브) — 셀 내 문단.
    pub fn set_char_shape_id_in_cell_native(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        char_shape_id: u32,
    ) -> Result<String, HwpError> {
        if char_shape_id as usize >= self.document.doc_info.char_shapes.len() {
            return Err(HwpError::RenderError(format!(
                "글자 모양 ID {} 범위 초과 (총 {}개)",
                char_shape_id,
                self.document.doc_info.char_shapes.len()
            )));
        }

        {
            let cell_para = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            cell_para.apply_char_shape_range(start_offset, end_offset, char_shape_id);
        }

        self.reflow_cell_paragraph(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        );
        // [#7265] 리플로우가 줄 수·높이를 바꿨으면 후속 문단 사다리도 다시 세운다.
        // #6639 의 지연 기구를 그대로 쓴다 — 저장 RowBreak 원점을 보존하고
        // 배치 경계에서 조각마다 한 번만 돈다.
        if let Ok(cell_para) = self.get_cell_paragraph_mut(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        ) {
            cell_para.cell_format_vpos_dirty = true;
        }
        self.pending_cell_format_vpos = true;
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::CharFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
            start: start_offset,
            end: end_offset,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 문단 서식 적용 (네이티브) — 본문 문단
    pub fn apply_para_format_native(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        if sec_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)));
        }
        if para_idx >= self.document.sections[sec_idx].paragraphs.len() {
            if let Some(src) = self.virtual_endnote_para_source(sec_idx, para_idx) {
                return self.apply_para_format_in_footnote_native(
                    src.section_index,
                    src.para_index,
                    src.control_index,
                    src.note_para_index,
                    props_json,
                );
            }
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        }

        let mut mods = parse_para_shape_mods(props_json);

        // 탭 설정 변경 처리: TabDef 생성 → tab_def_id 세팅
        if json_has_tab_keys(props_json) {
            let base_id = self.document.sections[sec_idx].paragraphs[para_idx].para_shape_id;
            let base_tab_def_id = self
                .document
                .doc_info
                .para_shapes
                .get(base_id as usize)
                .map(|ps| ps.tab_def_id)
                .unwrap_or(0);
            let new_td = build_tab_def_from_json(
                props_json,
                base_tab_def_id,
                &self.document.doc_info.tab_defs,
            );
            let new_tab_id = self.document.find_or_create_tab_def(new_td);
            mods.tab_def_id = Some(new_tab_id);
        }

        // 테두리/배경 변경 처리: BorderFill 생성 → border_fill_id 세팅
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }
        if let Some(arr) = parse_json_i16_array(props_json, "borderSpacing", 4) {
            mods.border_spacing = Some([arr[0], arr[1], arr[2], arr[3]]);
        }

        let base_id = self.document.sections[sec_idx].paragraphs[para_idx].para_shape_id;
        let new_id = self.document.find_or_create_para_shape(base_id, &mods);
        let marker_changed = marker_shape_changed(
            &self.document.doc_info.para_shapes[base_id as usize],
            &self.document.doc_info.para_shapes[new_id as usize],
        );
        let (old_indent, new_indent) = self.para_shape_indents(base_id, new_id);
        let para = &mut self.document.sections[sec_idx].paragraphs[para_idx];
        para.para_shape_id = new_id;
        restamp_indentation(&mut para.line_segs, old_indent, new_indent);
        let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
            &self.document.sections[sec_idx].paragraphs[para_idx],
        );
        // 이전 머리 배치는 새 줄을 생산하기 전에 무효화한다.
        // 재조판 후의 bit 21·줄 분할은 유효한 저장 결과로 남긴다.
        if marker_changed {
            self.document.sections[sec_idx].paragraphs[para_idx].invalidate_layout_inputs();
        }

        // 줄바꿈에 영향을 주는 변경 시 LineSeg 재계산 (compose는 LineSeg 값을 그대로
        // 사용하므로). 줄간격뿐 아니라 여백/들여쓰기/줄나눔 단위도 사용 가능 폭·토큰
        // 경계를 바꾼다 — [#4324] para_shape_mods_affect_text_flow(:16 부근) 참고.
        if para_shape_mods_affect_text_flow(&mods) {
            let styles = self.resolve_render_styles();
            let section = &self.document.sections[sec_idx];
            let page_def = &section.section_def.page_def;
            let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
            let layout = PageLayoutInfo::from_page_def(page_def, &column_def, self.dpi);
            let col_width = layout
                .column_areas
                .first()
                .map(|a| a.width)
                .unwrap_or(layout.body_area.width);
            let para_style = styles.para_styles.get(new_id as usize);
            // 본문: 열 상자.
            reflow_line_segs(
                &mut self.document.sections[sec_idx].paragraphs[para_idx],
                ParagraphBox::body_for_style(col_width, para_style, self.dpi),
                &styles,
                self.dpi,
            );
            self.fit_cell_grid(sec_idx, para_idx, &styles);
        }

        // 문단 간격은 줄 나눔을 바꾸지 않지만 이 문단과 뒤 문단의 저장 세로 위치를 옮긴다.
        // 다시 계산하지 않으면 편집 전 세로 위치로 그려 간격이 보이지 않는다.
        if para_shape_mods_affect_text_flow(&mods)
            || mods.spacing_before.is_some()
            || mods.spacing_after.is_some()
        {
            let styles = self.resolve_render_styles();
            let hwp3_layout = self.document.layout_profile().hwp3_layout();
            crate::renderer::composer::recalculate_section_vpos(
                &mut self.document.sections[sec_idx].paragraphs,
                para_idx,
                None,
                stored_end_for_reset,
                &styles,
                self.dpi,
                hwp3_layout,
            );
        }

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 문단 서식 ID 직접 복원 (네이티브) — 본문 문단.
    ///
    /// Undo/Redo에서는 `ParaProperties` JSON을 다시 적용하지 않고, 적용 전/후
    /// `para_shape_id`를 직접 복원한다. 조회 JSON은 UI용 px 단위가 섞여 있어
    /// raw 값을 기대하는 apply parser에 재투입하면 단위가 깨질 수 있다.
    pub fn set_para_shape_id_native(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        para_shape_id: u16,
    ) -> Result<String, HwpError> {
        if sec_idx >= self.document.sections.len() {
            return Err(HwpError::RenderError(format!("구역 {} 범위 초과", sec_idx)));
        }
        if para_idx >= self.document.sections[sec_idx].paragraphs.len() {
            return Err(HwpError::RenderError(format!(
                "문단 {} 범위 초과",
                para_idx
            )));
        }
        if para_shape_id as usize >= self.document.doc_info.para_shapes.len() {
            return Err(HwpError::RenderError(format!(
                "문단 모양 ID {} 범위 초과 (총 {}개)",
                para_shape_id,
                self.document.doc_info.para_shapes.len()
            )));
        }

        let old_id = self.document.sections[sec_idx].paragraphs[para_idx].para_shape_id;
        let marker_changed = marker_shape_changed(
            &self.document.doc_info.para_shapes[old_id as usize],
            &self.document.doc_info.para_shapes[para_shape_id as usize],
        );
        let styles = self.resolve_render_styles();
        let available_box = {
            let section = &self.document.sections[sec_idx];
            let page_def = &section.section_def.page_def;
            let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
            let layout = PageLayoutInfo::from_page_def(page_def, &column_def, self.dpi);
            let col_width = layout
                .column_areas
                .first()
                .map(|a| a.width)
                .unwrap_or(layout.body_area.width);
            let para_style = styles.para_styles.get(para_shape_id as usize);
            // 본문: 열 상자.
            ParagraphBox::body_for_style(col_width, para_style, self.dpi)
        };

        let stored_end_for_reset = {
            let old_id = self.document.sections[sec_idx].paragraphs[para_idx].para_shape_id;
            let (old_indent, new_indent) = self.para_shape_indents(old_id, para_shape_id);
            let para = &mut self.document.sections[sec_idx].paragraphs[para_idx];
            let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(para);
            para.para_shape_id = para_shape_id;
            restamp_indentation(&mut para.line_segs, old_indent, new_indent);
            if marker_changed {
                para.invalidate_layout_inputs();
            }
            reflow_line_segs(para, available_box, &styles, self.dpi);
            stored_end_for_reset
        };
        self.fit_cell_grid(sec_idx, para_idx, &styles);
        // 되돌린 문단 간격도 이 문단과 뒤 문단의 저장 세로 위치에 반영한다.
        let hwp3_layout = self.document.layout_profile().hwp3_layout();
        crate::renderer::composer::recalculate_section_vpos(
            &mut self.document.sections[sec_idx].paragraphs,
            para_idx,
            None,
            stored_end_for_reset,
            &styles,
            self.dpi,
            hwp3_layout,
        );

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 문단 서식 적용 (네이티브) — 셀 내 문단
    pub fn apply_para_format_in_cell_native(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        props_json: &str,
    ) -> Result<String, HwpError> {
        let mut mods = parse_para_shape_mods(props_json);

        // 탭 설정 변경 처리: TabDef 생성 → tab_def_id 세팅
        if json_has_tab_keys(props_json) {
            let para = self
                .get_cell_paragraph_ref(
                    sec_idx,
                    parent_para_idx,
                    control_idx,
                    cell_idx,
                    cell_para_idx,
                )
                .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?;
            let base_tab_def_id = self
                .document
                .doc_info
                .para_shapes
                .get(para.para_shape_id as usize)
                .map(|ps| ps.tab_def_id)
                .unwrap_or(0);
            let new_td = build_tab_def_from_json(
                props_json,
                base_tab_def_id,
                &self.document.doc_info.tab_defs,
            );
            let new_tab_id = self.document.find_or_create_tab_def(new_td);
            mods.tab_def_id = Some(new_tab_id);
        }

        // 테두리/배경 변경 처리: BorderFill 생성 → border_fill_id 세팅
        if json_has_border_keys(props_json) {
            let bf_id = self.create_border_fill_from_json(props_json);
            mods.border_fill_id = Some(bf_id);
        }
        if let Some(arr) = parse_json_i16_array(props_json, "borderSpacing", 4) {
            mods.border_spacing = Some([arr[0], arr[1], arr[2], arr[3]]);
        }

        let affects_vpos;
        let marker_changed;
        {
            let para = self
                .get_cell_paragraph_ref(
                    sec_idx,
                    parent_para_idx,
                    control_idx,
                    cell_idx,
                    cell_para_idx,
                )
                .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?;
            let base_id = para.para_shape_id;
            let new_id = self.document.find_or_create_para_shape(base_id, &mods);
            affects_vpos = self
                .document
                .doc_info
                .para_shapes
                .get(base_id as usize)
                .is_none_or(|old| {
                    cell_para_shape_affects_vpos(
                        old,
                        &self.document.doc_info.para_shapes[new_id as usize],
                    )
                });
            marker_changed = marker_shape_changed(
                &self.document.doc_info.para_shapes[base_id as usize],
                &self.document.doc_info.para_shapes[new_id as usize],
            );
            let (old_indent, new_indent) = self.para_shape_indents(base_id, new_id);
            self.restamp_cell_format_origin(
                (
                    sec_idx,
                    parent_para_idx,
                    control_idx,
                    cell_idx,
                    cell_para_idx,
                ),
                base_id,
                new_id,
            )?;

            let cell_para = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            cell_para.para_shape_id = new_id;
            restamp_indentation(&mut cell_para.line_segs, old_indent, new_indent);
            cell_para.cell_format_vpos_dirty |= affects_vpos;
            if marker_changed {
                cell_para.invalidate_layout_inputs();
            }
        }

        // 줄바꿈에 영향을 주는 변경 시 셀 내 문단 LineSeg 재계산.
        //
        // [자체 발견] apply_char_format_in_cell_native 와 동일한 결함 — 페이지 본문 단 폭을
        // 셀 리플로우에 썼다. undo 형제 set_cell_para_shape_id_native(:1538)는 이미
        // reflow_cell_paragraph 를 쓴다. 그 헬퍼로 통일해 폭 계산과 dirty 마킹을 함께 맞춘다.
        //
        // [#4324] 게이트가 줄간격만 보고 여백/들여쓰기/줄나눔 단위를 놓쳤다 — 이 값들도
        // reflow_cell_paragraph 가 계산하는 사용 가능 폭·토큰 경계에 실제로 쓰인다.
        // para_shape_mods_affect_text_flow(:16 부근)로 판정을 통일한다.
        if para_shape_mods_affect_text_flow(&mods) {
            self.reflow_cell_paragraph(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            );
        }

        // [#6639] 배치 중에는 셀별로 모으고, 스타일 갱신 뒤 조각마다 한 번 재배치한다.
        self.pending_cell_format_vpos |= affects_vpos;

        // 표 dirty 마킹 — measure_section_incremental이 셀 높이를 재계산하도록
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);

        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 문단 서식 ID 직접 복원 (네이티브) — 셀 내 문단.
    pub fn set_cell_para_shape_id_native(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        para_shape_id: u16,
    ) -> Result<String, HwpError> {
        if para_shape_id as usize >= self.document.doc_info.para_shapes.len() {
            return Err(HwpError::RenderError(format!(
                "문단 모양 ID {} 범위 초과 (총 {}개)",
                para_shape_id,
                self.document.doc_info.para_shapes.len()
            )));
        }

        let old_id = self
            .get_cell_paragraph_ref(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )
            .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?
            .para_shape_id;
        let affects_vpos = self
            .document
            .doc_info
            .para_shapes
            .get(old_id as usize)
            .is_none_or(|old| {
                cell_para_shape_affects_vpos(
                    old,
                    &self.document.doc_info.para_shapes[para_shape_id as usize],
                )
            });
        let marker_changed = marker_shape_changed(
            &self.document.doc_info.para_shapes[old_id as usize],
            &self.document.doc_info.para_shapes[para_shape_id as usize],
        );
        let (old_indent, new_indent) = self.para_shape_indents(old_id, para_shape_id);
        self.restamp_cell_format_origin(
            (
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            ),
            old_id,
            para_shape_id,
        )?;
        {
            let cell_para = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            cell_para.para_shape_id = para_shape_id;
            restamp_indentation(&mut cell_para.line_segs, old_indent, new_indent);
            cell_para.cell_format_vpos_dirty |= affects_vpos;
            if marker_changed {
                cell_para.invalidate_layout_inputs();
            }
        }

        self.reflow_cell_paragraph(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        );
        self.pending_cell_format_vpos |= affects_vpos;
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 문서 내 동일 style_id를 사용하는 기존 문단의 para_shape_id를 찾는다.
    fn find_reference_para_shape_for_style(&self, style_id: usize) -> Option<u16> {
        use crate::model::control::Control;

        for section in &self.document.sections {
            for para in &section.paragraphs {
                if para.style_id as usize == style_id {
                    return Some(para.para_shape_id);
                }
                for ctrl in &para.controls {
                    if let Control::Table(t) = ctrl {
                        for cell in &t.cells {
                            for cp in &cell.paragraphs {
                                if cp.style_id as usize == style_id {
                                    return Some(cp.para_shape_id);
                                }
                            }
                        }
                    }
                }
            }
        }
        None
    }

    /// 문서의 ParaShape 풀에서 동일 numbering_id·head_type이면서 target level인 것을 찾는다.
    fn find_para_shape_with_nid_and_level(
        &self,
        nid: u16,
        head_type: crate::model::style::HeadType,
        level: u8,
    ) -> Option<u16> {
        for (i, ps) in self.document.doc_info.para_shapes.iter().enumerate() {
            if ps.numbering_id == nid && ps.head_type == head_type && ps.para_level == level {
                return Some(i as u16);
            }
        }
        None
    }

    /// 스타일 이름에서 개요 수준을 추출한다. "개요 N" → Some(N-1)
    fn parse_outline_level_from_style(&self, style_id: usize) -> Option<u8> {
        let style = self.document.doc_info.styles.get(style_id)?;
        let name = style.local_name.trim();
        let rest = name.strip_prefix("개요")?.trim();
        let level_num = rest.parse::<u8>().ok()?;
        if level_num >= 1 && level_num <= 10 {
            Some(level_num - 1)
        } else {
            None
        }
    }

    /// 스타일에 맞는 ParaShape ID를 결정한다.
    ///
    /// current_psid: 현재 문단의 ParaShape ID (번호 문맥 보존용)
    ///
    /// 번호가 있는 문단의 스타일을 변경할 때 numbering_id를 보존하여
    /// 후속 문단의 번호 연속성을 유지한다.
    fn resolve_style_para_shape_id(&mut self, style_id: usize, current_psid: u16) -> u16 {
        use crate::model::style::HeadType;

        let current_ps = self
            .document
            .doc_info
            .para_shapes
            .get(current_psid as usize)
            .cloned();
        let current_head = current_ps
            .as_ref()
            .map(|ps| ps.head_type)
            .unwrap_or(HeadType::None);
        let current_nid = current_ps.as_ref().map(|ps| ps.numbering_id).unwrap_or(0);

        // ── 현재 문단이 번호/개요를 가지고 있는 경우 ──
        // numbering_id와 head_type을 보존하고 para_level만 변경
        if current_head != HeadType::None {
            // 대상 스타일의 개요 수준 결정
            let target_level = self.parse_outline_level_from_style(style_id).or_else(|| {
                // 스타일 이름에서 못 찾으면 참조 문단에서 추출
                self.find_reference_para_shape_for_style(style_id)
                    .and_then(|psid| self.document.doc_info.para_shapes.get(psid as usize))
                    .filter(|ps| ps.head_type != HeadType::None)
                    .map(|ps| ps.para_level)
            });

            if let Some(level) = target_level {
                // 같은 numbering_id·head_type에서 target level인 ParaShape 검색
                if let Some(found) =
                    self.find_para_shape_with_nid_and_level(current_nid, current_head, level)
                {
                    return found;
                }

                // 없으면 현재 ParaShape 기반으로 level + 여백 변경하여 생성
                let current_level = current_ps.as_ref().map(|ps| ps.para_level).unwrap_or(0);
                let current_margin = current_ps.as_ref().map(|ps| ps.margin_left).unwrap_or(0);
                // 수준별 여백 증감: 수준 1단계당 2000 HWPUNIT
                let margin_delta = (level as i32 - current_level as i32) * 2000;
                let new_margin = (current_margin + margin_delta).max(0);
                let mods = crate::model::style::ParaShapeMods {
                    para_level: Some(level),
                    margin_left: Some(new_margin),
                    ..Default::default()
                };
                return self.document.find_or_create_para_shape(current_psid, &mods);
            }
        }

        // ── 현재 문단에 번호가 없는 경우 (바탕글 등) ──
        // 일반 스타일은 기존 문단의 실효 ParaShape가 아니라 스타일 정의값을 따른다.
        // 참조 문단을 우선하면 직접 서식이 섞인 문단 값이 스타일 적용값으로 번질 수 있다.
        let style = match self.document.doc_info.styles.get(style_id) {
            Some(s) => s.clone(),
            None => return 0,
        };
        let base_psid = style.para_shape_id;

        // 스타일 이름에서 "개요 N" 패턴 감지
        if let Some(level) = self.parse_outline_level_from_style(style_id) {
            // Outline 문단의 numbering_id는 0 (렌더링 시 구역의 outline_numbering_id로 해석)
            let mods = crate::model::style::ParaShapeMods {
                head_type: Some(HeadType::Outline),
                para_level: Some(level),
                numbering_id: Some(0),
                ..Default::default()
            };
            return self.document.find_or_create_para_shape(base_psid, &mods);
        }

        // 일반 스타일 → 기본 ParaShape 사용
        base_psid
    }

    /// 본문 문단의 LineSeg를 현재 CharShape/ParaShape 기준으로 다시 계산한다.
    pub(crate) fn reflow_body_paragraph(&mut self, sec_idx: usize, para_idx: usize) {
        let para_shape_id = match self
            .document
            .sections
            .get(sec_idx)
            .and_then(|s| s.paragraphs.get(para_idx))
        {
            Some(para) => para.para_shape_id,
            None => return,
        };
        let styles = self.resolve_render_styles();
        let paragraph_box =
            body_paragraph_box_for_para_shape(self, sec_idx, para_shape_id, &styles);
        if let Some(para) = self
            .document
            .sections
            .get_mut(sec_idx)
            .and_then(|s| s.paragraphs.get_mut(para_idx))
        {
            para.line_segs.clear();
            reflow_line_segs(para, paragraph_box, &styles, self.dpi);
        }
        self.fit_cell_grid(sec_idx, para_idx, &styles);
    }

    /// 구역의 본문 문단 전부를 현재 용지/단 기준으로 다시 접는다 — 쪽 설정이 바뀌어 본문
    /// 폭 자체가 달라졌을 때 쓴다.
    ///
    /// 비우기만 하고 재계산을 조판에 맡기면 안 된다. 저장 분할이 없는 문단은 조판에서
    /// NO_LS 계급이 되는데, 그 계급은 쪽 나눔에서 문단 위 간격을 0 으로 세고(typeset.rs 의
    /// `para.line_segs.is_empty()` 분기) 렌더는 그대로 그린다 — 여백을 조금만 건드려도
    /// 쪽 나눔과 그리기가 문단마다 spacing_before 만큼 어긋난다.
    ///
    /// 문단 하나짜리 `reflow_body_paragraph` 를 문단 수만큼 부르면 `resolve_styles` 와
    /// `PageLayoutInfo` 계산이 그만큼 반복된다. 둘 다 한 번만 하고 문단별 여백만 뺀다.
    ///
    /// 본문 문단만 다룬다. 표 셀은 폭의 주인이 표라서 제외하고, 머리말·꼬리말은 폭이 본문과
    /// 같지만(`header_area`/`footer_area` 가 같은 `content_left..content_right`) 여기서 건드릴
    /// 필요가 없다 — 합성 경로가 저장 분할과 무관하게 영역 폭으로 다시 접는다. 실측: 저장
    /// 분할 1줄 그대로인 꼬리말이 본문을 절반으로 좁힌 뒤에도 렌더에서 386.7px 로 본문
    /// 오른쪽 끝(396.9px) 안에 들어온다 (samples/hwp3-sample19-hwp5.hwp).
    pub(crate) fn reflow_body_paragraphs_in_section(&mut self, sec_idx: usize) {
        let styles = self.resolve_render_styles();
        let dpi = self.dpi;
        let wrap_width = self.body_wrap_width(sec_idx);
        let Some(section) = self.document.sections.get_mut(sec_idx) else {
            return;
        };
        for para in section.paragraphs.iter_mut() {
            // 영역 폭에서 그 문단의 좌우 여백을 빼는 일은
            // `ParagraphBox::body_for_style` 하나가 소유한다 — 여기서 같은 뺄셈을
            // 다시 하면 본문 상자의 주인이 둘이 된다. 폭이 남지 않는 문단은
            // 1.0px 로 바닥을 대는 대신 `reflow_line_segs` 가 거절한다.
            let paragraph_box = ParagraphBox::body_for_style(
                wrap_width,
                styles.para_styles.get(para.para_shape_id as usize),
                dpi,
            );
            para.line_segs.clear();
            reflow_line_segs(para, paragraph_box, &styles, dpi);
        }
        for para_idx in 0..self.document.sections[sec_idx].paragraphs.len() {
            self.fit_cell_grid(sec_idx, para_idx, &styles);
        }
    }

    /// 이 구역의 본문 문단이 접히는 폭 (px) — 단이 나뉘어 있으면 첫 단 폭, 아니면 본문 상자 폭.
    ///
    /// "줄 나눔을 정하는 폭"의 정의는 하나여야 한다. 저장 분할을 버릴지 판단하는 곳(쪽 설정·단
    /// 설정 변경)과 실제로 다시 접는 곳이 각자 계산하면, 제본 여백·가로세로 뒤바꿈·여백 과대
    /// 폴백 같은 규칙이 한쪽에만 반영돼 "바뀐 줄 모르고 안 접거나, 안 바뀐 걸 접는" 어긋남이
    /// 생긴다.
    pub(crate) fn body_wrap_width(&self, sec_idx: usize) -> f64 {
        let Some(section) = self.document.sections.get(sec_idx) else {
            return 0.0;
        };
        let column_def = DocumentCore::find_initial_column_def(&section.paragraphs);
        let layout =
            PageLayoutInfo::from_page_def(&section.section_def.page_def, &column_def, self.dpi);
        layout
            .column_areas
            .first()
            .map(|a| a.width)
            .unwrap_or(layout.body_area.width)
    }

    /// 스타일 적용 (네이티브) — 본문 문단
    pub fn apply_style_native(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        style_id: usize,
    ) -> Result<String, HwpError> {
        let style = self
            .document
            .doc_info
            .styles
            .get(style_id)
            .cloned()
            .ok_or_else(|| HwpError::RenderError(format!("스타일 {} 범위 초과", style_id)))?;
        let new_char_shape_id = style.char_shape_id as u32;

        // 현재 문단의 기존 스타일/문단 모양을 먼저 읽어서 직접 서식 여부를 판단한다.
        let (current_style_id, current_psid) = self
            .document
            .sections
            .get(sec_idx)
            .and_then(|s| s.paragraphs.get(para_idx))
            .map(|p| (p.style_id, p.para_shape_id))
            .ok_or_else(|| {
                HwpError::RenderError(format!("문단 {}/{} 범위 초과", sec_idx, para_idx))
            })?;
        let old_style = self
            .document
            .doc_info
            .styles
            .get(current_style_id as usize)
            .cloned();

        if style.style_type == 1 {
            let text_len = {
                let para = self
                    .document
                    .sections
                    .get_mut(sec_idx)
                    .and_then(|s| s.paragraphs.get_mut(para_idx))
                    .ok_or_else(|| {
                        HwpError::RenderError(format!("문단 {}/{} 범위 초과", sec_idx, para_idx))
                    })?;
                para.apply_char_shape_to_entire_text(new_char_shape_id);
                para.text.chars().count()
            };

            self.reflow_body_paragraph(sec_idx, para_idx);
            self.document.sections[sec_idx].raw_stream = None;
            self.rebuild_section(sec_idx);
            self.event_log.push(DocumentEvent::CharFormatChanged {
                section: sec_idx,
                para: para_idx,
                start: 0,
                end: text_len,
            });
            return Ok("{\"ok\":true}".to_string());
        }

        let new_para_shape_id = match old_style.as_ref() {
            Some(old) if current_psid != old.para_shape_id => current_psid,
            _ => self.resolve_style_para_shape_id(style_id, current_psid),
        };

        let para = self
            .document
            .sections
            .get_mut(sec_idx)
            .and_then(|s| s.paragraphs.get_mut(para_idx))
            .ok_or_else(|| {
                HwpError::RenderError(format!("문단 {}/{} 범위 초과", sec_idx, para_idx))
            })?;

        para.style_id = style_id as u8;
        para.para_shape_id = new_para_shape_id;
        if let Some(old) = old_style {
            para.replace_style_char_shape_preserving_overrides(
                old.char_shape_id as u32,
                new_char_shape_id,
            );
        } else {
            para.set_single_char_shape(new_char_shape_id);
        }

        self.reflow_body_paragraph(sec_idx, para_idx);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 스타일 적용 (네이티브) — 셀 내 문단
    pub fn apply_cell_style_native(
        &mut self,
        sec_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        style_id: usize,
    ) -> Result<String, HwpError> {
        let style = self
            .document
            .doc_info
            .styles
            .get(style_id)
            .cloned()
            .ok_or_else(|| HwpError::RenderError(format!("스타일 {} 범위 초과", style_id)))?;
        let new_char_shape_id = style.char_shape_id as u32;

        // 현재 셀 문단의 기존 스타일/문단 모양을 먼저 읽어서 직접 서식 여부를 판단한다.
        let (current_style_id, current_psid) = self
            .get_cell_paragraph_ref(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )
            .map(|p| (p.style_id, p.para_shape_id))
            .ok_or_else(|| HwpError::RenderError("셀 문단을 찾을 수 없음".to_string()))?;
        let old_style = self
            .document
            .doc_info
            .styles
            .get(current_style_id as usize)
            .cloned();

        if style.style_type == 1 {
            let text_len = {
                let cell_para = self.get_cell_paragraph_mut(
                    sec_idx,
                    parent_para_idx,
                    control_idx,
                    cell_idx,
                    cell_para_idx,
                )?;
                cell_para.apply_char_shape_to_entire_text(new_char_shape_id);
                cell_para.cell_format_vpos_dirty = true;
                cell_para.text.chars().count()
            };

            self.reflow_cell_paragraph(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            );
            self.pending_cell_format_vpos = true;
            self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);
            self.document.sections[sec_idx].raw_stream = None;
            self.rebuild_section_deferred_in_batch(sec_idx);
            self.event_log.push(DocumentEvent::CharFormatChanged {
                section: sec_idx,
                para: parent_para_idx,
                start: 0,
                end: text_len,
            });
            return Ok("{\"ok\":true}".to_string());
        }

        let new_para_shape_id = match old_style.as_ref() {
            Some(old) if current_psid != old.para_shape_id => current_psid,
            _ => self.resolve_style_para_shape_id(style_id, current_psid),
        };
        let (old_indent, new_indent) = self.para_shape_indents(current_psid, new_para_shape_id);
        self.restamp_cell_format_origin(
            (
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            ),
            current_psid,
            new_para_shape_id,
        )?;

        {
            let cell_para = self.get_cell_paragraph_mut(
                sec_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            cell_para.style_id = style_id as u8;
            cell_para.para_shape_id = new_para_shape_id;
            cell_para.cell_format_vpos_dirty = true;
            restamp_indentation(&mut cell_para.line_segs, old_indent, new_indent);
            if let Some(old) = old_style {
                cell_para.replace_style_char_shape_preserving_overrides(
                    old.char_shape_id as u32,
                    new_char_shape_id,
                );
            } else {
                cell_para.set_single_char_shape(new_char_shape_id);
            }
        }

        self.reflow_cell_paragraph(
            sec_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        );
        self.pending_cell_format_vpos = true;
        self.mark_cell_control_dirty(sec_idx, parent_para_idx, control_idx);
        self.document.sections[sec_idx].raw_stream = None;
        self.rebuild_section_deferred_in_batch(sec_idx);
        self.event_log.push(DocumentEvent::ParaFormatChanged {
            section: sec_idx,
            para: parent_para_idx,
        });
        Ok("{\"ok\":true}".to_string())
    }

    /// 본문 문단에 글자 서식 적용 헬퍼
    pub(crate) fn apply_char_mods_to_paragraph(
        &mut self,
        sec_idx: usize,
        para_idx: usize,
        start_offset: usize,
        end_offset: usize,
        mods: &crate::model::style::CharShapeMods,
    ) -> Result<(), HwpError> {
        let base_ids = self.document.sections[sec_idx].paragraphs[para_idx]
            .char_shape_ids_in_range(start_offset, end_offset);
        let ids = self.document.modified_char_shape_ids(base_ids, mods);
        self.document.sections[sec_idx].paragraphs[para_idx].try_map_char_shape_range(
            start_offset,
            end_offset,
            |id| {
                ids.get(&id)
                    .copied()
                    .ok_or_else(|| HwpError::RenderError(format!("글자 모양 변환 ID {id} 누락")))
            },
        )
    }

    /// 문단 번호 시작 방식을 설정한다.
    /// mode: 0 = 앞 번호 목록에 이어 (기본), 1 = 이전 번호 목록에 이어, 2 = 새 번호 목록 시작
    /// start_num: mode=2일 때 시작 번호
    pub fn set_numbering_restart_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        mode: u8,
        start_num: u32,
    ) -> Result<String, crate::error::HwpError> {
        use crate::model::paragraph::NumberingRestart;

        if section_idx >= self.document.sections.len() {
            return Err(crate::error::HwpError::RenderError(
                "구역 범위 초과".to_string(),
            ));
        }
        if para_idx >= self.document.sections[section_idx].paragraphs.len() {
            return Err(crate::error::HwpError::RenderError(
                "문단 범위 초과".to_string(),
            ));
        }

        let restart = match mode {
            0 => None,
            1 => Some(NumberingRestart::ContinuePrevious),
            2 => Some(NumberingRestart::NewStart(start_num)),
            _ => None,
        };

        self.document.sections[section_idx].paragraphs[para_idx].numbering_restart = restart;
        self.document.sections[section_idx].raw_stream = None;

        self.recompose_section(section_idx);
        self.paginate_if_needed();

        Ok(crate::document_core::helpers::json_ok())
    }

    /// 감추기(PageHide) 컨트롤을 현재 문단에 삽입 또는 갱신한다.
    /// flags: { hideHeader, hideFooter, hideMasterPage, hideBorder, hideFill, hidePageNum }
    pub fn set_page_hide_native(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        hide_header: bool,
        hide_footer: bool,
        hide_master_page: bool,
        hide_border: bool,
        hide_fill: bool,
        hide_page_num: bool,
    ) -> Result<String, crate::error::HwpError> {
        use crate::model::control::{Control, PageHide};

        if section_idx >= self.document.sections.len() {
            return Err(crate::error::HwpError::RenderError(
                "구역 범위 초과".to_string(),
            ));
        }
        if para_idx >= self.document.sections[section_idx].paragraphs.len() {
            return Err(crate::error::HwpError::RenderError(
                "문단 범위 초과".to_string(),
            ));
        }

        let all_false = !hide_header
            && !hide_footer
            && !hide_master_page
            && !hide_border
            && !hide_fill
            && !hide_page_num;

        let para = &mut self.document.sections[section_idx].paragraphs[para_idx];

        // 기존 PageHide 컨트롤 찾기
        let existing_idx = para
            .controls
            .iter()
            .position(|c| matches!(c, Control::PageHide(_)));

        if all_false {
            // 모두 false → 기존 PageHide 제거
            if let Some(idx) = existing_idx {
                para.controls.remove(idx);
                if idx < para.ctrl_data_records.len() {
                    para.ctrl_data_records.remove(idx);
                }
                para.forget_para_text_if_emptied();
            }
        } else {
            let ph = PageHide {
                hide_header,
                hide_footer,
                hide_master_page,
                hide_border,
                hide_fill,
                hide_page_num,
            };
            if let Some(idx) = existing_idx {
                // 기존 컨트롤 갱신
                para.controls[idx] = Control::PageHide(ph);
            } else {
                // 새 컨트롤 삽입 (문단 맨 앞)
                para.controls.insert(0, Control::PageHide(ph));
                para.ctrl_data_records.insert(0, None);
            }
        }

        self.document.sections[section_idx].raw_stream = None;
        self.recompose_section(section_idx);
        self.paginate_if_needed();

        Ok(crate::document_core::helpers::json_ok())
    }

    /// 현재 문단의 PageHide 상태를 조회한다.
    pub fn get_page_hide_native(
        &self,
        section_idx: usize,
        para_idx: usize,
    ) -> Result<String, crate::error::HwpError> {
        use crate::model::control::Control;

        let section = self
            .document
            .sections
            .get(section_idx)
            .ok_or_else(|| crate::error::HwpError::RenderError("구역 범위 초과".to_string()))?;
        let para = section
            .paragraphs
            .get(para_idx)
            .ok_or_else(|| crate::error::HwpError::RenderError("문단 범위 초과".to_string()))?;

        for ctrl in &para.controls {
            if let Control::PageHide(ph) = ctrl {
                return Ok(format!(
                    "{{\"ok\":true,\"exists\":true,\"hideHeader\":{},\"hideFooter\":{},\"hideMasterPage\":{},\"hideBorder\":{},\"hideFill\":{},\"hidePageNum\":{}}}",
                    ph.hide_header, ph.hide_footer, ph.hide_master_page,
                    ph.hide_border, ph.hide_fill, ph.hide_page_num
                ));
            }
        }
        Ok("{\"ok\":true,\"exists\":false}".to_string())
    }

    /// 구역의 쪽 번호 매기기(`pgnp`)를 읽는다 (#7635).
    ///
    /// 한/글 쪽 번호 매기기 창처럼 구역 본문 문단의 마지막 쪽 번호 위치를 돌려준다.
    /// 구역에 없으면 `exists:false`다. 앞 구역의 것을 잇는지는 부르는 쪽이 정한다.
    pub fn get_page_number_position_native(
        &self,
        section_idx: usize,
    ) -> Result<String, crate::error::HwpError> {
        let section = self
            .document
            .sections
            .get(section_idx)
            .ok_or_else(|| crate::error::HwpError::RenderError("구역 범위 초과".to_string()))?;
        Ok(match last_page_number_position(&section.paragraphs) {
            Some(pnp) => format!(
                "{{\"ok\":true,\"exists\":true,\"position\":{},\"format\":{},\"dash\":{}}}",
                pnp.position,
                pnp.format,
                pnp.dash_char != '\0'
            ),
            None => "{\"ok\":true,\"exists\":false}".to_string(),
        })
    }

    /// 구역의 쪽 번호 매기기(`pgnp`)를 정한다 (#7635).
    ///
    /// 한/글 12.30 쪽 > 쪽 번호 매기기처럼 캐럿과 상관없이 구역 본문 문단의 쪽 번호 위치를
    /// 모두 지우고, 구역 첫 문단의 구역·단 정의 바로 뒤에 하나를 넣는다. 위치 0(쪽 번호 없음)도
    /// 컨트롤로 남겨 앞 구역의 쪽 번호를 잇지 않게 한다. 창에 없는 사용자 기호와 앞·뒤 장식
    /// 문자는 지운 위치의 값을 잇는다. 줄표는 `-`(HWPX `sideChar`)다.
    pub fn set_page_number_position_native(
        &mut self,
        section_idx: usize,
        position: u8,
        format: u8,
        dash: bool,
    ) -> Result<String, crate::error::HwpError> {
        use crate::document_core::inline_control::{active_shape, insert_slot, remove_slot, Slot};
        use crate::error::HwpError;
        use crate::model::control::{Control, PageNumberPos};
        use crate::model::paragraph::CharShapeRef;
        use crate::serializer::body_text::control_stream_slots;

        if position > 10 {
            return Err(HwpError::RenderError(
                "쪽 번호 위치는 0~10이어야 합니다".to_string(),
            ));
        }
        if format > 16 {
            return Err(HwpError::RenderError(
                "번호 모양은 0~16이어야 합니다".to_string(),
            ));
        }
        let paragraphs = &self
            .document
            .sections
            .get(section_idx)
            .ok_or_else(|| HwpError::RenderError("구역 범위 초과".to_string()))?
            .paragraphs;
        if paragraphs.is_empty() {
            return Err(HwpError::RenderError("구역에 문단이 없습니다".to_string()));
        }
        let kept = last_page_number_position(paragraphs).cloned();
        let pnp = PageNumberPos {
            format,
            position,
            dash_char: if dash { '-' } else { '\0' },
            ..kept.unwrap_or_default()
        };

        // 지울 자리와 넣을 자리를 복제본에서 먼저 확인한다. 실패하면 문서는 그대로다.
        let is_pnp = |control: &Control| matches!(control, Control::PageNumberPos(_));
        let mut removed = Vec::new();
        for (pi, para) in paragraphs.iter().enumerate() {
            if !para.controls.iter().any(is_pnp) {
                continue;
            }
            let mut copy = para.clone();
            while let Some(ci) = copy.controls.iter().rposition(is_pnp) {
                remove_slot(&mut copy, ci)?;
                removed.push((pi, ci));
            }
        }
        let mut first = paragraphs[0].clone();
        for &(_, ci) in removed.iter().filter(|(pi, _)| *pi == 0) {
            remove_slot(&mut first, ci)?;
        }
        let leading = first
            .controls
            .iter()
            .take_while(|c| matches!(c, Control::SectionDef(_) | Control::ColumnDef(_)))
            .count();
        let raw = match leading {
            0 => 0,
            n => control_stream_slots(&first)[n - 1]
                .map(|(raw, _)| raw + 8)
                .ok_or_else(|| HwpError::RenderError("구역 정의 슬롯이 없습니다".to_string()))?,
        };
        let slot = |para: &crate::model::paragraph::Paragraph| Slot {
            control: Control::PageNumberPos(pnp.clone()),
            data: None,
            shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: active_shape(para, raw),
            }],
            tags: vec![],
        };
        let checked = slot(&first);
        insert_slot(&mut first, raw, leading, checked)?;

        // 복제본과 같은 차례로 살아 있는 문단을 고쳐 표 Box 식별자와 조판 캐시를 지킨다.
        let section = &mut self.document.sections[section_idx];
        section.raw_stream = None;
        for &(pi, ci) in &removed {
            remove_slot(&mut section.paragraphs[pi], ci).expect("복제본에서 확인한 슬롯");
        }
        let first = &mut section.paragraphs[0];
        let inserted = slot(first);
        insert_slot(first, raw, leading, inserted).expect("복제본에서 확인한 자리");
        for &(pi, ci) in &removed {
            Self::remap_active_field_root_control(
                &mut self.active_field,
                section_idx,
                pi,
                |index| match index.cmp(&ci) {
                    std::cmp::Ordering::Less => Some(index),
                    std::cmp::Ordering::Equal => None,
                    std::cmp::Ordering::Greater => Some(index - 1),
                },
            );
        }
        self.shift_active_field_for_control_insert(section_idx, 0, leading);
        let mut changed: Vec<usize> = removed.iter().map(|(pi, _)| *pi).collect();
        changed.push(0);
        changed.sort_unstable();
        changed.dedup();
        for pi in changed {
            self.reflow_paragraph(section_idx, pi);
        }
        self.recompose_section(section_idx);
        // 뒤 구역은 이 구역의 쪽 번호 위치를 잇거나, 이 구역 첫 문단의 머리말·꼬리말을
        // 컨트롤 차례로 가리킨다. 옮긴 컨트롤 때문에 차례가 바뀌므로 함께 다시 짠다.
        for next in section_idx + 1..self.document.sections.len() {
            self.mark_section_dirty(next);
        }
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        // 셀·캡션 캐럿처럼 컨트롤 차례로 가리키는 주소를 부르는 쪽이 옮길 수 있게 바꾼 차례를 돌려준다.
        let removed_json: Vec<String> = removed
            .iter()
            .map(|(pi, ci)| format!("[{pi},{ci}]"))
            .collect();
        Ok(format!(
            "{{\"ok\":true,\"controlIdx\":{leading},\"removed\":[{}]}}",
            removed_json.join(",")
        ))
    }
}

/// 구역 본문 문단의 마지막 쪽 번호 위치. 조판이 구역 선언으로 쓰는 것과 같은 차례다.
fn last_page_number_position(
    paragraphs: &[crate::model::paragraph::Paragraph],
) -> Option<&crate::model::control::PageNumberPos> {
    paragraphs.iter().rev().find_map(|para| {
        para.controls
            .iter()
            .rev()
            .find_map(|control| match control {
                crate::model::control::Control::PageNumberPos(pnp) => Some(pnp),
                _ => None,
            })
    })
}

#[cfg(test)]
mod tests {
    use super::{
        body_paragraph_box_for_para_shape, char_shape_mods_affect_text_flow,
        para_shape_mods_affect_text_flow, DocumentCore,
    };
    use crate::model::control::Control;
    use crate::model::paragraph::{CharShapeRef, Paragraph};
    use crate::model::style::{CharShapeMods, ParaShapeMods};
    use crate::model::table::{Cell, Table};

    #[test]
    fn char_ratio_and_spacing_changes_require_text_reflow() {
        let mods = CharShapeMods {
            ratios: Some([99; 7]),
            ..Default::default()
        };
        assert!(char_shape_mods_affect_text_flow(&mods));

        let mods = CharShapeMods {
            spacings: Some([-1; 7]),
            ..Default::default()
        };
        assert!(char_shape_mods_affect_text_flow(&mods));
    }

    #[test]
    fn underline_changes_preserve_text_flow_classification() {
        let mods = CharShapeMods {
            underline: Some(true),
            ..Default::default()
        };
        assert!(!char_shape_mods_affect_text_flow(&mods));
    }

    /// [#4324] margin/indent/줄나눔 단위 변경도 사용 가능 폭·토큰 경계를 바꾸므로
    /// 줄간격과 마찬가지로 리플로우가 필요하다.
    #[test]
    fn para_margin_indent_and_break_unit_changes_require_text_reflow() {
        let mods = ParaShapeMods {
            margin_left: Some(8000),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            margin_right: Some(4000),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            indent: Some(2000),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            english_break_unit: Some(1),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            korean_break_unit: Some(1),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        // 문단 머리는 줄 앞을 차지하고(#7418) 첫 줄의 bit 21 을 정한다.
        let mods = ParaShapeMods {
            head_type: Some(crate::model::style::HeadType::Number),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));
        let mods = ParaShapeMods {
            numbering_id: Some(1),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));
        let mods = ParaShapeMods {
            para_level: Some(1),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));

        // 기존에 이미 게이트하던 줄간격도 계속 포함해야 한다 (회귀 방지).
        let mods = ParaShapeMods {
            line_spacing: Some(150),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));
        let mods = ParaShapeMods {
            line_spacing_type: Some(crate::model::style::LineSpacingType::Fixed),
            ..Default::default()
        };
        assert!(para_shape_mods_affect_text_flow(&mods));
    }

    /// [#4324] 정렬/문단테두리/문단간격/쪽나눔 휴리스틱 등은 `reflow_line_segs`가
    /// 읽지 않는 입력이다 — 리플로우를 요구하면 안 된다(전수 조사 결과, 판정 근거는
    /// `para_shape_mods_affect_text_flow` 문서 주석 참고).
    #[test]
    fn para_shape_changes_without_flow_impact_do_not_require_text_reflow() {
        let mods = ParaShapeMods {
            alignment: Some(crate::model::style::Alignment::Center),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            spacing_before: Some(1000),
            spacing_after: Some(1000),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            widow_orphan: Some(true),
            keep_with_next: Some(true),
            keep_lines: Some(true),
            page_break_before: Some(true),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            border_fill_id: Some(3),
            border_spacing: Some([100, 100, 100, 100]),
            border_connect: Some(true),
            border_ignore_margin: Some(true),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));

        // tab_def_id: 현재 resolve_single_para_style이 default_tab_width를 상수로 고정해
        // 두므로(별개 결함), 오늘 시점 코드 기준으로는 흐름에 영향이 없다.
        let mods = ParaShapeMods {
            tab_def_id: Some(2),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));

        let mods = ParaShapeMods {
            font_line_height: Some(true),
            single_line: Some(true),
            auto_space_kr_en: Some(true),
            auto_space_kr_num: Some(true),
            vertical_align: Some(1),
            ..Default::default()
        };
        assert!(!para_shape_mods_affect_text_flow(&mods));
    }

    #[test]
    fn apply_char_format_in_nested_cell_by_path_preserves_outer_cell() {
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native().unwrap();
        if core.document.doc_info.char_shapes.is_empty() {
            // 실제 문서는 기본 글자 모양을 보유한다. 새 서식이 0번을 재사용하지 않게 맞춘다.
            core.document.doc_info.char_shapes.push(Default::default());
        }

        let inner_para = Paragraph {
            text: "INNER".to_string(),
            char_count: 5,
            char_offsets: vec![0, 1, 2, 3, 4],
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            ..Default::default()
        };
        let nested_table = Table {
            cells: vec![Cell {
                paragraphs: vec![inner_para],
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut outer_para = Paragraph {
            text: "OUTER".to_string(),
            char_count: 5,
            char_offsets: vec![0, 1, 2, 3, 4],
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            ..Default::default()
        };
        outer_para
            .controls
            .push(Control::Table(Box::new(nested_table)));
        let nested_ctrl_idx = outer_para.controls.len() - 1;
        let outer_table = Table {
            cells: vec![Cell {
                paragraphs: vec![outer_para],
                ..Default::default()
            }],
            ..Default::default()
        };
        core.document.sections[0].paragraphs[0]
            .controls
            .push(Control::Table(Box::new(outer_table)));
        let outer_ctrl_idx = core.document.sections[0].paragraphs[0].controls.len() - 1;
        let path = [(outer_ctrl_idx, 0, 0), (nested_ctrl_idx, 0, 0)];

        // 안쪽 셀에만 굵게 적용한다. 바깥 셀의 글자 모양 ID는 그대로여야 한다.
        core.apply_char_format_in_cell_by_path(0, 0, &path, 0, 5, r#"{"bold":true}"#)
            .unwrap();

        let inner_shape_id = {
            let Control::Table(outer) =
                &core.document.sections[0].paragraphs[0].controls[outer_ctrl_idx]
            else {
                panic!("expected outer table");
            };
            assert_eq!(
                outer.cells[0].paragraphs[0].char_shape_id_at(0),
                Some(0),
                "바깥 셀에는 서식이 적용되면 안 된다"
            );
            let Control::Table(inner) = &outer.cells[0].paragraphs[0].controls[nested_ctrl_idx]
            else {
                panic!("expected nested table");
            };
            let inner_shape_id = inner.cells[0].paragraphs[0].char_shape_id_at(0);
            assert_ne!(
                inner_shape_id,
                Some(0),
                "안쪽 셀에는 새 글자 서식이 적용돼야 한다"
            );
            inner_shape_id
        };

        // undo가 쓰는 ByPath 복원도 안쪽 셀만 기본 글자 모양으로 되돌려야 한다.
        core.set_char_shape_id_in_cell_by_path(0, 0, &path, 0, 5, 0)
            .unwrap();

        let Control::Table(outer) =
            &core.document.sections[0].paragraphs[0].controls[outer_ctrl_idx]
        else {
            panic!("expected outer table");
        };
        assert_eq!(outer.cells[0].paragraphs[0].char_shape_id_at(0), Some(0));
        let Control::Table(inner) = &outer.cells[0].paragraphs[0].controls[nested_ctrl_idx] else {
            panic!("expected nested table");
        };
        assert_eq!(inner.cells[0].paragraphs[0].char_shape_id_at(0), Some(0));
        assert_ne!(
            inner_shape_id,
            Some(0),
            "복원 전에는 안쪽 셀만 새 ID여야 한다"
        );
    }
}

#[cfg(test)]
mod cell_reflow_width_tests {
    //! 셀 서식 적용의 리플로우 폭 회귀 테스트.
    //!
    //! apply_char_format_in_cell_native / apply_para_format_in_cell_native 는 예전에
    //! 페이지 본문 단(column) 폭으로 셀 문단을 리플로우했다 — 셀 폭은 보통 그보다 훨씬
    //! 좁아 텍스트가 한 줄로 뭉쳐졌다 셀 경계를 넘어 그려졌다. 같은 파일의 undo 형제
    //! set_char_shape_id_in_cell_native/set_cell_para_shape_id_native 는 이미
    //! reflow_cell_paragraph(셀/글상자 폭 기준)를 썼다 — do/undo 사이의 눈에 보이는 비대칭.
    //!
    //! 페이지 본문 폭(수만 HWPUNIT)과 셀 폭(200 HWPUNIT)을 극단적으로 벌려, 어떤 폰트
    //! 폭 추정치를 쓰든 "페이지 폭 사용" 과 "셀 폭 사용" 이 줄 수로 갈리게 한다.

    use crate::document_core::DocumentCore;
    use crate::model::control::Control;
    use crate::model::document::{Document, Section, SectionDef};
    use crate::model::page::PageDef;
    use crate::model::paragraph::{CharShapeRef, LineSeg, Paragraph};
    use crate::model::table::{Cell, Table};

    fn core_with_narrow_cell(text: &str) -> DocumentCore {
        // 셀 폭 200 HWPUNIT — 페이지 본문 폭(수만 HWPUNIT)의 1% 미만.
        core_with_cell(text, 200)
    }

    /// [#4324] `core_with_narrow_cell`의 셀 폭 파라미터화 버전. 200 HWPUNIT (약 2.7px)
    /// 는 어떤 텍스트든 이미 1글자/줄로 포화돼 있어 margin/indent를 더 좁혀도 줄 수가
    /// 늘어나는 걸 관찰할 여지가 없다 — margin 변화 전후 비교 테스트는 더 넓은 폭이
    /// 필요해 파라미터화한다.
    fn core_with_cell(text: &str, cell_width: u32) -> DocumentCore {
        // 참조하는 글자·문단 모양 0은 실제 정의를 가져야 한다. 빈 DocInfo에서는
        // 새 모양도 ID 0을 받아 이전 들여쓰기와 새 들여쓰기가 같은 값으로 보인다.
        let mut core = DocumentCore::new_empty();
        core.create_blank_document_native()
            .expect("기본 서식표를 가진 문서가 생성되어야 함");
        let mut doc = Document {
            doc_info: core.document.doc_info.clone(),
            ..Default::default()
        };

        let mut cell_para = Paragraph {
            text: text.to_string(),
            char_offsets: (0..text.chars().count() as u32).collect(),
            char_count: text.chars().count() as u32,
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            line_segs: vec![LineSeg {
                text_start: 0,
                ..Default::default()
            }],
            ..Default::default()
        };
        cell_para.has_para_text = true;

        let mut table = Table::default();
        table.row_count = 1;
        table.col_count = 1;
        table.cells = vec![Cell {
            row: 0,
            col: 0,
            col_span: 1,
            row_span: 1,
            width: cell_width,
            paragraphs: vec![cell_para],
            ..Default::default()
        }];

        let mut para = Paragraph::default();
        para.controls.push(Control::Table(Box::new(table)));

        let mut section = Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,
                    height: 84188,
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        section.paragraphs.push(para);
        doc.sections.push(section);

        core.set_document(doc);
        core
    }

    #[test]
    fn char_format_reflow_uses_cell_width_not_page_column_width() {
        let text = "A".repeat(40);
        let mut core = core_with_narrow_cell(&text);

        core.apply_char_format_in_cell_native(0, 0, 0, 0, 0, 0, 40, r#"{"fontSize":2000}"#)
            .expect("서식 적용이 성공해야 함");

        let table = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Table(t) => t,
            _ => panic!("표 컨트롤이어야 함"),
        };
        let line_count = table.cells[0].paragraphs[0].line_segs.len();
        assert!(
            line_count > 1,
            "셀 폭(200 HWPUNIT)으로 리플로우했다면 40자가 여러 줄로 나뉘어야 함              (실제 {line_count}줄 — 페이지 본문 폭을 쓰면 1줄로 뭉친다)"
        );
    }

    /// [#2755] `applyCharFormatInCellByPath` 도 깊이 1 셀에서 셀 폭 리플로우를 해야 한다.
    ///
    /// Studio 의 `ApplyCharFormatCommand` 는 `isCell`(= 모든 셀) 조건으로 이 경로를 쓰므로
    /// 깊이 1 셀 서식이 전부 여기로 들어온다. 리플로우가 없으면 글자 폭만 넓어지고 줄
    /// 경계는 그대로라 텍스트가 셀 오른쪽 경계를 넘어 그려진다.
    #[test]
    fn char_format_by_path_reflow_uses_cell_width_not_page_column_width() {
        let text = "A".repeat(40);
        let mut core = core_with_narrow_cell(&text);

        core.apply_char_format_in_cell_by_path(0, 0, &[(0, 0, 0)], 0, 40, r#"{"fontSize":2000}"#)
            .expect("서식 적용이 성공해야 함");

        let table = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Table(t) => t,
            _ => panic!("표 컨트롤이어야 함"),
        };
        let line_count = table.cells[0].paragraphs[0].line_segs.len();
        assert!(
            line_count > 1,
            "셀 폭(200 HWPUNIT)으로 리플로우했다면 40자가 여러 줄로 나뉘어야 함 \
             (실제 {line_count}줄 — 리플로우가 없으면 저장된 1줄 경계가 그대로 남는다)"
        );
    }

    /// [#2755] undo 가 쓰는 `setCharShapeIdInCellByPath` 도 같은 계약을 지켜야 한다.
    ///
    /// flat 형제 `set_char_shape_id_in_cell_native` 는 (모양 변화 내용을 알 수 없으므로)
    /// 무조건 `reflow_cell_paragraph` 를 호출한다.
    #[test]
    fn set_char_shape_id_by_path_reflow_uses_cell_width_not_page_column_width() {
        let text = "A".repeat(40);
        let mut core = core_with_narrow_cell(&text);
        if core.document.doc_info.char_shapes.is_empty() {
            core.document.doc_info.char_shapes.push(Default::default());
        }

        core.set_char_shape_id_in_cell_by_path(0, 0, &[(0, 0, 0)], 0, 40, 0)
            .expect("글자 모양 복원이 성공해야 함");

        let table = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Table(t) => t,
            _ => panic!("표 컨트롤이어야 함"),
        };
        let line_count = table.cells[0].paragraphs[0].line_segs.len();
        assert!(
            line_count > 1,
            "셀 폭(200 HWPUNIT)으로 리플로우했다면 40자가 여러 줄로 나뉘어야 함 \
             (실제 {line_count}줄)"
        );
    }

    #[test]
    fn para_format_reflow_uses_cell_width_not_page_column_width() {
        let text = "A".repeat(40);
        let mut core = core_with_narrow_cell(&text);

        core.apply_para_format_in_cell_native(0, 0, 0, 0, 0, r#"{"lineSpacing":150}"#)
            .expect("서식 적용이 성공해야 함");

        let table = match &core.document.sections[0].paragraphs[0].controls[0] {
            Control::Table(t) => t,
            _ => panic!("표 컨트롤이어야 함"),
        };
        let line_count = table.cells[0].paragraphs[0].line_segs.len();
        assert!(
            line_count > 1,
            "셀 폭(200 HWPUNIT)으로 리플로우했다면 40자가 여러 줄로 나뉘어야 함              (실제 {line_count}줄 — 페이지 본문 폭을 쓰면 1줄로 뭉친다)"
        );
    }

    /// [#4324] 재현 테스트 — 여백(marginLeft) 변경 전후 줄바꿈 결과 비교.
    ///
    /// 이슈 실측 프로브와 동일한 축척을 쓴다: 셀 폭 20000 HWPUNIT(≈266.7px, 이슈의
    /// "266.1px" 실측과 정합), `marginLeft: 8000`(≈53.3px 축소, 이슈의 "212.8px" 실측과
    /// 정합). 고정폭 게이트(line_spacing만 보던 옛 조건)에서는 marginLeft 변경이
    /// `reflow_cell_paragraph`를 호출하지 않아 LineSeg 경계가 그대로 남는다 — 줄
    /// 상자만 좁아지고 글자 수는 그대로인 원본 결함을 그대로 재현한다.
    ///
    /// 먼저 `reflow_cell_paragraph`를 직접 호출해 "여백 0" 기준선을 실제로 셀 폭으로
    /// 계산한 뒤, `marginLeft` 적용 전/후의 줄 수를 비교한다.
    #[test]
    fn para_format_margin_left_change_triggers_cell_reflow_and_rewraps() {
        let text = "A".repeat(200);
        let mut core = core_with_cell(&text, 20000);

        // 기준선: 여백 0 상태에서 실제 셀 폭(20000 HWPUNIT)으로 먼저 리플로우한다.
        core.reflow_cell_paragraph(0, 0, 0, 0, 0);
        let before_lines = {
            let table = match &core.document.sections[0].paragraphs[0].controls[0] {
                Control::Table(t) => t,
                _ => panic!("표 컨트롤이어야 함"),
            };
            table.cells[0].paragraphs[0].line_segs.len()
        };

        // 이슈 실측과 동일한 marginLeft(8000)를 적용한다 — 사용 가능 폭이 ≈53.3px 줄어든다.
        core.apply_para_format_in_cell_native(0, 0, 0, 0, 0, r#"{"marginLeft":8000}"#)
            .expect("서식 적용이 성공해야 함");
        let after_lines = {
            let table = match &core.document.sections[0].paragraphs[0].controls[0] {
                Control::Table(t) => t,
                _ => panic!("표 컨트롤이어야 함"),
            };
            table.cells[0].paragraphs[0].line_segs.len()
        };

        assert!(
            after_lines > before_lines,
            "marginLeft 적용으로 사용 가능 폭이 줄었으면 줄 수가 늘어야 함 \
             (before={before_lines}줄, after={after_lines}줄 — 게이트가 marginLeft를 놓치면 \
             after==before로 남는다)"
        );
    }

    /// [#4324] 재현 테스트 — `indent`(들여쓰기) 변경도 marginLeft와 동일하게
    /// `fill_lines`의 유효 폭을 줄이므로 리플로우를 유발해야 한다.
    #[test]
    fn para_format_indent_change_triggers_cell_reflow_and_rewraps() {
        let text = "A".repeat(200);
        let mut core = core_with_cell(&text, 20000);

        core.reflow_cell_paragraph(0, 0, 0, 0, 0);
        let before_starts: Vec<u32> = {
            let table = match &core.document.sections[0].paragraphs[0].controls[0] {
                Control::Table(t) => t,
                _ => panic!("표 컨트롤이어야 함"),
            };
            table.cells[0].paragraphs[0]
                .line_segs
                .iter()
                .map(|line| line.text_start)
                .collect()
        };

        // 들여쓰기는 첫 줄의 수용량을 줄인다. 뒤 줄의 남은 공간에 흡수되면 전체
        // 줄 수는 같을 수 있으므로 총 줄 수 대신 실제 첫 줄의 내용 경계를 검사한다.
        core.apply_para_format_in_cell_native(0, 0, 0, 0, 0, r#"{"indent":19000}"#)
            .expect("서식 적용이 성공해야 함");
        let after_starts: Vec<u32> = {
            let table = match &core.document.sections[0].paragraphs[0].controls[0] {
                Control::Table(t) => t,
                _ => panic!("표 컨트롤이어야 함"),
            };
            assert_eq!(table.cells[0].paragraphs[0].text, text, "내용 보존");
            table.cells[0].paragraphs[0]
                .line_segs
                .iter()
                .map(|line| line.text_start)
                .collect()
        };

        assert!(
            after_starts.len() > 1 && before_starts.len() > 1 && after_starts[1] < before_starts[1],
            "들여쓰기 적용 뒤 첫 줄에 들어가는 내용이 줄어야 함 \
             (before={before_starts:?}, after={after_starts:?})"
        );
    }

    /// [#2755] 깊이 2 중첩 표: 바깥 표(1셀, 폭 5000) 문단 안에 안쪽 표(1셀, 폭 200 + 권위
    /// line_segs)를 둔다. path = [(outer,0,0),(inner,0,0)] 를 함께 돌려준다.
    fn core_with_nested_narrow_cell(text: &str) -> (DocumentCore, Vec<(usize, usize, usize)>) {
        let mut inner_para = Paragraph {
            text: text.to_string(),
            char_offsets: (0..text.chars().count() as u32).collect(),
            char_count: text.chars().count() as u32,
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            line_segs: vec![LineSeg {
                text_start: 0,
                ..Default::default()
            }],
            ..Default::default()
        };
        inner_para.has_para_text = true;

        let inner_table = Table {
            row_count: 1,
            col_count: 1,
            cells: vec![Cell {
                row: 0,
                col: 0,
                col_span: 1,
                row_span: 1,
                width: 200,
                paragraphs: vec![inner_para],
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut outer_cell_para = Paragraph::default();
        outer_cell_para
            .controls
            .push(Control::Table(Box::new(inner_table)));
        let inner_ctrl_idx = outer_cell_para.controls.len() - 1;

        let outer_table = Table {
            row_count: 1,
            col_count: 1,
            cells: vec![Cell {
                row: 0,
                col: 0,
                col_span: 1,
                row_span: 1,
                width: 5000,
                paragraphs: vec![outer_cell_para],
                ..Default::default()
            }],
            ..Default::default()
        };

        let mut body_para = Paragraph::default();
        body_para
            .controls
            .push(Control::Table(Box::new(outer_table)));
        let outer_ctrl_idx = body_para.controls.len() - 1;

        let mut section = Section {
            section_def: SectionDef {
                page_def: PageDef {
                    width: 59528,
                    height: 84188,
                    margin_left: 8504,
                    margin_right: 8504,
                    margin_top: 5668,
                    margin_bottom: 4252,
                    margin_header: 4252,
                    margin_footer: 4252,
                    ..Default::default()
                },
                ..Default::default()
            },
            ..Default::default()
        };
        section.paragraphs.push(body_para);
        let mut core = DocumentCore::new_empty();
        // flat helper와 같은 정상 서식표를 쓴다. 파생 기본 글자 모양의
        // base_size=0으로 폭 없는 글자를 만들면 중첩 셀 재래핑을 검증할 수 없다.
        core.create_blank_document_native()
            .expect("기본 서식표를 가진 문서가 생성되어야 함");
        let doc = Document {
            doc_info: core.document.doc_info.clone(),
            sections: vec![section],
            ..Default::default()
        };
        core.set_document(doc);
        let path = vec![(outer_ctrl_idx, 0, 0), (inner_ctrl_idx, 0, 0)];
        (core, path)
    }

    fn inner_cell_line_count(core: &DocumentCore, path: &[(usize, usize, usize)]) -> usize {
        let Control::Table(outer) = &core.document.sections[0].paragraphs[0].controls[path[0].0]
        else {
            panic!("바깥 표여야 함");
        };
        let Control::Table(inner) = &outer.cells[0].paragraphs[0].controls[path[1].0] else {
            panic!("안쪽 표여야 함");
        };
        inner.cells[0].paragraphs[0].line_segs.len()
    }

    /// [#2755] 깊이 2 — `applyCharFormatInCellByPath` 가 최내곽 셀 폭으로 재래핑한다.
    #[test]
    fn char_format_by_path_reflow_reaches_nested_inner_cell() {
        let (mut core, path) = core_with_nested_narrow_cell(&"A".repeat(40));

        core.apply_char_format_in_cell_by_path(0, 0, &path, 0, 40, r#"{"fontSize":2000}"#)
            .expect("서식 적용이 성공해야 함");

        let line_count = inner_cell_line_count(&core, &path);
        assert!(
            line_count > 1,
            "깊이 2 안쪽 셀 폭(200)으로 재래핑되면 40자가 여러 줄이어야 함 (실제 {line_count}줄)"
        );
    }

    /// [#2755] 깊이 2 — `setCharShapeIdInCellByPath` 도 최내곽 셀 폭으로 재래핑한다.
    #[test]
    fn set_char_shape_id_by_path_reflow_reaches_nested_inner_cell() {
        let (mut core, path) = core_with_nested_narrow_cell(&"A".repeat(40));
        if core.document.doc_info.char_shapes.is_empty() {
            core.document.doc_info.char_shapes.push(Default::default());
        }

        core.set_char_shape_id_in_cell_by_path(0, 0, &path, 0, 40, 0)
            .expect("글자 모양 복원이 성공해야 함");

        let line_count = inner_cell_line_count(&core, &path);
        assert!(
            line_count > 1,
            "깊이 2 안쪽 셀 폭(200)으로 재래핑되면 40자가 여러 줄이어야 함 (실제 {line_count}줄)"
        );
    }
}