rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
//! Contents/section{N}.xml — Section 본문 직렬화
//!
//! Stage 2 (#182): 기존 템플릿 기반 구조를 유지하되, `<hp:p>` 와 `<hp:run>` 의 속성을
//! IR에서 가져와 동적으로 생성한다. `secPr`/`pagePr`/`grid` 등 섹션 정의는 템플릿 보존
//! (IR에 대응 필드가 더 담길 때까지 점진적으로 동적화 예정).
//!
//! Stage #177 (2026-04-18): `<hp:lineseg>` 직렬화를 IR 기반으로 전환.
//! `Paragraph.line_segs` 의 9개 필드(textpos, vertpos, vertsize, textheight, baseline,
//! spacing, horzpos, horzsize, flags)를 그대로 출력하여 **원본 lineseg 값 보존**.
//! rhwp 는 자신의 문서에서 새로 부정확한 값을 생산하지 않는다.
//!
//! IR 매핑 관행:
//!   - `section.paragraphs` 여러 개 = 하드 문단 경계 (`<hp:p>` 여러 개)
//!   - `paragraph.text` 내 `\n` = 소프트 라인브레이크 (`<hp:lineBreak/>`, 같은 문단 내)
//!   - `paragraph.text` 내 `\t` = 탭 (`<hp:tab width=... leader="0" type="1"/>`)
//!   - `paragraph.text` 내 `U+2007` = 고정폭 빈칸 (`<hp:fwSpace/>`, #4675)
//!   - `paragraph.para_shape_id` → `<hp:p paraPrIDRef>`
//!   - `paragraph.style_id` → `<hp:p styleIDRef>`
//!   - `paragraph.column_type` → `<hp:p pageBreak/columnBreak>`
//!   - `paragraph.char_shapes[0].char_shape_id` → 첫 `<hp:run charPrIDRef>`
//!   - `paragraph.line_segs[i]` → 각 `<hp:lineseg>` 속성 (9개 필드 그대로 출력)

use quick_xml::Writer;

use crate::model::control::{
    AutoNumber, AutoNumberType, CharOverlap, Control, Equation, Field, NewNumber, PageHide,
    PageNumCtrl, PageNumberPos, PageStartsOn, Ruby, EQUATION_LINE_MODE_BIT,
};
use crate::model::document::{Document, Section, SectionDef};
use crate::model::footnote::{Endnote, Footnote};
use crate::model::header_footer::{Footer, Header, HeaderFooterApply};
use crate::model::page::{ColumnDef, ColumnDirection, ColumnType};
use crate::model::paragraph::{
    ColumnBreakType, FieldRange, LineSeg, OrphanFieldEnd, Paragraph, TitleMark,
};
use crate::model::shape::{
    CommonObjAttr, HorzAlign, HorzRelTo, ShapeObject, SizeCriterion, TextWrap, VertAlign, VertRelTo,
};

use crate::parser::tags;
use crate::serializer::body_text::line_segs_within_text_axis;

use super::context::SerializeContext;
use super::field::{
    write_bookmark, write_field_begin, write_field_end, write_field_end_full, write_hyperlink_begin,
};
use super::utils::{
    xml_error, xml_escape, xml_escape_with_storage, xml_insert, xml_replacen, xml_value,
};
use super::SerializeError;
use super::{picture, table};

const EMPTY_SECTION_XML: &str = include_str!("templates/empty_section0.xml");

/// MEMO subList 여는 태그 (#1391) — 실물(aift) 고정 속성.
/// `textDirection` 만 원본값 보존(가변); 나머지는 실측 고정 속성.
fn render_sub_list_open(text_direction: Option<&str>) -> String {
    render_sub_list_open_with_storage(text_direction, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_sub_list_open_with_storage<S: crate::storage::Storage>(
    text_direction: Option<&str>,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            r#"<hp:subList id="" textDirection="{}" lineWrap="BREAK" vertAlign="TOP" linkListIDRef="0" linkListNextIDRef="0" textWidth="0" textHeight="0" hasTextRef="0" hasNumRef="0">"#,
            text_direction.unwrap_or("HORIZONTAL"),
        ),
    )
}
const LINESEG_SLOT_OPEN: &str = "<hp:linesegarray>";
const LINESEG_SLOT_CLOSE: &str = "</hp:linesegarray>";
const PARA_CLOSE: &str = "</hp:p></hs:sec>";

// 템플릿 내 첫 <hp:p> 태그의 실제 문자열 (id="3121190098" 랜덤 해시 포함).
// 템플릿은 정적이므로 이 문자열이 고정 위치에 있음이 보장됨.
const TEMPLATE_FIRST_P_TAG: &str = r#"<hp:p id="3121190098" paraPrIDRef="0" styleIDRef="0" pageBreak="0" columnBreak="0" merged="0">"#;
// 템플릿 첫 문단의 텍스트 run 전체 — 템플릿 내 유일하게 1회 등장 (#1378).
const TEMPLATE_TEXT_RUN: &str = r#"<hp:run charPrIDRef="0"><hp:t/></hp:run>"#;
// 템플릿 첫 run(secPr/colPr 전용)의 여는 태그 + secPr 시작 — run id 정비용 anchor (#1378).
const TEMPLATE_SECPR_RUN_OPEN: &str = r#"<hp:run charPrIDRef="0"><hp:secPr "#;

// [#1407] 템플릿의 하드코딩 본문 colPr(단 정의) — 단일 단 기본값. 첫 문단 IR 에
// ColumnDef 가 있으면 이 anchor 를 IR 값으로 치환한다 (#1388 secPr 동형).
const TEMPLATE_BODY_COL_PR: &str = r#"<hp:ctrl><hp:colPr id="" type="NEWSPAPER" layout="LEFT" colCount="1" sameSz="1" sameGap="0"/></hp:ctrl>"#;

// [#1637] 템플릿의 하드코딩 secPr visibility — 전부 기본값(미숨김/SHOW_ALL). 원본의
// visibility 를 IR(SectionDef) 값으로 치환하지 않으면 hideFirstEmptyLine 등이 드롭되어
// (특히 ="1" → "0") 선두 빈줄이 가시화되며 본문이 밀려 페이지네이션이 달라진다 (#1388 동형).
const TEMPLATE_VISIBILITY: &str = r#"<hp:visibility hideFirstHeader="0" hideFirstFooter="0" hideFirstMasterPage="0" border="SHOW_ALL" fill="SHOW_ALL" hideFirstPageNum="0" hideFirstEmptyLine="0" showLineNumber="0"/>"#;

/// SectionDef 의 visibility 플래그를 `<hp:visibility>` 요소로 직렬화.
///
/// 파서가 IR 에 보존하는 6필드(hideFirstHeader/Footer/MasterPage·border·fill·
/// hideFirstEmptyLine)만 치환하고, IR 미보존 필드(hideFirstPageNum·showLineNumber)는
/// 템플릿 기본값("0")을 유지한다.
fn render_visibility(sd: &SectionDef) -> String {
    render_visibility_with_storage(sd, &crate::storage::Unbounded).expect("unbounded section XML")
}

fn render_visibility_with_storage<S: crate::storage::Storage>(
    sd: &SectionDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let b = |v: bool| if v { "1" } else { "0" };
    // [#5717] SHOW_FIRST(구역 첫 쪽에만 표시, flags bit 8/9)를 왕복 보존한다 —
    // 한글 2022 가 같은 문서를 HWPX 로 저장할 때 쓰는 어휘 그대로다(성북구 실측).
    let bf = |hide: bool, first: bool| {
        if hide {
            "HIDE_ALL"
        } else if first {
            "SHOW_FIRST"
        } else {
            "SHOW_ALL"
        }
    };
    xml_value(
        storage,
        format_args!(
            r#"<hp:visibility hideFirstHeader="{}" hideFirstFooter="{}" hideFirstMasterPage="{}" border="{}" fill="{}" hideFirstPageNum="0" hideFirstEmptyLine="{}" showLineNumber="0"/>"#,
            b(sd.hide_header),
            b(sd.hide_footer),
            b(sd.hide_master_page),
            bf(sd.hide_border, sd.first_page_border),
            bf(sd.hide_fill, sd.first_page_fill),
            b(sd.hide_empty_line),
        ),
    )
}

/// 템플릿의 visibility 고정 문자열을 IR 기반 값으로 1회 치환.
fn replace_visibility(xml: &str, sd: &SectionDef) -> String {
    replace_visibility_with_storage(xml, sd, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_visibility_with_storage<S: crate::storage::Storage>(
    xml: &str,
    sd: &SectionDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_replacen(
        xml,
        TEMPLATE_VISIBILITY,
        &render_visibility_with_storage(sd, storage)?,
        1,
        storage,
    )
}

/// [#1987] 템플릿 secPr 의 하드코딩 스칼라(spaceColumns, outlineShapeIDRef, memoShapeIDRef 등)를
/// IR 값으로 치환.
/// 각 속성은 템플릿 secPr 여는 태그에 정확히 1회 등장하므로 replacen(1)로 안전하다.
fn replace_secpr_scalars(xml: &str, sd: &SectionDef) -> String {
    replace_secpr_scalars_with_storage(xml, sd, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_secpr_scalars_with_storage<S: crate::storage::Storage>(
    xml: &str,
    sd: &SectionDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let out = xml_replacen(
        xml,
        r#"spaceColumns="1134""#,
        &xml_value(
            storage,
            format_args!(r#"spaceColumns="{}""#, sd.column_spacing),
        )?,
        1,
        storage,
    )?;
    // 구역 세로쓰기: 파서는 textDirection="VERTICAL" → text_direction=1 로 읽지만
    // (parser/hwpx/section.rs) 직렬화기는 이 필드를 재출력하지 않아, 세로쓰기 구역이
    // .hwpx 저장 시 HORIZONTAL 로 유실됐다. text_direction==1 일 때만 치환한다
    // (기본 0 문서는 템플릿 HORIZONTAL 유지). 템플릿엔 secPr 에만 등장하므로 replacen(1) 안전.
    let out = if sd.text_direction == 1 {
        xml_replacen(
            out,
            r#"textDirection="HORIZONTAL""#,
            r#"textDirection="VERTICAL""#,
            1,
            storage,
        )?
    } else {
        out
    };
    let out = xml_replacen(
        out,
        r#"outlineShapeIDRef="1""#,
        &xml_value(
            storage,
            format_args!(r#"outlineShapeIDRef="{}""#, sd.outline_numbering_id),
        )?,
        1,
        storage,
    )?;

    // [#2779] 메모 모양 참조. 파서가 secPr@memoShapeIDRef 를 memo_shape_id 로 읽지만
    // 직렬화가 템플릿 상수 "0" 만 방출해, 메모 모양이 지정된 구역이 저장마다 0 으로
    // 리셋됐다(실측 14 secPr/9 파일). 템플릿 secPr 여는 태그에 정확히 1회 등장하고
    // 기본 SectionDef 도 0 이라 기본 문서 출력은 바이트 동일하다.
    let out = xml_replacen(
        out,
        r#"memoShapeIDRef="0""#,
        &xml_value(
            storage,
            format_args!(r#"memoShapeIDRef="{}""#, sd.memo_shape_id),
        )?,
        1,
        storage,
    )?;

    // 기본 탭 폭. HWPX 파서는 secPr 의 tabStop 속성을 default_tab_spacing 으로 읽는다
    // (parser/hwpx/section.rs). 치환하지 않으면 열었던 값과 무관하게 늘 템플릿 상수
    // 8000 으로 저장돼, 탭 정렬이 원본과 어긋난다.
    //
    // 다만 SectionDef 는 derive(Default) 라 파싱을 거치지 않은 문서(신규 작성 등)에서는
    // 0 이다. 0 을 그대로 내보내면 탭 폭이 0 이 되어 지금보다 나빠지므로, 값이 있을 때만
    // 치환하고 없으면 템플릿 기본값을 유지한다.
    let out = if sd.default_tab_spacing != 0 {
        xml_replacen(
            out,
            r#"tabStop="8000""#,
            &xml_value(
                storage,
                format_args!(r#"tabStop="{}""#, sd.default_tab_spacing),
            )?,
            1,
            storage,
        )?
    } else {
        out
    };

    // 구역 그리드와 시작 번호. 템플릿 상수가 모두 0 이고 SectionDef 기본값도 0 이라
    // 기본 문서의 출력은 그대로이며, 파싱된 문서에서만 실제 값이 살아난다.
    let out = xml_replacen(
        out,
        r#"<hp:grid lineGrid="0" charGrid="0" wonggojiFormat="0"/>"#,
        &xml_value(
            storage,
            format_args!(
                r#"<hp:grid lineGrid="{}" charGrid="{}" wonggojiFormat="{}"/>"#,
                sd.line_grid,
                sd.char_grid,
                u8::from(sd.wonggoji_format())
            ),
        )?,
        1,
        storage,
    )?;
    xml_replacen(
        out,
        r#"<hp:startNum pageStartsOn="BOTH" page="0" pic="0" tbl="0" equation="0"/>"#,
        &xml_value(
            storage,
            format_args!(
                r#"<hp:startNum pageStartsOn="{}" page="{}" pic="{}" tbl="{}" equation="{}"/>"#,
                page_starts_on_str(sd.page_num_type),
                sd.page_num,
                sd.picture_num,
                sd.table_num,
                sd.equation_num
            ),
        )?,
        1,
        storage,
    )
}

/// 쪽 번호 시작 종류(SectionDef.page_num_type, 0/1/2) → HWPX `pageStartsOn` 토큰.
/// 파서 `parse_start_num` 의 역매핑. 0(이어서)=BOTH, 1(홀수)=ODD, 2(짝수)=EVEN.
fn page_starts_on_str(page_num_type: u8) -> &'static str {
    match page_num_type {
        1 => "ODD",
        2 => "EVEN",
        _ => "BOTH",
    }
}

/// [#1984] noteLine `type` u8 → HWPX 문자열 (parser noteLine type 역매핑).
fn note_line_type_str(t: u8) -> &'static str {
    super::header::border_line_type_str(super::header::border_line_type_from_code(t))
}

/// [#1984] separator_color(0xBBGGRR LE) → "#RRGGBB" (parser noteLine color 역매핑).
fn note_color_hex(c: u32) -> String {
    note_color_hex_with_storage(c, &crate::storage::Unbounded).expect("unbounded section XML")
}

fn note_color_hex_with_storage<S: crate::storage::Storage>(
    c: u32,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    super::shape::color_to_hex_with_storage(c, storage)
}

/// [#1984] FootnoteShape → `<hp:noteLine .../>` + `<hp:noteSpacing .../>` 두 요소.
fn render_note_line_spacing(shape: &crate::model::footnote::FootnoteShape) -> (String, String) {
    render_note_line_spacing_with_storage(shape, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn render_note_line_spacing_with_storage<S: crate::storage::Storage>(
    shape: &crate::model::footnote::FootnoteShape,
    storage: &S,
) -> Result<(String, String), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let note_line = xml_value(
        storage,
        format_args!(
            r#"<hp:noteLine length="{}" type="{}" width="{} mm" color="{}"/>"#,
            shape.separator_length,
            note_line_type_str(shape.separator_line_type),
            line_width_mm(shape.separator_line_width),
            note_color_hex_with_storage(shape.separator_color, storage)?,
        ),
    )?;
    let note_spacing = xml_value(
        storage,
        format_args!(
            r#"<hp:noteSpacing betweenNotes="{}" belowLine="{}" aboveLine="{}"/>"#,
            shape.between_notes_margin_hu(),
            shape.separator_below_margin_hu(),
            shape.separator_above_margin_hu(),
        ),
    )?;
    Ok((note_line, note_spacing))
}

/// FootnoteNumbering → HWPX `type` 토큰.
///
/// [#6872] **한컴이 실제로 쓰는 토큰만 낸다.** 종전에는 `RESTART_PAGE`·`RESTART_SECTION`
/// 을 냈는데, rhwp 파서는 그것을 수용하지만(그래서 x2x 가 자기 눈에는 무결했다) 한글은
/// 못 알아듣고 **연속 번호로 떨어진다** — 쪽마다 1) 로 재시작하던 각주가 왕복 뒤
/// 1) 2) 3) … 으로 이어진다(156584446 정답지 PDF 실측).
///
/// 코퍼스 실측이 토큰을 확정한다 — 원본 HWPX 3,391 파일의 `<hp:numbering type>` 은
/// `CONTINUOUS` 7,640 · `ON_PAGE` 12 뿐이고 `RESTART_*` 는 **0건**이다.
fn note_numbering_str(numbering: crate::model::footnote::FootnoteNumbering) -> &'static str {
    use crate::model::footnote::FootnoteNumbering::*;
    match numbering {
        Continue => "CONTINUOUS",
        RestartSection => "ON_SECTION",
        RestartPage => "ON_PAGE",
    }
}

fn render_note_numbering(shape: &crate::model::footnote::FootnoteShape) -> String {
    render_note_numbering_with_storage(shape, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn render_note_numbering_with_storage<S: crate::storage::Storage>(
    shape: &crate::model::footnote::FootnoteShape,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            r#"<hp:numbering type="{}" newNum="{}"/>"#,
            note_numbering_str(shape.numbering),
            shape.start_number,
        ),
    )
}

/// [#2779] FootnotePlacement → HWPX `placement/@place` 토큰 (컨텍스트 키 역매핑).
///
/// OWPML 스키마(ParaList: footNotePr/endNotePr 의 placement@place)는 각주와 미주에
/// 서로 다른 열거를 두지만, 두 열거는 HWP5 `attr` bits 8-9 의 같은 코드 공간을 쓴다
/// (모델 주석 「각 단마다 따로 배열 / 문서의 마지막」과 동일한 대응):
///
/// | 코드 | FootnotePlacement | 각주 토큰          | 미주 토큰       |
/// |------|-------------------|--------------------|-----------------|
/// | 0    | EachColumn        | EACH_COLUMN        | END_OF_DOCUMENT |
/// | 1    | BelowText         | MERGED_COLUMN      | END_OF_SECTION  |
/// | 2    | RightColumn       | RIGHT_MOST_COLUMN  | (없음)          |
///
/// 즉 코드↔토큰은 컨텍스트를 아는 한 각 컨텍스트 안에서 전단사이므로, 호출자가
/// 자기가 각주/미주 중 무엇을 렌더하는지 알려주면 무손실 역매핑이 된다.
/// 미주에 코드 2(RightColumn)가 들어오는 비정상 IR 은 스키마에 대응 토큰이 없어
/// 기본값 `END_OF_DOCUMENT` 로 강등한다.
fn note_place_str(
    placement: crate::model::footnote::FootnotePlacement,
    is_end_note: bool,
) -> &'static str {
    use crate::model::footnote::FootnotePlacement::*;
    if is_end_note {
        match placement {
            BelowText => "END_OF_SECTION",
            // EachColumn 및 스키마 밖 RightColumn → 기본값.
            _ => "END_OF_DOCUMENT",
        }
    } else {
        match placement {
            BelowText => "MERGED_COLUMN",
            RightColumn => "RIGHT_MOST_COLUMN",
            EachColumn => "EACH_COLUMN",
        }
    }
}

/// [#2779] FootnoteShape → `<hp:placement .../>` (place + beneathText).
fn render_note_placement(
    shape: &crate::model::footnote::FootnoteShape,
    is_end_note: bool,
) -> String {
    render_note_placement_with_storage(shape, is_end_note, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn render_note_placement_with_storage<S: crate::storage::Storage>(
    shape: &crate::model::footnote::FootnoteShape,
    is_end_note: bool,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            r#"<hp:placement place="{}" beneathText="{}"/>"#,
            note_place_str(shape.placement, is_end_note),
            u8::from(shape.print_inline_after_text),
        ),
    )
}

/// [#2742] NumberFormat → HWPX `autoNumFormat/@type` 토큰.
///
/// 파서 `FootnoteShape::number_format_from_name` 의 UPPER_SNAKE 분기 역매핑이며,
/// 같은 파일의 `note_line_type_str`·`note_numbering_str` 와 동형이다. 이름이 모델
/// variant 와 다른 항목(UpperRoman=ROMAN_CAPITAL, HangulDigit=HANGUL_PHONETIC,
/// HanjaDigit=IDEOGRAPH, HanjaGapEul=DECAGON_CIRCLE, FourSymbol=SYMBOL)은 파서 표기를
/// 그대로 따른다.
fn note_number_format_str(format: crate::model::footnote::NumberFormat) -> &'static str {
    super::header::numbering_format_str(
        crate::model::footnote::FootnoteShape::number_format_attr_code(format) as u8,
    )
}

/// [#2742] 주석 장식 문자(IR `char`) → HWPX 속성값.
///
/// `'\0'` 은 "미지정" 규약이므로(`object_ops/note.rs` 가 `suffix_char == '\0'` 을 기본값
/// 폴백으로 해석) 템플릿 기본값 `fallback` 을 유지한다. 파싱을 거치지 않은 문서에서
/// IR 이 0 이면 템플릿 상수를 남기는 `tabStop`/`textDirection` 치환과 같은 패턴이다.
///
/// `'\0'` 외의 제어문자(< 0x20)도 같은 폴백으로 보낸다. HWP5 의 장식 문자는 WCHAR 원값이라
/// 이론상 제어문자가 올 수 있고, 그대로 방출하면 XML 1.0 이 금지하는 문자가 되어 저장본을
/// 한컴이 열지 못한다. 같은 파일 `render_hp_t_content` 도 `< 0x20` 을 방출 대상에서 뺀다.
/// (코퍼스 828 note shape 의 장식 문자는 전부 `'\0'` 또는 출력 가능 문자였다.)
fn note_deco_char_attr(c: char, fallback: &str) -> String {
    note_deco_char_attr_with_storage(c, fallback, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn note_deco_char_attr_with_storage<S: crate::storage::Storage>(
    c: char,
    fallback: &str,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    Ok(if (c as u32) < 0x20 {
        xml_value(storage, fallback)?
    } else {
        xml_escape_with_storage(&xml_value(storage, c)?, storage)?
    })
}

/// [#2742] FootnoteShape → `<hp:autoNumFormat .../>`.
/// 속성 순서는 템플릿·한컴 실물과 같이 type → userChar → prefixChar → suffixChar → supscript.
fn render_auto_num_format(shape: &crate::model::footnote::FootnoteShape) -> String {
    render_auto_num_format_with_storage(shape, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn render_auto_num_format_with_storage<S: crate::storage::Storage>(
    shape: &crate::model::footnote::FootnoteShape,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#6872] 번호 모양이 **사용자 기호**면 표시는 그 기호 하나로 끝난다 — 한컴도
    // `suffixChar` 를 비운다(코퍼스 HWPX 3,418건의 노트 모양 7,778개 중 `suffixChar=""`
    // 는 1개이고 그것이 유일한 `USER_CHAR` 다). 이때 기본값 `)` 를 채우면 표시가 `*` 에서
    // `*)` 로 바뀐다. 숫자 계열(7,651개가 `)`)의 폴백은 그대로 둔다.
    // Preserve explicit source emptiness for every format, including digits.
    let suffix_fallback = if shape.deco_chars_from_source
        || shape.number_format == crate::model::footnote::NumberFormat::UserChar
    {
        ""
    } else {
        ")"
    };
    xml_value(
        storage,
        format_args!(
            r#"<hp:autoNumFormat type="{}" userChar="{}" prefixChar="{}" suffixChar="{}" supscript="{}"/>"#,
            note_number_format_str(shape.number_format),
            note_deco_char_attr_with_storage(shape.user_char, "", storage)?,
            note_deco_char_attr_with_storage(shape.prefix_char, "", storage)?,
            note_deco_char_attr_with_storage(shape.suffix_char, suffix_fallback, storage)?,
            u8::from(shape.number_code_superscript),
        ),
    )
}

/// [#2742] 템플릿의 하드코딩 autoNumFormat — 각주/미주 두 슬롯의 문자열이 동일하다.
const TEMPLATE_AUTO_NUM_FORMAT: &str =
    r#"<hp:autoNumFormat type="DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="0"/>"#;

/// `needle` 의 처음 두 출현을 각각 `first`/`second` 로 치환한다. 치환 결과가 needle
/// 과 같아도 안전하다(연쇄 replacen 은 replacement==needle 일 때 두 번째가 첫 슬롯을
/// 다시 잡는 버그가 있어 각주/미주 numbering 처럼 fn/en 템플릿 문자열이 동일한 경우
/// 위치 기반 분할이 필요하다). needle 이 2회 미만이면 원본을 반환한다.
fn replace_first_two(haystack: &str, needle: &str, first: &str, second: &str) -> String {
    replace_first_two_with_storage(haystack, needle, first, second, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_first_two_with_storage<S: crate::storage::Storage>(
    haystack: &str,
    needle: &str,
    first: &str,
    second: &str,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut parts = haystack.splitn(3, needle);
    Ok(match (parts.next(), parts.next(), parts.next()) {
        (Some(a), Some(b), Some(c)) => {
            xml_value(storage, format_args!("{a}{first}{b}{second}{c}"))?
        }
        _ => xml_value(storage, haystack)?,
    })
}

/// [#1984] 템플릿 footNotePr/endNotePr 의 하드코딩 noteLine·noteSpacing 을 IR 값으로 치환.
/// 미치환 시 각주 구분선 위/아래 여백·주석간격이 항상 기본값(aboveLine=850 등)으로 방출돼
/// 각주 zone 높이가 달라지고, 각주 있는 페이지의 본문 가용높이가 어긋나 표 분할·페이지 수가
/// 갈린다(1543000: 각주 overhead 32.83→19.39px → p141 표 1행/3행 → 192/190쪽). 파서는
/// 값을 FootnoteShape 로 수집하나 직렬화가 템플릿 상수만 방출하던 결함.
fn replace_footnote_shape(xml: &str, sd: &SectionDef) -> String {
    replace_footnote_shape_with_storage(xml, sd, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_footnote_shape_with_storage<S: crate::storage::Storage>(
    xml: &str,
    sd: &SectionDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#2742] 번호 모양·사용자 기호·앞/뒤 장식 문자·위첨자. 파서는 HWPX(autoNumFormat)와
    // HWP5(FOOTNOTE_SHAPE attr) 양쪽에서 이 5필드를 FootnoteShape 로 읽지만 직렬화가
    // 템플릿 상수만 방출해, 저장할 때마다 구역 각주/미주 모양이 한컴 기본값으로 리셋됐다.
    // 새 주석 삽입은 이 모양을 기본값으로 쓰므로(object_ops/note.rs) 저장본에서는 미주가
    // 「문1)」 대신 「1)」로 매겨진다(실측: 코퍼스 330파일 중 18파일 · note shape 19개).
    // 각주/미주 템플릿 문자열이 완전히 같아 연쇄 replacen 은 두 번째 슬롯을 못 잡는다 —
    // numbering 과 같은 사유로 위치 기반 2회 치환을 쓴다.
    let xml = replace_first_two_with_storage(
        xml,
        TEMPLATE_AUTO_NUM_FORMAT,
        &render_auto_num_format_with_storage(&sd.footnote_shape, storage)?,
        &render_auto_num_format_with_storage(&sd.endnote_shape, storage)?,
        storage,
    )?;
    // 템플릿: 첫 noteLine(length="-1")·noteSpacing(betweenNotes="283") = 각주,
    // 둘째(length="14692344"·betweenNotes="0") = 미주.
    let (fn_line, fn_spacing) = render_note_line_spacing_with_storage(&sd.footnote_shape, storage)?;
    let (en_line, en_spacing) = render_note_line_spacing_with_storage(&sd.endnote_shape, storage)?;
    let out = xml_replacen(
        xml_replacen(
            xml_replacen(
                xml_replacen(
                    xml,
                    r##"<hp:noteLine length="-1" type="SOLID" width="0.12 mm" color="#000000"/>"##,
                    &fn_line,
                    1,
                    storage,
                )?,
                r#"<hp:noteSpacing betweenNotes="283" belowLine="567" aboveLine="850"/>"#,
                &fn_spacing,
                1,
                storage,
            )?,
            r##"<hp:noteLine length="14692344" type="SOLID" width="0.12 mm" color="#000000"/>"##,
            &en_line,
            1,
            storage,
        )?,
        r#"<hp:noteSpacing betweenNotes="0" belowLine="567" aboveLine="850"/>"#,
        &en_spacing,
        1,
        storage,
    )?;
    // 번호 매기기(각주 번호 종류 + 시작 번호). 템플릿은 fn/en 모두
    // `type="CONTINUOUS" newNum="1"` 로 동일해, 미치환 시 페이지/구역마다
    // 새로 매기거나 시작 번호가 1이 아닌 문서가 저장 때 연속·1로 되돌아간다.
    // fn/en 템플릿 문자열이 같으므로 위치 기반 2회 치환을 쓴다.
    let out = replace_first_two_with_storage(
        &out,
        r#"<hp:numbering type="CONTINUOUS" newNum="1"/>"#,
        &render_note_numbering_with_storage(&sd.footnote_shape, storage)?,
        &render_note_numbering_with_storage(&sd.endnote_shape, storage)?,
        storage,
    )?;
    // placement — 배치 방법(place)과 beneathText(본문 아래 바로 이어 출력).
    //
    // beneathText 는 같은 요소의 독립 bool 이라 종전에도 IR 반영됐다(템플릿 "0" 고정
    // 이라 저장 때마다 꺼지던 결함). [#2779] place 는 종전에 템플릿 상수
    // (EACH_COLUMN/END_OF_DOCUMENT)를 그대로 방출해, 통단·오른쪽단 각주와 구역끝
    // 미주가 저장마다 기본 배치로 되돌아갔다. 컨텍스트 키 역매핑(note_place_str)으로
    // 각주/미주 각각의 스키마 토큰을 방출한다.
    //
    // 각주 슬롯의 방출 토큰은 EACH_COLUMN/MERGED_COLUMN/RIGHT_MOST_COLUMN 셋 뿐이라
    // 미주 앵커(END_OF_DOCUMENT)를 새로 만들어내지 않는다 — 연쇄 replacen(1) 이
    // 서로의 슬롯을 훔칠 수 없다(기존 코드와 동일 근거).
    xml_replacen(
        xml_replacen(
            out,
            r#"<hp:placement place="EACH_COLUMN" beneathText="0"/>"#,
            &render_note_placement_with_storage(&sd.footnote_shape, false, storage)?,
            1,
            storage,
        )?,
        r#"<hp:placement place="END_OF_DOCUMENT" beneathText="0"/>"#,
        &render_note_placement_with_storage(&sd.endnote_shape, true, storage)?,
        1,
        storage,
    )
}

/// 레퍼런스 기준 줄 레이아웃 파라미터.
const VERT_STEP: u32 = 1600; // vertsize(1000) + spacing(600)

/// 탭 확장 데이터(`tab_extended`)가 없는 "암묵적 기본 탭"을 위한 `<hp:tab width>` 마커.
///
/// OWPML `<hp:tab>` 은 구조상 `width`/`leader`/`type` 이 모두 필수라 값 없음을 표현할 수
/// 없다(#4403). 예전에는 여기 고정 상수 `TAB_DEFAULT_WIDTH = 4000`(한컴 실제 기본 탭 간격,
/// `secPr@tabStopVal` 실측·HWP5 스펙 "기본 탭 간격" 필드와 일치 — 상수 자체는 정확했다)을
/// 채웠는데, 렌더러(`renderer/layout/text_measurement.rs` 인라인 탭 처리)는 `tab_extended`
/// 항목이 있으면 그 `width` 를 "이 탭의 실제 계산된 전진량"으로 신뢰해 커서 위치에 그대로 더한다
/// (`total + width`) — 탭 앞 텍스트 폭이나 문단의 실제 `TabDef`(좌/우/가운데 정렬, 커스텀 위치)
/// 를 무시한다. 그 결과 재적재 후 탭 뒤 텍스트가 원래와 다른 위치에 그려진다: 목차처럼 "제목 +
/// 탭 + 쪽번호"인 문단에서 원본은 문단의 우측 정렬 `TabDef` 로 쪽번호가 우측 끝에 정렬되는데,
/// 라운드트립 후에는 이 탭이 명시적 LEFT 로 굳어져 제목 바로 뒤에 고정 거리만큼만 전진한다
/// (실측: `samples/SO-SUEOP.hwp` 자기 라운드트립 `render-diff`, 목차 페이지 최대 변위 470px).
///
/// `width=0` 은 실제 탭에서 나올 수 없는 값이다(폭 0인 탭은 시각적으로 아무 효과가 없어 한컴도
/// 만들지 않는다) — 그래서 "원본에 계산된 탭 폭 데이터가 없었다"는 마커로 안전하게 쓴다.
/// HWPX 파서(`parser/hwpx/section.rs`)는 `width=0` 인 `<hp:tab>` 을 만나면 `tab_extended`
/// 항목을 만들지 않고 비워 둔다 — HWP5 바이너리 직렬화기의 동형 널 마커(`serializer/body_text.rs`,
/// #1892)와 같은 규약이다. 그러면 렌더러는 이 문단의 실제 `TabDef`/커서 위치 기준으로
/// `find_next_tab_stop` 을 통해 탭 정지를 다시 계산해, 원본과 같은 경로를 탄다. 한컴 앱 자신도
/// 이 값을 열 때 재계산하는 것으로 보여(주석 원문 "한컴이 열면서 재계산하지만 초기값으로 필요"),
/// `width=0` 은 실제 한컴에서 다시 열 때도 안전하다.
const TAB_NO_DATA_WIDTH_MARKER: u32 = 0;

/// Stage 2 진입점. `ctx` 는 Stage 3+ 에서 파라미터 검증에 사용.
pub fn write_section(
    section: &Section,
    doc: &Document,
    index: usize,
    ctx: &mut SerializeContext,
) -> Result<Vec<u8>, SerializeError> {
    write_section_with_storage(section, doc, index, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_section_with_storage<S: crate::storage::Storage>(
    section: &Section,
    doc: &Document,
    index: usize,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<Vec<u8>, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let section =
        super::super::column_sizes::for_export_with_storage(section, storage).map_err(xml_error)?;
    let section = section.as_ref();
    let mut vert_cursor: u32 = 0;

    let first_para = section.paragraphs.first();
    // [#1584] 첫 문단 렌더 직전 set — 본문 첫 ColumnDef(섹션 템플릿 흡수분)의 인라인
    // XML 방출만 1회 억제한다(슬롯 위치는 보존). 렌더 직후 reset 하여 추가 문단 누설 방지.
    ctx.body_coldef_template_pending = true;
    let first_parts = match first_para {
        Some(p) => render_paragraph_parts_with_storage(p, vert_cursor, ctx, storage),
        None => Ok((String::new(), String::new(), vert_cursor)),
    };
    ctx.body_coldef_template_pending = false;
    let (first_runs, first_linesegs, first_advance) = first_parts?;
    ctx.check_storage()?;
    vert_cursor = first_advance;

    // 치환은 모두 pristine 템플릿의 고정 anchor 에 대해 수행한다 (#1378):
    // linesegarray 치환을 콘텐츠(run 시퀀스) 삽입보다 먼저 두어, 콘텐츠에 포함된
    // 중첩 linesegarray(각주·머리말 등)가 anchor 탐색을 오염시키지 않도록 한다.
    let mut out = replace_first_linesegs_with_storage(EMPTY_SECTION_XML, &first_linesegs, storage)?;
    out = replace_page_pr_with_storage(&out, &section.section_def.page_def, storage)?;
    // 쪽 테두리/배경 — 템플릿의 하드코딩 borderFillIDRef="1"(테두리 없음)을 IR 값으로
    // 치환한다. 누락 시 문서의 쪽 테두리가 소실되어 외곽 4선 노드가 사라진다(#1388 동형).
    out = replace_page_border_fill_with_storage(&out, &section.section_def, storage)?;
    // [#1637] secPr visibility — 템플릿 고정값을 IR 값으로 치환(hideFirstEmptyLine 등 보존).
    out = replace_visibility_with_storage(&out, &section.section_def, storage)?;

    // [#1987] secPr 스칼라 필드 — 템플릿 하드코딩(spaceColumns="1134", outlineShapeIDRef="1")을
    // IR 값으로 치환한다. 미치환 시 원본이 spaceColumns=1130·outlineShapeIDRef=0 등이어도
    // 1134/1 로 방출돼 단 간격·개요번호 문단모양 참조가 어긋난다. ir-diff 는 secPr 스칼라를
    // 비교하지 않아 못 잡던 저장 충실도 결함.
    out = replace_secpr_scalars_with_storage(&out, &section.section_def, storage)?;

    // [#1984] 각주/미주 모양(구분선 여백·주석간격)을 IR 값으로 치환 — 미치환 시 각주 zone
    // 높이가 기본값으로 고정돼 각주 있는 페이지의 표 분할·페이지 수가 갈린다.
    out = replace_footnote_shape_with_storage(&out, &section.section_def, storage)?;

    // 바탕쪽(masterPage) — secPr 의 masterPageCnt 치환 + secPr 내부 끝에 idRef 참조 삽입.
    // 누락 시 라운드트립에서 바탕쪽 전체(그 안의 그림/표/문단 노드 포함)가 소실된다.
    // id 인덱스는 전 섹션 누적 전역값으로, mod.rs 의 파일 생성 인덱스와 정합한다.
    let master_pages = &section.section_def.master_pages;
    if !master_pages.is_empty() {
        let base: usize = doc.sections[..index]
            .iter()
            .map(|s| s.section_def.master_pages.len())
            .sum();
        let mut ids = storage.vec(master_pages.len()).map_err(xml_error)?;
        for k in 0..master_pages.len() {
            storage
                .push(
                    &mut ids,
                    xml_value(storage, format_args!("masterpage{}", base + k))?,
                )
                .map_err(xml_error)?;
        }
        out = xml_replacen(
            out,
            r#"masterPageCnt="0""#,
            &xml_value(
                storage,
                format_args!(r#"masterPageCnt="{}""#, master_pages.len()),
            )?,
            1,
            storage,
        )?;
        let refs = super::master_page::render_master_page_refs_with_storage(&ids, storage)?;
        out = xml_replacen(
            out,
            "</hp:secPr>",
            &xml_value(storage, format_args!("{refs}</hp:secPr>"))?,
            1,
            storage,
        )?;
    }

    // [#1407] 본문 단 정의(colPr) — 첫 문단 IR 의 ColumnDef 를 템플릿 하드코딩
    // colPr(colCount=1)에 치환한다. 본문(depth 0) ColumnDef 는 render_runs 인라인
    // 슬롯에서 제외되므로(#1379) 여기서 받지 않으면 단 정의가 손실된다(2단→1단 →
    // 페이지 넘침). #1388 secPr 여백 치환과 동형.
    if let Some(p) = first_para {
        if let Some(Control::ColumnDef(cd)) = p
            .controls
            .iter()
            .find(|c| matches!(c, Control::ColumnDef(_)))
        {
            out = xml_replacen(
                out,
                TEMPLATE_BODY_COL_PR,
                &render_col_pr_ctrl_with_storage(cd, storage)?,
                1,
                storage,
            )?;
        }
    }

    if let Some(p) = first_para {
        // 첫 문단 `<hp:p>` 태그를 IR 기반 속성으로 교체
        // (#1933) 본문 경로는 종전에 style_id 를 reference 하지 않았다 — emit 만
        // 강등해 미등록 ID 방출을 막고, 참조 집합/assert 동작은 종전 유지한다.
        let pid = ctx.next_para_id();
        let sid = ctx.effective_style_id(p.style_id);
        let new_p_tag = render_hp_p_open_with_storage(p, pid, sid, storage)?;
        out = xml_replacen(out, TEMPLATE_FIRST_P_TAG, &new_p_tag, 1, storage)?;

        // 섹션 첫 run(secPr/colPr 전용)의 charPrIDRef 를 첫 텍스트 run id 와 일치시킨다.
        // 파서는 이 run 시작에서도 (0, id) 를 기록하므로, id 가 다르면 재파싱 시
        // 가짜 (0, 0) entry 가 생긴다 (#1378 stage1 양상 ②).
        let first_cs = first_run_char_shape_id(p);
        if first_cs != 0 {
            let new_secpr_run = xml_value(
                storage,
                format_args!(r#"<hp:run charPrIDRef="{}"><hp:secPr "#, first_cs),
            )?;
            out = xml_replacen(out, TEMPLATE_SECPR_RUN_OPEN, &new_secpr_run, 1, storage)?;
        }

        // 템플릿의 텍스트 run 전체를 문단의 run 시퀀스(다중 run 분할 포함)로 1회 치환.
        out = xml_replacen(out, TEMPLATE_TEXT_RUN, &first_runs, 1, storage)?;

        // [#3367/#4433] 컨트롤 방출 순서를 IR 순서에 맞춘다 — HWP5 원본이
        // `[cold, secd]` 인 문단(field-01 실측: 전 구역 cold→secd)을 템플릿 고정
        // 순서(secPr → ctrl/colPr)로 내보내면 재파싱 IR 이 `[secd, cold]` 로
        // 뒤집혀 왕복 무손실 계약(ir-diff)이 깨진다. OWPML 스키마(run 의
        // choice, ParaList XML schema)는 순서를 규정하지 않고, 한컴 원산 실물도
        // colPr-before-secPr 20건 / colPr-after-secPr 315건으로 양쪽을 다 쓴다 —
        // 문서 순서가 곧 보존 대상이다. 파서(parse_ctrl/secPr arm)는 이미 문서
        // 순서를 보존하므로 방출만 IR 순서를 따르면 왕복이 닫힌다.
        let cold_before_secd = {
            let i_secd = p
                .controls
                .iter()
                .position(|c| matches!(c, Control::SectionDef(_)));
            let i_cold = p
                .controls
                .iter()
                .position(|c| matches!(c, Control::ColumnDef(_)));
            matches!((i_cold, i_secd), (Some(c), Some(s)) if c < s)
        };
        if cold_before_secd {
            if let Some(Control::ColumnDef(cd)) = p
                .controls
                .iter()
                .find(|c| matches!(c, Control::ColumnDef(_)))
            {
                // 위 #1407 치환이 이미 심어 둔 IR colPr 블록을 정확히 되찾아
                // (render_col_pr_ctrl 은 결정적) secPr 앞으로 옮긴다.
                let rendered = render_col_pr_ctrl_with_storage(cd, storage)?;
                if let Some(colpr_at) = out.find(&rendered) {
                    out.replace_range(colpr_at..colpr_at + rendered.len(), "");
                    if let Some(secpr_at) = out.find("<hp:secPr ") {
                        xml_insert(&mut out, secpr_at, &rendered, storage)?;
                    } else {
                        // secPr 미발견(비정상 템플릿) — 원위치 복원으로 무손실 유지.
                        xml_insert(&mut out, colpr_at, &rendered, storage)?;
                    }
                }
            }
        }
    }

    // 추가 문단: `</hp:p></hs:sec>` 직전에 `<hp:p>` 요소를 삽입.
    if section.paragraphs.len() > 1 {
        let mut extra = String::new();
        for p in section.paragraphs.iter().skip(1) {
            let (runs, linesegs, advance) =
                render_paragraph_parts_with_storage(p, vert_cursor, ctx, storage)?;
            ctx.check_storage()?;
            vert_cursor = advance;
            let pid = ctx.next_para_id();
            let sid = ctx.effective_style_id(p.style_id);
            storage
                .push_str(
                    &mut extra,
                    &render_hp_p_open_with_storage(p, pid, sid, storage)?,
                )
                .map_err(xml_error)?;
            // [#4056] 후속 문단이 구역나누기(SectionDef)면 그 구역을 secPr 로 방출한다.
            // `render_runs` 는 SectionDef 슬롯을 hidden 처리해 XML 을 내지 않으므로
            // 여기서 내지 않으면 뒤 구역이 통째로 사라져 쪽나눔이 소실된다.
            if let Some(Control::SectionDef(sd)) = p
                .controls
                .iter()
                .find(|c| matches!(c, Control::SectionDef(_)))
            {
                storage
                    .push_str(
                        &mut extra,
                        &build_secpr_run_with_storage(sd, first_run_char_shape_id(p), storage)?,
                    )
                    .map_err(xml_error)?;
            }
            storage.push_str(&mut extra, &runs).map_err(xml_error)?;
            storage.push_str(&mut extra, &linesegs).map_err(xml_error)?;
            storage.push_str(&mut extra, "</hp:p>").map_err(xml_error)?;
        }
        out = xml_replacen(
            out,
            PARA_CLOSE,
            &xml_value(storage, format_args!("</hp:p>{}</hs:sec>", extra))?,
            1,
            storage,
        )?;
    }

    Ok(out.into_bytes())
}

/// IR의 Paragraph를 기반으로 `<hp:p>` 시작 태그를 생성.
///
/// `id` 는 문단 순서 기반(0, 1, 2, ...)로 할당한다. 한컴 샘플은 랜덤 해시도 쓰지만
/// 파서는 id 를 무시하므로 순차값으로 충분.
///
/// `style_id_ref` 는 호출자가 `ctx.effective_style_id(p.style_id)` 로 강등한 값
/// (미등록 스타일 → 0, #1933). 전 문단 경로가 이 함수를 거치므로 여기가 단일
/// 방출 지점이다.
pub(crate) fn render_hp_p_open(p: &Paragraph, id: u32, style_id_ref: u8) -> String {
    render_hp_p_open_with_storage(p, id, style_id_ref, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

pub(super) fn render_hp_p_open_with_storage<S: crate::storage::Storage>(
    p: &Paragraph,
    id: u32,
    style_id_ref: u8,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // 합성 쪽나눔(파서가 자연 쪽 경계에서 승격, HWP3)은 문서 내용이 아니라 조판
    // 힌트라 저장하지 않는다. 저장하면 한글 재조판의 자연 경계와 이중 작용해
    // 빈 쪽을 만든다(07615: 합성 138건이 264→329쪽 부풀림, 중화 시 264쪽 복원).
    let page_break = if (matches!(p.column_type, ColumnBreakType::Page)
        || p.raw_break_type & 0x04 != 0)
        && !p.page_break_synthesized
    {
        1
    } else {
        0
    };
    let column_break =
        if matches!(p.column_type, ColumnBreakType::Column) || p.raw_break_type & 0x08 != 0 {
            1
        } else {
            0
        };
    xml_value(
        storage,
        format_args!(
            r#"<hp:p id="{}" paraPrIDRef="{}" styleIDRef="{}" pageBreak="{}" columnBreak="{}" merged="0">"#,
            id, p.para_shape_id, style_id_ref, page_break, column_break,
        ),
    )
}

/// 문단 첫 run 의 charPrIDRef. IR의 `char_shapes[0].char_shape_id` 사용.
/// 비어있으면 0 (기본 글자모양) 반환.
pub(super) fn first_run_char_shape_id(p: &Paragraph) -> u32 {
    p.char_shapes.first().map(|r| r.char_shape_id).unwrap_or(0)
}

/// [#4056] 후속 구역(SectionDef)을 HWPX `<hp:secPr>` run 으로 방출한다.
///
/// HWP5 는 한 BodyText 섹션에 구역(secd)을 여럿 담을 수 있다(issue-505: 수식 4개가
/// 각 구역 = 4쪽). 종전 HWPX 직렬화기는 `render_runs` 에서 **모든 SectionDef 를 드롭**해
/// (첫 구역만 write_section 의 secPr 템플릿으로 살아남음) 뒤 구역들의 쪽나눔이 사라졌다
/// (issue-505: 4→1쪽). HWPX 는 한 section0.xml 안에 secPr 를 여럿 둘 수 있으므로(한글
/// 원본 실증: issue2019 10개·06544 63개), 뒤 구역마다 secPr 를 방출한다.
///
/// secPr 템플릿(`EMPTY_SECTION_XML`)에서 secPr 블록만 잘라 IR 값으로 치환한다 —
/// 커스터마이즈 앵커(pagePr·visibility·scalars·footNotePr·pageBorderFill)가 모두 secPr
/// 내부라 첫 구역과 같은 함수를 재사용한다. 바탕쪽(masterPage)은 이 경로에서 미지원
/// (`masterPageCnt="0"` 유지) — 후속 구역의 바탕쪽은 드물다.
///
/// [#5873] 표 셀(subList) 안 문단도 같은 보완이 필요하다 —
/// `table.rs::write_sub_list_paragraphs` 가 이 함수를 재사용한다.
pub(super) fn build_secpr_run(sd: &SectionDef, first_cs: u32) -> String {
    build_secpr_run_with_storage(sd, first_cs, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

pub(super) fn build_secpr_run_with_storage<S: crate::storage::Storage>(
    sd: &SectionDef,
    first_cs: u32,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let start = EMPTY_SECTION_XML
        .find("<hp:secPr ")
        .expect("템플릿에 secPr 열기 태그가 있어야 함");
    let end = EMPTY_SECTION_XML[start..]
        .find("</hp:secPr>")
        .map(|e| start + e + "</hp:secPr>".len())
        .expect("템플릿에 secPr 닫기 태그가 있어야 함");
    let mut secpr = xml_value(storage, &EMPTY_SECTION_XML[start..end])?;
    secpr = replace_page_pr_with_storage(&secpr, &sd.page_def, storage)?;
    secpr = replace_page_border_fill_with_storage(&secpr, sd, storage)?;
    secpr = replace_visibility_with_storage(&secpr, sd, storage)?;
    secpr = replace_secpr_scalars_with_storage(&secpr, sd, storage)?;
    secpr = replace_footnote_shape_with_storage(&secpr, sd, storage)?;
    xml_value(
        storage,
        format_args!(r#"<hp:run charPrIDRef="{}">{}</hp:run>"#, first_cs, secpr),
    )
}

/// Paragraph 하나를 (완전한 `<hp:run>` 시퀀스 XML, `<hp:linesegarray>` 요소 XML,
/// 다음 vert_cursor)로 변환.
///
/// `<hp:lineseg>` 출력 원칙 (#177, #1380):
/// - `para.line_segs` 가 비어있지 않으면 **IR 값 그대로** `<hp:linesegarray>` 요소로 출력
/// - 비어있으면 **요소 자체를 방출 생략** (빈 문자열 반환) — 원본에 linesegarray 가
///   없는 문단의 보존 + rhwp 는 lineseg 를 새로 생산하지 않음. 한컴은 열 때 재계산
///
pub(crate) fn render_paragraph_parts(
    para: &Paragraph,
    vert_start: u32,
    ctx: &mut SerializeContext,
) -> (String, String, u32) {
    render_paragraph_parts_with_storage(para, vert_start, ctx, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

pub(super) fn render_paragraph_parts_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    vert_start: u32,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(String, String, u32), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // 첫 run의 secPr/colPr는 각각 실제 8유닛 슬롯이다. 원본에 없는 정의만
    // 템플릿이 추가하면 뒤 줄의 시작도 같은 폭만큼 전진해야 한다.
    let injected_prefix_units = if ctx.line_segs_on_paragraph_axis
        && ctx.sub_list_depth == 0
        && ctx.body_coldef_template_pending
    {
        let has_section = para
            .controls
            .iter()
            .any(|c| matches!(c, Control::SectionDef(_)));
        let has_column = para
            .controls
            .iter()
            .any(|c| matches!(c, Control::ColumnDef(_)));
        8 * (u32::from(!has_section) + u32::from(!has_column))
    } else {
        0
    };
    let (
        runs_xml,
        position_axis_intact,
        serialized_axis_end,
        mut hwp5_only_slot_positions,
        collapsed_slot_positions,
    ) = render_runs_with_storage(para, ctx, storage)?;

    (|| -> Result<(String, String, u32), SerializeError> {
        // [#4778] 위치 축이 무너진 문단(파서가 담지 못한 8유닛 슬롯 — 예: 차례표지
        // 0x0008 — 이 있거나 mismatch 폴백으로 컨트롤을 말미에 몰아쓴 문단)에는 저장
        // lineseg 를 방출하지 않는다. 방출 텍스트와 textpos 사다리가 어긋난 lineseg 를
        // 한글 2022 가 만나면 **그 문단부터 문서 끝까지 본문을 통째로 폐기**한다
        // (성년후견 h2x: -112,075자 실측 — lineseg 억제만으로 전량 회복). 방출을
        // 생략하면 한글이 열 때 재계산한다(#1380 과 같은 계약).
        // [#5563] 문단 축을 넘어서는 `textpos` 를 실은 줄은 내보내지 않는다. 원본이
        // 들고 있던 낡은 줄나눔 캐시가 그대로 옮겨 실리면(07990: 5개 문단이 길이 15 에
        // textpos 119 등) 한글 2022 가 "다음 줄은 119번째 글자에서 시작"을 14글자 문단에서
        // 해소하려다 **파일 개방이 끝나지 않는다**(COM Open 3,663초 미반환 실측). rhwp 는
        // 자기가 쓴 파일을 그대로 다시 읽으므로 `--verify` 로는 잡히지 않는다.
        //
        // 판정은 HWP5 저장기의 #4677 계약(`line_segs_within_text_axis`)을 그대로 쓴다 —
        // 경계 `text_start == char_count` 는 정상(한컴 자신이 쓰는 값)이라 `>` 이고, 범위
        // 밖이 나오면 그 앞까지만 남긴다. 첫 줄부터 범위 밖이면 요소를 통째로 생략해
        // 한글이 스스로 조판하게 한다(#1380 과 같은 계약).
        //
        // `char_count` 가 0 인 합성 IR(파서를 거치지 않은 문단)은 축 증거가 없으므로
        // 종전대로 원본 줄을 그대로 낸다.
        // `DocumentCore`는 빈 누름틀의 안내문 텍스트를 IR에서 비울 수 있지만,
        // 직렬화기는 그 Field 슬롯과 안내문을 다시 방출한다. 이때 IR `char_count`만
        // 상한으로 쓰면 필드 뒤의 정상 lineseg까지 잘려 셀 세로 정렬이 달라진다
        // (issue1893의 `textpos=25`). 실제 방출한 축 끝도 함께 써야 한다.
        //
        // [#5943] 그 상한을 쓰기 전에 **축을 HWPX 쪽으로 내린다**. HWP5 문단 축은 구역 정의와
        // 템플릿 흡수 단 정의에도 8유닛씩을 주지만 HWPX 문단에는 그 자리가 없다(`hp:secPr` 은
        // 구역 머리 run 소속). 그래서 구역 첫 문단에서 두 축이 16유닛 어긋나고, 원본 그대로 실은
        // `textpos` 가 한글이 세는 자리보다 뒤를 가리킨다. 한글 2024 는 그 문단부터 본문을
        // 폐기한다(02502.h2x: 9쪽 6,040자 → 1쪽 423자. `textpos` 를 48→40 으로 내리면 여전히
        // 실패, **32 로 내리면 완전 복원** — 축이 16 짧다는 직접 증거다). 2022 는 관대했다.
        // `char_count` 도 HWP5 축이므로 상한에서 같은 폭을 뺀다.
        //
        // 단 **HWPX 출처는 손대지 않는다**. `LineSeg::text_start` 는 파서가 파일 값을 그대로
        // 담으므로 출처마다 축이 다르다 — HWPX 원본의 `textpos` 는 이미 HWPX 축이라 한 번 더
        // 빼면 왕복이 깨진다(aift.hwpx 문단 0: `textpos 24 → 8`).
        // [#7526] rhwp 원본 마커 문서는 문단마다 가른다 — HWPX 에서 읽은 그대로인 문단(보정폭
        // 0 아님)만 날값을 둔다.
        if ctx.line_segs_on_hwpx_axis || para.hwpx_axis_shift != 0 {
            hwp5_only_slot_positions.clear();
        }
        // [#6871] 우리가 **접은** 슬롯은 출처와 무관하게 축에서 뺀다.
        //
        // 위 게이트가 다루는 `secd`·`cold` 는 HWPX 축에 **원래 없던** 자리라, HWPX 출처면
        // 이미 빠져 있어 다시 빼면 왕복이 깨진다. 반면 `#6869` 가 접는 중복 쪽번호는 원본
        // HWPX 축에 **분명히 있던** 자리다 — 접고도 빼지 않으면 `textpos` 가 방출 축보다
        // 길어져 한글이 파일을 열지 못한다.
        //
        // 실측(156730118, s39 `02482`): 원본은 한글이 1쪽으로 폐기하고 컨트롤만 접은 산출도
        // 마찬가지인데, 접기 + 축 −16 을 함께 하면 **2쪽으로 정상 개봉**한다. `#6871` 의 네
        // 문서가 모두 이 형상(한 문단에 쪽번호 3개)이다.
        storage
            .reserve(
                &mut hwp5_only_slot_positions,
                collapsed_slot_positions.len(),
            )
            .map_err(xml_error)?;
        hwp5_only_slot_positions.extend(collapsed_slot_positions);
        hwp5_only_slot_positions.sort_unstable();
        hwp5_only_slot_positions.dedup();
        let hwp5_only_units = 8 * hwp5_only_slot_positions.len() as u32;
        let serializable_line_segs = para.serializable_line_segs();
        let rebased_line_segs: Option<Vec<LineSeg>> = if (!hwp5_only_slot_positions.is_empty()
            || ctx.line_segs_on_paragraph_axis)
            && !serializable_line_segs.is_empty()
        {
            Some(
                storage
                    .collect(serializable_line_segs.iter().map(|seg| {
                        let text_start = if ctx.line_segs_on_paragraph_axis {
                            para.line_seg_text_start_of(seg.text_start)
                        } else {
                            seg.text_start
                        };
                        let shift = 8 * hwp5_only_slot_positions
                            .iter()
                            .filter(|&&pos| pos < text_start)
                            .count() as u32;
                        LineSeg {
                            text_start: text_start.saturating_sub(shift).saturating_add(
                                if text_start == 0 {
                                    0
                                } else {
                                    injected_prefix_units
                                },
                            ),
                            ..seg.clone()
                        }
                    }))
                    .map_err(xml_error)?,
            )
        } else {
            None
        };
        let source_line_segs = rebased_line_segs
            .as_deref()
            .unwrap_or(serializable_line_segs);

        let line_seg_axis_end = para
            .char_count
            .max(serialized_axis_end)
            .saturating_add(injected_prefix_units)
            .saturating_sub(hwp5_only_units);
        let axis_line_segs =
            if !crate::serializer::line_cache::can_serialize_hwpx_line_partition(para) {
                // The retained rows are an edit-reflow template, not a partition of
                // the current text. Omit the cache and let the consumer recompute it.
                &source_line_segs[..0]
            } else if line_seg_axis_end > 0 {
                line_segs_within_text_axis(source_line_segs, line_seg_axis_end)
            } else {
                source_line_segs
            };

        // [#5847] 줄 전체가 reflow 합성(bit31)인 문단 — 원본에 linesegarray 가 없어
        // rhwp 가 조판용으로 만든 줄이다. 파일로 내면 구역 누적 vertpos 와 bit31
        // 플래그가 그대로 실려 한글 2022 가 캐시를 신뢰하다 조판을 폐기한다
        // (08818: 81쪽 → 5쪽). 원본과 같게 방출을 생략해 한글이 재계산하게 한다
        // (#1380 계약). HWP5→HWPX materialize 는 별도 placeholder 를 쓰므로 무관.
        let all_synthetic = line_segs_are_all_synthetic(axis_line_segs);
        Ok(
            if !axis_line_segs.is_empty() && position_axis_intact && !all_synthetic {
                // IR 기반 출력 — 원본 lineseg 값 보존 (#177)
                //
                // [#5847] reflow 의 구역 단위 vpos 재계산이 원본 캐시 보유 문단의
                // vertpos 를 문서 누적 좌표로 덮어쓴 경우, 파싱 때 스냅샷해 둔 원본
                // 쪽-상대 좌표로 되돌려 낸다 — 누적 좌표가 파일로 나가면 한글 2022 가
                // 캐시를 신뢰해 조판을 폐기한다(08818: 81쪽 → 5쪽). axis 절단은 앞
                // 접두 슬라이스라 인덱스가 그대로 대응한다.
                let source_vpos = crate::serializer::line_cache::source_vertical_positions(para)
                    .map(|v| &v[..axis_line_segs.len()]);
                let linesegs = xml_value(
                    storage,
                    format_args!(
                        "{}{}{}",
                        LINESEG_SLOT_OPEN,
                        render_lineseg_array_from_ir_with_storage(
                            axis_line_segs,
                            source_vpos,
                            storage
                        )?,
                        LINESEG_SLOT_CLOSE
                    ),
                )?;
                let vert_end = next_vert_cursor_from_ir(axis_line_segs, source_vpos, vert_start);
                (runs_xml, linesegs, vert_end)
            } else {
                // IR 에 line_segs 없음 — linesegarray 방출 생략 (#1380)
                (runs_xml, String::new(), vert_start)
            },
        )
    })()
    .map_err(|error| SerializeError::XmlError(format!("HWPX lineseg: {error}")))
}

/// [#5847] 문단의 저장 줄이 **모두** reflow 합성(bit 31)인가 — HWPX 저장은 이런 문단의
/// `linesegarray` 를 내지 않는다. `export-hwpx --verify` 의 기대 IR 도 이 판정을 쓴다(#8306).
pub(crate) fn line_segs_are_all_synthetic(line_segs: &[LineSeg]) -> bool {
    !line_segs.is_empty()
        && line_segs
            .iter()
            .all(|s| s.tag & LineSeg::TAG_IMPLEMENTATION_PROPERTY != 0)
}

/// [#6869] HWPX 저장이 접는(내지 않는) 쪽 번호 위치 컨트롤의 인덱스 — 한 문단에서 첫 번째를
/// 뺀 나머지다. 방출은 `SerializeContext::para_page_num_pos_emitted` 로 같은 규칙을 따르고,
/// `export-hwpx --verify` 의 기대 IR 은 이 목록의 자리를 걷어낸다(#8306).
pub(crate) fn hwpx_collapsed_page_number_pos_indices(para: &Paragraph) -> Vec<usize> {
    para.controls
        .iter()
        .enumerate()
        .filter(|(_, control)| matches!(control, Control::PageNumberPos(_)))
        .map(|(index, _)| index)
        .skip(1)
        .collect()
}

/// [#5140] 한컴 사용자 정의 기호를 HWPX 표기(평면 15 보충 PUA)로 올린다.
///
/// 같은 글자를 HWP5 는 `0xA000 | X`, HWPX 는 `U+F0000 | X` 로 싣는다. IR 정본은 HWP5 쪽
/// 사영이므로 HWPX 로 낼 때만 올려 준다 — 리터럴로 내면 한글이 그 자리를 Yi 음절(U+A8xx)
/// 로 읽어 글자가 깨진다. 표에 없는 글자는 그대로 통과한다(`0xA813` 반례 참고).
///
/// 본문 텍스트(`hp:t`)와 글자겹침(`hp:compose/@composeText`) 두 경로 모두 이 규칙을 쓴다 —
/// 한글 SaveAs 실측에서 둘 다 예외 없이 평면 15 로 갔다.
fn hancom_symbol_for_hwpx(c: char) -> char {
    let Ok(unit) = u16::try_from(u32::from(c)) else {
        return c;
    };
    tags::hancom_symbol_to_plane15(unit)
        .and_then(char::from_u32)
        .unwrap_or(c)
}

/// 원본에서 글자들이 0 부터 연속으로 놓여 있었는가 — 곧 컨트롤이 전부 텍스트 뒤에 있어
/// mismatch 경로로 다시 써도 글자 위치가 밀리지 않는가.
///
/// mismatch 경로는 텍스트를 0 부터 연속으로 방출한다. 원본 `char_offsets` 가 그 누적 폭과
/// 같으면 방출 전후 좌표가 일치하므로 lineseg 의 `text_start` 가 그대로 유효하다.
fn text_positions_unshifted(para: &Paragraph) -> bool {
    let mut expected = 0u32;
    for (i, c) in para.text.chars().enumerate() {
        match para.char_offsets.get(i) {
            Some(&off) if off == expected => {}
            // char_offsets 가 없는 합성 IR 은 갭이 없다고 본다(종전 동작 유지).
            None => {}
            _ => return false,
        }
        expected = expected.saturating_add(char_utf16_width(c));
    }
    true
}

/// 문단 하나를 여러 `<hp:t>` 조각으로 나눠 방출해도 위치가 이어지는 커서.
///
/// 탭 확장·제목 차례 표시는 둘 다 "문단 축 위 n번째" 로만 식별되므로, run 분할·필드
/// 방출로 조각이 갈려도 같은 커서를 물려줘야 제자리에 실린다.
#[derive(Default)]
pub(crate) struct InlineCursor<'a> {
    /// 다음에 소비할 `tab_extended` 인덱스
    pub tab_idx: usize,
    /// 문단의 제목 차례 표시 전체 (문자 인덱스 오름차순)
    pub title_marks: &'a [TitleMark],
    /// [#6956] 문단의 형광펜 표지 전체 (문자 인덱스 오름차순)
    pub markpen_marks: &'a [crate::model::paragraph::MarkpenMark],
    /// 다음에 방출할 `markpen_marks` 인덱스
    pub markpen_idx: usize,
    /// [#5537] `title_marks[i]` 가 **앞(닫히는) run 소유**인가 — char_shapes 경계
    /// 유닛이 표시 끝 유닛과 일치하면 원본은 표시까지를 앞 run 에 뒀다는 증거다.
    /// 비어 있으면 전부 false(종전 동작: 다음 run 머리 방출).
    pub mark_owned_by_prev: &'a [bool],
    /// 다음에 방출할 `title_marks` 인덱스
    pub mark_idx: usize,
    /// [#8305] 조각 말미의 앞 run 소유 표시 방출을 잠시 미룬다 — 표시 시작 유닛에
    /// 글자 모양 경계가 있으면 글만 먼저 닫고 경계를 끊은 뒤 표시를 내야 한다.
    pub hold_prev_owned_marks: bool,
    /// 지금까지 방출한 문단 텍스트의 문자 수
    pub char_idx: usize,
    /// [#4895] 이 문단의 소프트 하이픈을 `<hp:hypen/>` 요소로 내릴지 여부.
    ///
    /// 한컴 원본은 소프트 하이픈을 리터럴 U+00AD 로도, 제어 표기로도 쓴다. 출처가
    /// 제어 표기(HWP5 `control_mask` 비트 24)일 때만 요소로 내려 원본 표기를 지킨다.
    pub soft_hyphen_as_element: bool,
    /// 개별 출처가 없는 기존 입력에서 문단 단위 제어 표기를 유지한다.
    pub nb_space_as_element: bool,
    /// 리터럴 문자는 고정폭 빈칸 요소와 구분하여 원래 표기로 저장한다.
    pub literal_figure_spaces: &'a [usize],
    /// 개별 문자 출처를 확인한 문단은 문단 단위 신호보다 이 위치를 우선한다.
    pub nb_space_control_indices: Option<&'a [usize]>,
    /// 개체로 방출해 텍스트 커서에서 소비하지 않은 모델 자리표 수.
    pub nb_space_skipped_source_scalars: usize,
}

impl InlineCursor<'_> {
    /// 현재 문자 위치에 걸린 제목 차례 표시를 전부 방출한다.
    fn flush_marks_at_cursor(&mut self, t_xml: &mut String, buf: &mut String) {
        self.flush_marks_at_cursor_with_storage(t_xml, buf, &crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn flush_marks_at_cursor_with_storage<S: crate::storage::Storage>(
        &mut self,
        t_xml: &mut String,
        buf: &mut String,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        // [#6956] 형광펜 표지 — 제목 차례 표시와 같은 자리에서 순서대로 흘린다.
        while let Some(m) = self.markpen_marks.get(self.markpen_idx) {
            if m.char_idx > self.char_idx {
                break;
            }
            flush_buf_with_storage(t_xml, buf, storage)?;
            match &m.color {
                Some(color) => storage
                    .push_str(
                        t_xml,
                        &xml_value(
                            storage,
                            format_args!(
                                r#"<hp:markpenBegin color="{}"/>"#,
                                xml_escape_with_storage(color, storage)?
                            ),
                        )?,
                    )
                    .map_err(xml_error)?,
                None => storage
                    .push_str(t_xml, "<hp:markpenEnd/>")
                    .map_err(xml_error)?,
            }
            self.markpen_idx += 1;
        }
        while let Some(m) = self.title_marks.get(self.mark_idx) {
            if m.char_idx > self.char_idx {
                break;
            }
            flush_buf_with_storage(t_xml, buf, storage)?;
            storage
                .push_str(
                    t_xml,
                    &xml_value(
                        storage,
                        format_args!(
                            r#"<hp:titleMark ignore="{}"/>"#,
                            if m.ignore { 1 } else { 0 }
                        ),
                    )?,
                )
                .map_err(xml_error)?;
            self.mark_idx += 1;
        }

        Ok(())
    }

    /// [#5537] 다음 미방출 표시가 현재 위치에 걸려 있고 **닫히는 run 소유**
    /// (char_shapes 경계 유닛 == 표시 끝 유닛 — 원본이 표시를 앞 run 에 뒀다는
    /// 증거)인가. 조각 말미 flush 의 발동 조건이다.
    fn has_pending_prev_owned_mark(&self) -> bool {
        self.title_marks
            .get(self.mark_idx)
            .is_some_and(|m| m.char_idx == self.char_idx)
            && self
                .mark_owned_by_prev
                .get(self.mark_idx)
                .copied()
                .unwrap_or(false)
    }

    /// [#5537] 조각 말미에서 닫히는 run 소유의 표시만 방출한다 — 나머지는
    /// 종전대로 다음 run 머리에서 flush 된다(한컴 실측 두 형태 공존).
    /// [#6956] 조각 말미에서 현재 문자 위치에 걸린 형광펜 표지를 마저 낸다.
    fn flush_markpen_at_fragment_end(&mut self, t_xml: &mut String, buf: &mut String) {
        self.flush_markpen_at_fragment_end_with_storage(t_xml, buf, &crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn flush_markpen_at_fragment_end_with_storage<S: crate::storage::Storage>(
        &mut self,
        t_xml: &mut String,
        buf: &mut String,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        while let Some(m) = self.markpen_marks.get(self.markpen_idx) {
            if m.char_idx > self.char_idx {
                break;
            }
            flush_buf_with_storage(t_xml, buf, storage)?;
            match &m.color {
                Some(color) => storage
                    .push_str(
                        t_xml,
                        &xml_value(
                            storage,
                            format_args!(
                                r#"<hp:markpenBegin color="{}"/>"#,
                                xml_escape_with_storage(color, storage)?
                            ),
                        )?,
                    )
                    .map_err(xml_error)?,
                None => storage
                    .push_str(t_xml, "<hp:markpenEnd/>")
                    .map_err(xml_error)?,
            }
            self.markpen_idx += 1;
        }

        Ok(())
    }

    fn flush_prev_owned_marks_at_fragment_end(&mut self, t_xml: &mut String, buf: &mut String) {
        self.flush_prev_owned_marks_at_fragment_end_with_storage(
            t_xml,
            buf,
            &crate::storage::Unbounded,
        )
        .expect("unbounded run XML")
    }

    fn flush_prev_owned_marks_at_fragment_end_with_storage<S: crate::storage::Storage>(
        &mut self,
        t_xml: &mut String,
        buf: &mut String,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        while self.has_pending_prev_owned_mark() {
            let m = &self.title_marks[self.mark_idx];
            flush_buf_with_storage(t_xml, buf, storage)?;
            storage
                .push_str(
                    t_xml,
                    &xml_value(
                        storage,
                        format_args!(
                            r#"<hp:titleMark ignore="{}"/>"#,
                            if m.ignore { 1 } else { 0 }
                        ),
                    )?,
                )
                .map_err(xml_error)?;
            self.mark_idx += 1;
        }

        Ok(())
    }
}

/// `<hp:t>...</hp:t>` 본문 생성 — 탭/소프트브레이크/XML escape 포함.
///
/// `tab_extended`: IR의 탭 확장 정보 목록. `cursor.tab_idx` 를 통해 탭 문자마다 순서대로
/// 참조한다. 항목이 없으면 "데이터 없음" 마커(width=`TAB_NO_DATA_WIDTH_MARKER`=0, leader=0,
/// type=1)를 방출한다(#4403) — 파서가 이를 인식해 `tab_extended` 를 만들지 않아야 렌더러가
/// 실제 `TabDef` 기준으로 탭 정지를 다시 계산한다.
pub(crate) fn render_hp_t_content(
    text: &str,
    tab_extended: &[[u16; 7]],
    cursor: &mut InlineCursor<'_>,
) -> String {
    render_hp_t_content_with_storage(text, tab_extended, cursor, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn render_hp_t_content_with_storage<S: crate::storage::Storage>(
    text: &str,
    tab_extended: &[[u16; 7]],
    cursor: &mut InlineCursor<'_>,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut t_xml = storage.string("<hp:t>").map_err(xml_error)?;
    let mut buf = String::new();
    // 조각 첫머리에서도 훑는다 — char_shape 경계가 표시 자리에 걸리면 그 표시만 담은
    // 빈 run 이 나오는데(한컴 실측: `<hp:t><hp:titleMark ignore="1"/></hp:t>`),
    // 문자 루프만으로는 문자가 없어 그 run 을 그냥 지나친다.
    cursor.flush_marks_at_cursor_with_storage(&mut t_xml, &mut buf, storage)?;
    for c in text.chars() {
        // 제목 차례 표시는 이 문자 **앞**에 놓인다.
        cursor.flush_marks_at_cursor_with_storage(&mut t_xml, &mut buf, storage)?;
        cursor.char_idx += 1;
        match c {
            '\t' => {
                flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
                let (width, leader, tab_type) = if let Some(ext) = tab_extended.get(cursor.tab_idx)
                {
                    cursor.tab_idx += 1;
                    if crate::model::paragraph::tab_ext_is_placeholder(ext) {
                        // [#7170] 자리표는 파서가 알아보는 마커 표기로 되돌린다.
                        (TAB_NO_DATA_WIDTH_MARKER, 0u16, 1u16)
                    } else {
                        (ext[0] as u32, ext[2] & 0x00ff, (ext[2] >> 8) & 0x00ff)
                    }
                } else {
                    (TAB_NO_DATA_WIDTH_MARKER, 0u16, 1u16)
                };
                storage
                    .push_str(
                        &mut t_xml,
                        &xml_value(
                            storage,
                            format_args!(
                                r#"<hp:tab width="{}" leader="{}" type="{}"/>"#,
                                width, leader, tab_type
                            ),
                        )?,
                    )
                    .map_err(xml_error)?;
            }
            '\n' => {
                flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
                storage
                    .push_str(&mut t_xml, "<hp:lineBreak/>")
                    .map_err(xml_error)?;
            }
            // HWP 코드 31과 fwSpace 요소는 기존 요소 표기를 유지한다(#4675).
            // 실제 리터럴 U+2007은 다른 문자 폭 계약이므로 요소로 바꾸지 않는다.
            '\u{2007}' => {
                if cursor
                    .literal_figure_spaces
                    .contains(&(cursor.char_idx - 1))
                {
                    storage.push_char(&mut buf, c).map_err(xml_error)?;
                } else {
                    flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
                    storage
                        .push_str(&mut t_xml, "<hp:fwSpace/>")
                        .map_err(xml_error)?;
                }
            }
            // [#5174] 묶음 빈칸은 U+2007 과 달리 **원본 표기를 따라간다.** 종전에는 늘
            // 리터럴로 냈는데(표현 강등), 원본이 제어·요소 표기였으면 한글 추출 텍스트에
            // 없던 공백이 생겨 원본과 어긋난다. 반대로 리터럴 원본을 요소로 바꾸면 글자가
            // 사라진다 — 그래서 어느 한쪽으로 강제하지 않고 출처를 보존한다.
            //
            // 원본 문자별 출처가 있으면 이를 우선한다. 문단 비트는 개별 출처가 없는
            // 기존 입력의 호환 신호이며, 혼용 문단의 각 표기를 구분하지 못한다.
            '\u{00A0}'
                if cursor.nb_space_control_indices.map_or(
                    cursor.nb_space_as_element,
                    |indices| {
                        indices
                            .binary_search(
                                &(cursor.char_idx - 1 + cursor.nb_space_skipped_source_scalars),
                            )
                            .is_ok()
                    },
                ) =>
            {
                flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
                storage
                    .push_str(&mut t_xml, "<hp:nbSpace/>")
                    .map_err(xml_error)?;
            }
            // [#4895] 소프트 하이픈(U+00AD)은 U+2007 과 달리 **원본 표기를 따라간다.**
            // 종전에는 늘 `<hp:hyphen/>` 요소로 내렸는데(#4776), 한컴이 만든 문서는
            // 두 표기를 다 쓴다(10k 코퍼스 실측: 리터럴 원본 58문서 · 제어 표기 원본 10문서).
            //
            // 한글 2022 대조 실측(01628, 하이픈 표기만 교체):
            //   `<hp:hyphen/>`     → 본문 2,477자 (한글이 글자를 버린다)
            //   raw U+00AD 리터럴  → 본문 2,478자, 원본과 textSha 일치
            //
            // 즉 한글은 요소·제어문자를 텍스트로 복원하지 않는다. 리터럴 원본을 요소로
            // 바꾸면 글자가 사라지고(10k 스윕 36경로 회귀), 반대로 제어 표기 원본을
            // 리터럴로 바꾸면 원본에 없던 글자가 생긴다. 그래서 출처 표기를 보존한다 —
            // HWP5 PARA_HEADER `control_mask` 비트 24 가 그 신호다(`cursor` 가 나른다).
            // [#7993] 요소 이름은 한/글 표기 `hp:hypen` 이다 — `hp:hyphen` 은 한/글이
            // 모르는 요소로 버린다(위 «글자를 버린다» 실측의 원인, 07615 h2x 265 → 264쪽).
            '\u{00AD}' if cursor.soft_hyphen_as_element => {
                flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
                storage
                    .push_str(&mut t_xml, "<hp:hypen/>")
                    .map_err(xml_error)?;
            }
            c if (c as u32) < 0x20 => { /* 기타 제어문자 무시 */ }
            c => storage
                .push_char(&mut buf, hancom_symbol_for_hwpx(c))
                .map_err(xml_error)?,
        }
    }
    // [#5537] 조각 말미 — 닫히는 run 소유의 표시(경계 유닛 = 표시 끝 유닛)는 여기서
    // 방출한다. 다음 run 머리로 넘기면 재파싱 char_shapes 경계가 8유닛 무너진다.
    if !cursor.hold_prev_owned_marks {
        cursor
            .flush_prev_owned_marks_at_fragment_end_with_storage(&mut t_xml, &mut buf, storage)?;
    }
    // [#6956] 형광펜 닫는 표지는 런 **끝**에 오는 것이 한컴 실측 형태다. 문자 루프는
    // 글자 **앞**에서만 흘리므로 여기서 현재 위치에 걸린 것을 마저 낸다.
    cursor.flush_markpen_at_fragment_end_with_storage(&mut t_xml, &mut buf, storage)?;
    flush_buf_with_storage(&mut t_xml, &mut buf, storage)?;
    storage.push_str(&mut t_xml, "</hp:t>").map_err(xml_error)?;
    Ok(t_xml)
}

/// 문단 콘텐츠를 `char_shapes` 경계 기준 다중 `<hp:run>` 으로 분할 출력하는 빌더 (#1378).
///
/// 파서(`src/parser/hwpx/section.rs`)는 각 `<hp:run charPrIDRef>` 시작 위치에서
/// `(utf16_pos, char_shape_id)` 를 기록한다. 동일 id라도 위치가 다른 경계는 보존한다.
/// 이 빌더는 그 역방향: `segs[i].0` (i ≥ 1) 위치에서 run 을 닫고 새 run 을 연다.
///
/// 경계 규칙 (구현계획서 1.2):
/// 1. 경계와 슬롯/문자가 같은 위치면 경계 먼저 — 해당 콘텐츠는 새 run 소속 (`cut_before`)
/// 2. 연속 동일 id 경계도 run으로 방출 — start_pos 보존 (#3739)
/// 3. `char_shapes` 가 비어있으면 단일 run `charPrIDRef="0"`
/// 4. `segs[0].start_pos > 0` 인 비정상 IR 도 첫 run 은 위치 0 부터 시작 (관용 처리)
/// 5. 빈 세그먼트는 `<hp:t></hp:t>` 로 방출 — 재파싱 시 run 시작 entry 위치 보존
struct RunSplitter {
    /// `(start_pos, char_shape_id)` — `[0]` 은 첫 run, `[1..]` 은 cut 경계.
    segs: Vec<(u32, u32)>,
    /// 다음 적용할 경계 인덱스.
    next: usize,
    /// 완성된 run 시퀀스.
    runs: String,
    /// 현재 run 의 내부 콘텐츠 버퍼.
    content: String,
}

impl RunSplitter {
    fn new(para: &Paragraph) -> Self {
        Self::new_with_storage(para, &crate::storage::Unbounded).expect("unbounded run XML")
    }

    fn new_with_storage<S: crate::storage::Storage>(
        para: &Paragraph,
        storage: &S,
    ) -> Result<Self, SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        // #3500/#3739: 연속 동일 id 도 start_pos 가 다르면 별도 run.
        let mut segs = storage
            .collect(
                para.char_shapes
                    .iter()
                    .map(|cs| (cs.start_pos, cs.char_shape_id)),
            )
            .map_err(xml_error)?;
        if segs.is_empty() {
            storage.push(&mut segs, (0, 0)).map_err(xml_error)?; // 규칙 3
        }
        Ok(Self {
            segs,
            next: 1,
            runs: String::new(),
            content: String::new(),
        })
    }

    /// 경계가 없는 단일 run 문단인지.
    fn single_run(&self) -> bool {
        self.segs.len() == 1
    }

    /// `pos` 위치의 콘텐츠 방출 전에 run 경계 적용이 필요한지 (flush 판단용).
    fn needs_cut(&self, pos: u32) -> bool {
        self.next < self.segs.len() && self.segs[self.next].0 <= pos
    }

    /// `pos` 이하 위치의 경계를 모두 적용 — 규칙 1 (경계 먼저, 콘텐츠는 새 run 소속).
    fn cut_before(&mut self, pos: u32) {
        self.cut_before_with_storage(pos, &crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn cut_before_with_storage<S: crate::storage::Storage>(
        &mut self,
        pos: u32,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        while self.needs_cut(pos) {
            self.cut_one_with_storage(storage)?;
        }

        Ok(())
    }

    /// 경계 1개만 적용한다 — 같은 위치에 여러 경계가 겹칠 때 그중 특정 run 에
    /// 콘텐츠를 넣어야 하는 경우에 쓴다 (#3545 안내문 잔재 복원).
    fn cut_one(&mut self) {
        self.cut_one_with_storage(&crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn cut_one_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        self.close_run_with_storage(storage)?;
        self.next += 1;

        Ok(())
    }

    /// 현재 열려 있는 run 의 `charPrIDRef`.
    fn current_shape_id(&self) -> u32 {
        self.segs[self.next - 1].1
    }

    /// 현재 run 을 `<hp:run charPrIDRef>` 로 감싸 완성 목록에 추가.
    fn close_run(&mut self) {
        self.close_run_with_storage(&crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn close_run_with_storage<S: crate::storage::Storage>(
        &mut self,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        storage
            .push_str(
                &mut self.runs,
                &xml_value(
                    storage,
                    format_args!(r#"<hp:run charPrIDRef="{}">"#, self.segs[self.next - 1].1),
                )?,
            )
            .map_err(xml_error)?;
        if self.content.is_empty() {
            // 규칙 5 — 빈 run 도 <hp:t></hp:t> 로 방출해 재파싱 시 entry 보존
            storage
                .push_str(&mut self.runs, "<hp:t></hp:t>")
                .map_err(xml_error)?;
        } else {
            storage
                .push_str(&mut self.runs, &self.content)
                .map_err(xml_error)?;
            self.content.clear();
        }
        storage
            .push_str(&mut self.runs, "</hp:run>")
            .map_err(xml_error)?;

        Ok(())
    }

    /// 잔여 경계(콘텐츠 끝 이후 시작)를 빈 run 으로 방출하고 마지막 run 을 닫는다.
    fn finish(mut self) -> String {
        self.finish_with_storage(&crate::storage::Unbounded)
            .expect("unbounded run XML")
    }

    fn finish_with_storage<S: crate::storage::Storage>(
        mut self,
        storage: &S,
    ) -> Result<String, SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        while self.next < self.segs.len() {
            self.close_run_with_storage(storage)?;
            self.next += 1;
        }
        self.close_run_with_storage(storage)?;
        Ok(self.runs)
    }
}

/// `<hp:ctrl><hp:fieldEnd beginIDRef=".."/></hp:ctrl>` 방출 공통 경로.
fn emit_field_end(out: &mut String, para: &Paragraph, fr: &FieldRange) {
    emit_field_end_with_storage(out, para, fr, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn emit_field_end_with_storage<S: crate::storage::Storage>(
    out: &mut String,
    para: &Paragraph,
    fr: &FieldRange,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    if let Some(Control::Field(f)) = para.controls.get(fr.control_idx) {
        // [Task #bookmark-hyperlink] 짝(matched) fieldEnd 자신의 fieldid 는 fieldBegin 의
        // id(f.field_id, beginIDRef 로 사용)와 별개 값 — 파싱된 fr.end_field_id 를 그대로
        // 되돌려 써야 한다. 과거엔 write_field_end 로 beginIDRef 만 쓰고 fieldid 는 항상
        // 누락시켰다(고아 fieldEnd 경로만 write_field_end_full 로 보존, 비대칭).
        let xml_result = if fr.end_field_id == 0 {
            checked_xml_result(
                writer_to_string_with_storage(|w| write_field_end(w, f.field_id), storage),
                storage,
            )?
        } else {
            checked_xml_result(
                writer_to_string_with_storage(
                    |w| write_field_end_full(w, f.field_id, fr.end_field_id),
                    storage,
                ),
                storage,
            )?
        };
        if let Ok(xml) = xml_result {
            storage.push_str(out, "<hp:ctrl>").map_err(xml_error)?;
            storage.push_str(out, &xml).map_err(xml_error)?;
            storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
        }
    }

    Ok(())
}

/// [#3545] 적재 정규화가 지운 **초기 상태 누름틀의 안내문 본문 run** 을 되살린다.
///
/// 한컴은 미기입 누름틀(`dirty="0"`)의 안내문을 파일에는 begin~end 사이 본문 run 으로
/// 유지하고 렌더·인쇄에서만 구분 취급한다 (`samples/hwpx/form-01.hwpx` 의
/// `<hp:run charPrIDRef="6"><hp:t>여기에 입력</hp:t></hp:run>`). rhwp 는 적재 시
/// `clear_initial_field_texts` 로 이를 빈 필드로 정규화하므로, 저장에서 되살리지 않으면
/// 파일 차원에서 텍스트가 영구 소실된다(XSD 는 통과하는 조용한 내용 소실).
///
/// IR 위치는 바꾸지 않고 **방출 XML 에만** 텍스트를 되돌린다. 다만 호출자는 반환된
/// UTF-16 길이를 직렬화 축에 반영해 뒤따르는 슬롯·lineseg를 실제 출력 위치에 맞춘다.
/// 재적재하면 같은 정규화가 다시 지우므로 IR 은 저장→적재 고정점을 유지한다.
fn emit_guide_residue(
    splitter: &mut RunSplitter,
    para: &Paragraph,
    fr: &FieldRange,
    pos: u32,
) -> u32 {
    emit_guide_residue_with_storage(splitter, para, fr, pos, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn emit_guide_residue_with_storage<S: crate::storage::Storage>(
    splitter: &mut RunSplitter,
    para: &Paragraph,
    fr: &FieldRange,
    pos: u32,
    storage: &S,
) -> Result<u32, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // 값이 채워진 필드는 본문 run 이 이미 있다 — 중복 주입 금지.
    if fr.start_char_idx != fr.end_char_idx {
        return Ok(0);
    }
    let Some(Control::Field(f)) = para.controls.get(fr.control_idx) else {
        return Ok(0);
    };
    // 수정됨(bit 15) 표식이 선 필드는 초기 상태가 아니다 — 사용자가 비운 값을 되살리면 안 된다.
    if f.is_dirty() {
        return Ok(0);
    }
    let Some(residue) = f.guide_residue.as_ref() else {
        return Ok(0);
    };
    if residue.text.is_empty() {
        return Ok(0);
    }
    // 잔재를 담던 run 의 경계까지만 먼저 끊는다 — 삭제 수술이 같은 위치에 접어 둔
    // zero-width run 들이 원본 서식(charPrIDRef)의 유일한 근거다.
    while splitter.needs_cut(pos) && splitter.current_shape_id() != residue.char_shape_id {
        splitter.cut_one_with_storage(storage)?;
    }
    // 안내문 잔재는 합성 텍스트라 탭 확장·제목 차례 표시가 없다 — 빈 커서로 낸다.
    let mut cursor = InlineCursor::default();
    storage
        .push_str(
            &mut splitter.content,
            &render_hp_t_content_with_storage(&residue.text, &[], &mut cursor, storage)?,
        )
        .map_err(xml_error)?;
    Ok(residue.text.encode_utf16().count() as u32)
}

/// `pos` 위치에서 경계를 적용하고 `fieldEnd` 를 방출한다.
/// 0-length 필드면 그 직전에 안내문 잔재를 복원한다 (#3545).
///
/// 반환값은 방출한 안내문 잔재의 UTF-16 축 길이다. 호출자는 fieldEnd의 8유닛에 이 값을
/// 더해 뒤따르는 슬롯과 lineseg의 실제 직렬화 축을 맞춘다.
fn emit_field_end_at(
    splitter: &mut RunSplitter,
    para: &Paragraph,
    fr: &FieldRange,
    pos: u32,
) -> u32 {
    emit_field_end_at_with_storage(splitter, para, fr, pos, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn emit_field_end_at_with_storage<S: crate::storage::Storage>(
    splitter: &mut RunSplitter,
    para: &Paragraph,
    fr: &FieldRange,
    pos: u32,
    storage: &S,
) -> Result<u32, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let guide_units = emit_guide_residue_with_storage(splitter, para, fr, pos, storage)?;
    splitter.cut_before_with_storage(pos, storage)?;
    emit_field_end_with_storage(&mut splitter.content, para, fr, storage)?;
    Ok(guide_units)
}

/// 고아(다단락) fieldEnd 를 `<hp:ctrl><hp:fieldEnd .../></hp:ctrl>` 로 방출 (Task #1556).
///
/// [#5252] **여는 짝을 찾지 못한 종료 마커는 내지 않는다.** `link_orphan_field_ends` 가
/// 섹션을 훑고도 `begin_id_ref` 를 채우지 못했다면 그 문서 어디에도 짝 `fieldBegin` 이
/// 없다는 뜻이다(원본 HWP5 자체가 그렇게 만들어진 문서가 있다). 한글은 **열려 있지 않은
/// 필드를 닫는 `fieldEnd` 를 참조 값과 무관하게 버리므로**, 그대로 내면 한글이 세는 문단
/// 축만 8유닛 짧아진다. 그런데 `linesegarray` 는 원본 축을 담고 있어 줄이 축을 넘고,
/// 한글이 **그 문단부터 본문을 통째로 폐기한다**.
///
/// 한글 2022 주입 검정(07276 h2x): 이 마커만 빼면 137쪽 → 224쪽, 본문 +100,393자.
/// `beginIDRef` 를 실제 id 로 바꾸는 것으로는 해결되지 않는다 — 그 필드는 이미 자기
/// 종료로 닫혀 있어 여전히 이중 닫기다(같은 검정에서 변화 0).
/// `02899` 는 이 마커 2개를 빼면 한글 추출 텍스트가 원본과 **해시까지 일치**한다.
///
/// 위치 부기(`expected_utf16_pos += 8`)는 호출부에서 그대로 둔다 — IR 축은 슬롯을 세고
/// 있고 `char_shapes`·`linesegarray` 도 그 축 위에 있으므로, 방출만 막는 것이 검정에서
/// 통과한 모양이다.
///
/// 앞 문단에 진짜 `fieldBegin` 이 있는 정상 다단락 고아는 종전대로 방출한다.
fn emit_orphan_field_end(out: &mut String, ofe: &OrphanFieldEnd) {
    emit_orphan_field_end_with_storage(out, ofe, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn emit_orphan_field_end_with_storage<S: crate::storage::Storage>(
    out: &mut String,
    ofe: &OrphanFieldEnd,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    if ofe.begin_id_ref == 0 {
        return Ok(());
    }
    if let Ok(xml) = checked_xml_result(
        writer_to_string_with_storage(
            |w| write_field_end_full(w, ofe.begin_id_ref, ofe.field_id),
            storage,
        ),
        storage,
    )? {
        storage.push_str(out, "<hp:ctrl>").map_err(xml_error)?;
        storage.push_str(out, &xml).map_err(xml_error)?;
        storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
    }

    Ok(())
}

/// 문단 텍스트 전체를 char_shapes 경계로 분할하며 `splitter` 에 누적한다.
///
/// `char_offsets` 로 문자 idx → UTF-16 위치를 매핑하므로 IR 내 컨트롤(8 유닛 갭)이
/// 있어도 경계 위치가 어긋나지 않는다.
fn split_text_into(splitter: &mut RunSplitter, para: &Paragraph, cursor: &mut InlineCursor<'_>) {
    split_text_into_with_storage(splitter, para, cursor, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn split_text_into_with_storage<S: crate::storage::Storage>(
    splitter: &mut RunSplitter,
    para: &Paragraph,
    cursor: &mut InlineCursor<'_>,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut text_buf = String::new();
    let mut running_pos = 0u32;
    for (idx, c) in para.text.chars().enumerate() {
        let char_pos = para.char_offsets.get(idx).copied().unwrap_or(running_pos);
        if splitter.needs_cut(char_pos) {
            flush_text_fragment_before_cut_with_storage(
                splitter,
                &mut text_buf,
                &para.tab_extended,
                cursor,
                char_pos,
                storage,
            )?;
            splitter.cut_before_with_storage(char_pos, storage)?;
        }
        storage.push_char(&mut text_buf, c).map_err(xml_error)?;
        running_pos = char_pos
            .max(running_pos)
            .saturating_add(char_utf16_width(c));
    }
    flush_text_fragment_with_storage(
        &mut splitter.content,
        &mut text_buf,
        &para.tab_extended,
        cursor,
        storage,
    )?;
    // 마지막 문자 뒤에 남은 제목 차례 표시 — 빈 조각으로 한 번 더 낸다.
    flush_trailing_title_marks_with_storage(splitter, cursor, running_pos, storage)?;

    Ok(())
}

/// [#5943] 슬롯을 방출하되 **XML 을 한 글자도 내지 않았으면** 그 위치를 기록한다.
///
/// HWP5 문단 축에서 확장 제어는 예외 없이 8유닛을 차지하지만, HWPX 에는 대응 요소가
/// 문단 안에 없는 컨트롤이 있다 — 구역 정의(`hp:secPr` 은 문단이 아니라 구역 머리 run 이
/// 싣는다)와 첫 문단이 템플릿에 흡수시킨 첫 단 정의가 그것이다. 이 슬롯들은 위치 계산을
/// 위해 축을 8씩 전진시키지만 방출 XML 은 비어 있으므로, **한글이 세는 HWPX 축은 그만큼
/// 짧다**. 어느 컨트롤이 비는지는 arm 유무와 consume-once 상태에 함께 걸려 있어 종류로
/// 판정하면 틀리므로, 실제 방출 길이 변화로 본다.
fn render_control_slot_tracked(
    out: &mut String,
    control: &Control,
    ctx: &mut SerializeContext,
    hwp5_pos: u32,
    hwp5_only_slot_positions: &mut Vec<u32>,
    collapsed_slot_positions: &mut Vec<u32>,
) {
    render_control_slot_tracked_with_storage(
        out,
        control,
        ctx,
        hwp5_pos,
        hwp5_only_slot_positions,
        collapsed_slot_positions,
        &crate::storage::Unbounded,
    )
    .expect("unbounded run XML")
}

fn render_control_slot_tracked_with_storage<S: crate::storage::Storage>(
    out: &mut String,
    control: &Control,
    ctx: &mut SerializeContext,
    hwp5_pos: u32,
    hwp5_only_slot_positions: &mut Vec<u32>,
    collapsed_slot_positions: &mut Vec<u32>,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let before = out.len();
    // XML이 인라인에서 비어도 구역 머리 run이나 별도 secPr run으로 옮겨진
    // 정의는 실제 출력에 남는다. 새 문단 축 계약에서 이를 삭제 슬롯으로 세지 않는다.
    let relocated_definition = ctx.line_segs_on_paragraph_axis
        && (matches!(control, Control::SectionDef(_))
            || (matches!(control, Control::ColumnDef(_))
                && ctx.sub_list_depth == 0
                && ctx.body_coldef_template_pending));
    // [#6871] 이 슬롯이 **우리가 접은 것**인지 미리 안다 — 두 번째 이후 쪽번호 위치.
    let collapses_here =
        matches!(control, Control::PageNumberPos(_)) && ctx.para_page_num_pos_emitted;
    render_control_slot_with_storage(out, control, ctx, storage)?;
    if out.len() == before && !relocated_definition {
        if collapses_here {
            // [#6871] **출처와 무관하게** 축에서 빼야 한다 — 아래 호출부 주석.
            storage
                .push(collapsed_slot_positions, hwp5_pos)
                .map_err(xml_error)?;
        } else {
            storage
                .push(hwp5_only_slot_positions, hwp5_pos)
                .map_err(xml_error)?;
        }
    }

    Ok(())
}

/// Paragraph 본문을 완전한 `<hp:run>` 시퀀스로 직렬화한다 (#1378 다중 run 분할).
///
/// 반환: (run 시퀀스 XML, **위치 축 보존 여부**, 실제 방출한 UTF-16 축 끝,
/// [#5943] HWP5 축에서만 자리를 차지한 슬롯들의 위치).
///
/// [#4778] 두 번째 값이 `false` 면 방출된 텍스트 스트림이 원본 8유닛 슬롯 축과
/// 어긋난 상태다(파서 미수용 슬롯 또는 mismatch 폴백). 호출부는 이때 저장
/// lineseg 방출을 억제해야 한다 — textpos 사다리와 어긋난 lineseg 는 한글이
/// 그 문단부터 본문을 통째 폐기하는 트리거다.
/// 문자와 개체 슬롯을 같은 UTF-16 축에서 보며, 형광펜 자체는 축을 소비하지 않는다.
struct PositionedMarkpens<'a> {
    marks: Vec<(u32, &'a crate::model::paragraph::MarkpenMark)>,
    next: usize,
}

impl PositionedMarkpens<'_> {
    fn flush(
        &mut self,
        position: u32,
        splitter: &mut RunSplitter,
        text: &mut String,
        para: &Paragraph,
        cursor: &mut InlineCursor<'_>,
    ) {
        self.flush_with_storage(
            position,
            splitter,
            text,
            para,
            cursor,
            &crate::storage::Unbounded,
        )
        .expect("unbounded run XML")
    }

    fn flush_with_storage<S: crate::storage::Storage>(
        &mut self,
        position: u32,
        splitter: &mut RunSplitter,
        text: &mut String,
        para: &Paragraph,
        cursor: &mut InlineCursor<'_>,
        storage: &S,
    ) -> Result<(), SerializeError>
    where
        S::Error: std::fmt::Display,
    {
        if !self
            .marks
            .get(self.next)
            .is_some_and(|(pos, _)| *pos <= position)
        {
            return Ok(());
        }
        flush_text_fragment_with_storage(
            &mut splitter.content,
            text,
            &para.tab_extended,
            cursor,
            storage,
        )?;
        while let Some(&(pos, mark)) = self.marks.get(self.next) {
            if pos > position {
                break;
            }
            splitter.cut_before_with_storage(pos, storage)?;
            storage
                .push_str(&mut splitter.content, "<hp:t>")
                .map_err(xml_error)?;
            match &mark.color {
                Some(color) => storage
                    .push_str(
                        &mut splitter.content,
                        &xml_value(
                            storage,
                            format_args!(
                                r#"<hp:markpenBegin color="{}"/>"#,
                                xml_escape_with_storage(color, storage)?
                            ),
                        )?,
                    )
                    .map_err(xml_error)?,
                None => storage
                    .push_str(&mut splitter.content, "<hp:markpenEnd/>")
                    .map_err(xml_error)?,
            }
            storage
                .push_str(&mut splitter.content, "</hp:t>")
                .map_err(xml_error)?;
            self.next += 1;
        }

        Ok(())
    }
}

fn render_runs(
    para: &Paragraph,
    ctx: &mut SerializeContext,
) -> (String, bool, u32, Vec<u32>, Vec<u32>) {
    render_runs_with_storage(para, ctx, &crate::storage::Unbounded).expect("unbounded run XML")
}

fn render_runs_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(String, bool, u32, Vec<u32>, Vec<u32>), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let parent = std::mem::replace(&mut ctx.para_page_num_pos_emitted, false);
    let result = render_runs_in_paragraph_scope_with_storage(para, ctx, storage);
    ctx.para_page_num_pos_emitted = parent;
    result.map_err(|error| SerializeError::XmlError(format!("HWPX run: {error}")))
}

fn render_runs_in_paragraph_scope(
    para: &Paragraph,
    ctx: &mut SerializeContext,
) -> (String, bool, u32, Vec<u32>, Vec<u32>) {
    render_runs_in_paragraph_scope_with_storage(para, ctx, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn render_runs_in_paragraph_scope_with_storage<S: crate::storage::Storage>(
    para: &Paragraph,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(String, bool, u32, Vec<u32>, Vec<u32>), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // ID 참조 무결성 (구현계획서 1.5): 실제 char_shapes entry 만 reference.
    // 빈 IR 의 fallback 0 은 제외 — char_shapes 미등록 문서(`Document::default()`)의
    // 직렬화를 깨지 않도록.
    for cs in &para.char_shapes {
        ctx.char_shape_ids.reference(cs.char_shape_id);
    }

    // [#1592] 완전 빈 문단(원본에 <hp:run> 없음)은 run 을 방출하지 않는다. char_shapes=[]
    // 인 문단에 RunSplitter 가 기본 (0,0) 세그먼트로 charPrIDRef="0" 빈 run 을 추가하면,
    // 재파싱 시 spurious (0,0) char_shape 가 생긴다(원본은 run 없어 char_shapes=[]).
    // char_shapes 가 있으면(예: [(0,0)] 명시) 종전대로 run 을 방출한다(linesegarray 는 별도).
    if para.text.is_empty()
        && para.char_shapes.is_empty()
        && para.controls.is_empty()
        && para.field_ranges.is_empty()
        && para.orphan_field_ends.is_empty()
        // 표시만 있고 텍스트가 없는 문단도 8유닛을 점유한다 — 여기서 빠지면 축이 밀린다.
        && para.title_marks.is_empty()
        && para.markpen_marks.is_empty()
    {
        // 방출할 것이 없는 문단 — 옮길 슬롯도 없으므로 위치 축은 그대로다.
        return Ok((String::new(), true, 0, Vec::new(), Vec::new()));
    }

    ctx.check_storage()?;
    let mut splitter = RunSplitter::new_with_storage(para, storage)?;

    let slot_count = inferred_control_slot_count(para);
    // [#4778] U+FFFC 마커는 컨트롤이 없어도 위치 축의 정규 시민이다(HWP3 암호 변환본:
    // 마커 리터럴이 그대로 방출돼 재파싱 고정점 유지 — #3739 --verify 계약). 억제는
    // **마커로 설명되지 않는 8유닛 구멍**(차례표지 0x0008 등 파서 미수용 슬롯)에만 건다.
    let marker_count = para.text.chars().filter(|c| *c == '\u{fffc}').count();
    // slots 와 각 slot 의 para.controls 인덱스(slot_ctrl_indices)를 병행 수집 —
    // [Task #1627] empty-text 문단의 bookmark in-order 방출에서 slot 사이 위치 계산에 사용.
    let (slots, slot_ctrl_indices): (Vec<&Control>, Vec<usize>) =
        if slot_count == para.controls.len() {
            // 전 컨트롤이 위치 슬롯인 경로. 본문 첫 문단의 첫 ColumnDef 도 슬롯으로 남겨
            // char-offset 정합을 보존하고, 그 XML 만 render_control_slot 의 consume-once
            // 플래그로 억제한다(템플릿이 이미 방출 — 중복 방지). 2번째+ 는 인라인 방출.
            (
                storage.collect(para.controls.iter()).map_err(xml_error)?,
                storage.collect(0..para.controls.len()).map_err(xml_error)?,
            )
        } else {
            // [Task #1379] 셀·글상자 subList(depth>0) 경로에서는 ColumnDef 도 인라인 슬롯으로
            // 취급한다 (원본 XML 에 <hp:ctrl><hp:colPr/></hp:ctrl> 인라인 존재).
            // [Task #1584] 본문(depth 0) 경로에서도 ColumnDef 를 인라인 슬롯에 포함하되,
            // 첫 문단의 첫 ColumnDef(섹션 템플릿 흡수분)는 슬롯에서 기본 제외한다.
            // 2번째+ 본문 ColumnDef 는 포함하여 드롭을 방지한다.
            let suppress_first_col = ctx.sub_list_depth == 0 && ctx.body_coldef_template_pending;
            let mut col_seen = 0u32;
            let mut s: Vec<&Control> = Vec::new();
            let mut si: Vec<usize> = Vec::new();
            // 제외된 hidden 슬롯 후보(SectionDef·템플릿 흡수 첫 ColumnDef)의 인덱스.
            let mut hidden: Vec<usize> = Vec::new();
            for (i, c) in para.controls.iter().enumerate() {
                let keep = if matches!(c, Control::ColumnDef(_)) {
                    col_seen += 1;
                    if suppress_first_col && col_seen == 1 {
                        storage.push(&mut hidden, i).map_err(xml_error)?;
                        false
                    } else {
                        true
                    }
                } else if matches!(c, Control::SectionDef(_)) {
                    storage.push(&mut hidden, i).map_err(xml_error)?;
                    false
                } else {
                    // [#4677] 위치 축은 책갈피까지 포함한다(`occupies_hwpx_slot_axis`).
                    let slot = occupies_hwpx_slot_axis(c);
                    // [#4388] Unknown 은 슬롯이 아니므로 이 실제 배제 지점에서 직접
                    // 경고한다. HWP3 Hyperlink은 occupies_hwpx_slot_axis가 HWPX field로
                    // 승격해 보존한다. HiddenComment 등 다른 non-slot 컨트롤은 이 헬퍼가
                    // 내부적으로 무시한다.
                    if !slot {
                        warn_if_unrepresentable_in_hwpx(c);
                    }
                    slot
                };
                if keep {
                    storage.push(&mut s, c).map_err(xml_error)?;
                    storage.push(&mut si, i).map_err(xml_error)?;
                }
            }
            // [Task #1591 v2] hidden 슬롯 정합: cc 증거(slot_count)가 hidden 후보
            // (secPr/템플릿 흡수 colPr — 원본 XML 에서 첫 run 이 점유하는 8유닛 슬롯)의
            // 점유를 보여주면 위치 슬롯으로 편입한다. XML 은 방출되지 않고
            // (SectionDef: 방출 arm 없음, 첫 ColumnDef: consume-once 억제) 위치 축만
            // 8유닛씩 전진 — 첫 문단이 mismatch 폴백 대신 메인 경로(위치 정확)로
            // 진입해 후위 슬롯(pageNum 등)·fieldEnd 가 char-offset 위치에 방출된다
            // (Class C1 +8 시프트·C2 fieldEnd 드롭의 근원 교정). 증거 불일치(합성 IR,
            // hidden 이 cc 를 점유하지 않는 문서)는 종전 동작 그대로.
            if !hidden.is_empty() && slot_count == s.len() + hidden.len() {
                let mut s2: Vec<&Control> = Vec::new();
                let mut si2: Vec<usize> = Vec::new();
                let mut keep_iter = si.iter().peekable();
                for (i, c) in para.controls.iter().enumerate() {
                    let kept = keep_iter.peek() == Some(&&i);
                    if kept {
                        keep_iter.next();
                    }
                    if kept || hidden.contains(&i) {
                        storage.push(&mut s2, c).map_err(xml_error)?;
                        storage.push(&mut si2, i).map_err(xml_error)?;
                    }
                }
                // 첫 ColumnDef 를 슬롯으로 되살렸으므로 consume-once 플래그를 유지해
                // render_control_slot 이 XML 방출만 1회 건너뛰게 한다(첫 분기와 동형).
                (s2, si2)
            } else {
                if suppress_first_col {
                    // 템플릿 흡수분을 슬롯에서 제외한 채 진행하므로, render_control_slot 의
                    // consume-once 억제가 2번째 ColumnDef 를 잘못 건너뛰지 않도록 플래그 해제.
                    ctx.body_coldef_template_pending = false;
                }
                (s, si)
            }
        };

    // [#4677] 책갈피는 이제 위치 슬롯이라(`occupies_hwpx_slot_axis`) 슬롯 루프가 제자리에
    // 방출한다. 종전의 별도 방출(문단 시작 hoist / slot 사이 in-order, Task #1591·#1627)은
    // 슬롯 축이 책갈피를 잡지 못하던 시절의 우회였고, 그대로 두면 이중 방출이 된다.
    // [#5537] 표시별 소유 run 판별 — 표시 끝 유닛(= 다음 문자의 char_offsets 값)에
    // char_shapes 경계가 정확히 걸리면, 원본은 표시까지를 **앞 run** 에 뒀다
    // (hwp3-sample10-hwp5 pi=14164: 유닛 7..15 표시 + 경계 15 = run(39) 소유.
    // 다음 run 머리로 넘기면 재파싱 경계가 15→7 로 무너진다). 표시가 문자 갭
    // 없이 놓인 합성 IR(char_offsets 에 8유닛 갭 없음)은 어느 경계에도 안 걸려
    // 종전 동작(다음 run 머리) 그대로다.
    let mark_owned_by_prev: Vec<bool> = storage
        .collect(para.title_marks.iter().map(|m| {
            para.char_offsets.get(m.char_idx).is_some_and(|&end_unit| {
                end_unit >= 8 && para.char_shapes.iter().any(|cs| cs.start_pos == end_unit)
            })
        }))
        .map_err(xml_error)?;
    let mut cursor = InlineCursor {
        title_marks: &para.title_marks,
        markpen_marks: &para.markpen_marks,
        markpen_idx: 0,
        mark_owned_by_prev: &mark_owned_by_prev,
        // [#4895] 출처가 제어 표기였던 문단만 `<hp:hypen/>` 로 되돌린다(#7993 철자).
        soft_hyphen_as_element: para.control_mask & (1u32 << 0x0018) != 0,
        // [#5174] 같은 계약 — 출처가 제어·요소 표기였던 문단만 `<hp:nbSpace/>` 로 되돌린다.
        nb_space_as_element: para.control_mask & (1u32 << 0x001E) != 0,
        literal_figure_spaces: &para.literal_figure_spaces,
        nb_space_control_indices: para.nb_space_control_indices.as_deref(),
        ..Default::default()
    };

    // fast path: 슬롯·필드·고아 fieldEnd·경계 없음 — 텍스트 전체를 단일 run 으로
    if slots.is_empty()
        && para.field_ranges.is_empty()
        && para.orphan_field_ends.is_empty()
        && splitter.single_run()
    {
        let t =
            render_hp_t_content_with_storage(&para.text, &para.tab_extended, &mut cursor, storage)?;
        storage
            .push_str(&mut splitter.content, &t)
            .map_err(xml_error)?;
        let text_units: u32 = para.text.chars().map(char_utf16_width).sum();
        flush_trailing_title_marks_with_storage(&mut splitter, &mut cursor, text_units, storage)?;
        // 슬롯이 하나도 없는데 char_count 는 슬롯을 주장하면(파서가 못 읽은 컨트롤 —
        // 예: 차례표지 0x0008) 방출 축이 원본보다 짧다 — 이때 lineseg 를 그대로 쓰면
        // 한글이 그 문단부터 본문을 폐기한다(#4778). 축 붕괴를 호출부에 알린다.
        // U+FFFC 마커가 슬롯 주장을 전부 설명하면 종전 계약 유지(#3739).
        return Ok((
            splitter.finish_with_storage(storage)?,
            slot_count == 0 || marker_count >= slot_count,
            0,
            Vec::new(),
            Vec::new(),
        ));
    }

    // mismatch 경로: 슬롯 위치 추정 불가 — 텍스트(경계 분할 포함) 후 슬롯 일괄 방출
    if slot_count != slots.len() {
        split_text_into_with_storage(&mut splitter, para, &mut cursor, storage)?;
        // [#3532] 본문 끝 zero-width 글자모양 경계(문단 마크 전용 모양)는 말미
        // 컨트롤보다 앞에 적용한다 — 종전에는 컨트롤을 먼저 몰아써서 재파싱
        // 경계가 컨트롤 슬롯 폭(8유닛×n)만큼 밀렸다(hwp3-sample10 실측:
        // (50,80)→(66,80)). 경계를 먼저 끊으면 컨트롤이 마지막 run 안쪽(경계
        // 뒤)에 실려 왕복이 고정점이 된다.
        let text_units: u32 = para.text.chars().map(char_utf16_width).sum();
        splitter.cut_before_with_storage(text_units, storage)?;
        for slot in slots.iter() {
            render_control_slot_with_storage(&mut splitter.content, slot, ctx, storage)?;
        }
        // [Task #1591 v2] 균형 field_ranges 의 닫는 fieldEnd 도 말미 복원 — 이 경로는
        // fieldBegin(슬롯)만 방출하고 fieldEnd 방출 코드가 없어 same-para 균형 필드가
        // 1/0 으로 깨지며 cc −8 (#1593). #1556 고아 복원과 동형(위치 대신 말미 일괄).
        for fr in &para.field_ranges {
            emit_field_end_with_storage(&mut splitter.content, para, fr, storage)?;
        }
        // [Task #1556] 위치 추정 불가 경로에서도 고아 fieldEnd 의 8유닛 슬롯은 복원한다
        // (정확한 위치 대신 말미 일괄 — 최소한 char_count 보존).
        for ofe in &para.orphan_field_ends {
            emit_orphan_field_end_with_storage(&mut splitter.content, ofe, storage)?;
        }
        // 컨트롤을 말미로 몰았으므로 원본 lineseg 좌표계는 더 이상 유효하지 않다 —
        // 호출부가 저장 lineseg 방출을 억제하게 한다(#4778). 단, 슬롯 부족분이
        // U+FFFC 마커로 전부 설명되면 종전 계약(방출 유지, #3739 고정점)을 지킨다.
        //
        // [#3518] HWP3 는 컨트롤 페이로드 hchar 를 char_count/char_offsets 에
        // 1유닛씩 쌓아 슬롯 추론이 부풀어 mismatch 로 떨어지지만, 본문 글자
        // 자체는 0부터 연속이다(hwp3-sample16 문단 70: "1.추진목적" offs=0..5,
        // cc=53). 그때는 말미 일괄 방출이 글자 좌표를 밀지 않으므로 저장
        // lineseg 를 버려 reflow 하면 쪽이 +1 된다. 글자가 연속이고 textpos 가
        // 본문 폭 안이면 축이 살아 있다.
        let shortfall = slot_count.saturating_sub(slots.len());
        let text_unshifted_and_in_range = text_positions_unshifted(para)
            && para.line_segs.iter().all(|ls| ls.text_start <= text_units);
        return Ok((
            splitter.finish_with_storage(storage)?,
            marker_count >= shortfall || text_unshifted_and_in_range,
            0,
            Vec::new(),
            Vec::new(),
        ));
    }

    // 슬롯으로 세어 놓고 XML 은 내지 않는 컨트롤이 섞여 있으면, 방출 축은 그만큼 짧다.
    // 위치는 여전히 최선을 다해 맞추되 **축 정합을 주장하지는 않는다** — lineseg 를 그대로
    // 쓰면 한글이 범위 밖 textpos 를 만나 파일을 아예 열지 못한다.
    let axis_faithful = slots.iter().all(|c| emits_hwpx_slot_xml(c));

    // 메인 경로 — UTF-16 위치 축 위에서 슬롯/필드/문자/경계를 함께 처리
    cursor.markpen_marks = &[];
    let mut markpens = PositionedMarkpens {
        marks: storage
            .collect(
                para.markpen_marks
                    .iter()
                    .map(|m| (m.stream_position(para), m)),
            )
            .map_err(xml_error)?,
        next: 0,
    };
    storage
        .bytes(std::mem::size_of_val(markpens.marks.as_slice()))
        .map_err(xml_error)?;
    markpens.marks.sort_by_key(|(pos, _)| *pos);
    let mut text_buf = String::new();
    let mut slot_idx = 0usize;
    let mut expected_utf16_pos = 0u32;
    // [#5943] XML 을 한 글자도 내지 않은 슬롯의 **HWP5 축** 위치. 저장 lineseg 의
    // `textpos` 를 HWPX 축으로 내릴 때 쓴다 — 아래 `render_control_slot_tracked` 주석.
    let mut hwp5_only_slot_positions: Vec<u32> = Vec::new();
    // [#6871] 우리가 접은 슬롯(중복 쪽번호)의 위치 — 출처와 무관하게 축에서 뺀다.
    let mut collapsed_slot_positions: Vec<u32> = Vec::new();
    let mut field_end_emitted = storage.vec(para.field_ranges.len()).map_err(xml_error)?;
    field_end_emitted.resize(para.field_ranges.len(), false);
    // [Task #1556] 고아 fieldEnd 방출 추적.
    let mut orphan_emitted = storage
        .vec(para.orphan_field_ends.len())
        .map_err(xml_error)?;
    orphan_emitted.resize(para.orphan_field_ends.len(), false);
    let text_char_count = para.text.chars().count();

    // 빈 문단(text == "")의 0-length 필드: 메인 루프가 실행되지 않아
    // pre-char 검사를 통과하지 못한다. 따라서 슬롯마다 `inner_slot_count`를
    // 확인해 fieldEnd를 제자리에 방출한다. 모든 슬롯 뒤에 fieldEnd를 몰면
    // 연속 또는 중첩 필드의 닫는 순서가 뒤바뀐다.
    if para.text.is_empty() {
        while slot_idx < slots.len() {
            splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
            markpens.flush_with_storage(
                expected_utf16_pos,
                &mut splitter,
                &mut text_buf,
                para,
                &mut cursor,
                storage,
            )?;
            render_control_slot_tracked_with_storage(
                &mut splitter.content,
                slots[slot_idx],
                ctx,
                expected_utf16_pos,
                &mut hwp5_only_slot_positions,
                &mut collapsed_slot_positions,
                storage,
            )?;
            let emitted_ctrl_idx = slot_ctrl_indices[slot_idx];
            slot_idx += 1;
            expected_utf16_pos = expected_utf16_pos.saturating_add(8);
            for (i, fr) in para.field_ranges.iter().enumerate() {
                if !field_end_emitted[i]
                    && fr.start_char_idx == fr.end_char_idx
                    && fr.control_idx + fr.inner_slot_count == emitted_ctrl_idx
                {
                    let guide_units = emit_field_end_at_with_storage(
                        &mut splitter,
                        para,
                        fr,
                        expected_utf16_pos,
                        storage,
                    )?;
                    expected_utf16_pos = expected_utf16_pos
                        .saturating_add(guide_units)
                        .saturating_add(8);
                    field_end_emitted[i] = true;
                }
            }
        }
        // [Task #1556] 빈 문단의 고아 fieldEnd (char_idx == 0).
        for (i, ofe) in para.orphan_field_ends.iter().enumerate() {
            if ofe.char_idx == 0 && !orphan_emitted[i] {
                splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
                emit_orphan_field_end_with_storage(&mut splitter.content, ofe, storage)?;
                expected_utf16_pos = expected_utf16_pos.saturating_add(8);
                orphan_emitted[i] = true;
            }
        }
    }

    for (idx, c) in para.text.chars().enumerate() {
        let char_pos = para
            .char_offsets
            .get(idx)
            .copied()
            .unwrap_or(expected_utf16_pos);
        // [#1407] 이 idx 위치에서 닫혀야 할(미방출) fieldEnd 가 있으면, 그 8유닛 갭은
        // 슬롯이 아니라 fieldEnd 소유다. 슬롯 방출을 양보해 텍스트-끝 슬롯(newNum 등)이
        // fieldEnd 자리를 가로채지 못하게 한다 (0-length 필드는 아래 pre-char 경로가 처리).
        // [#5173] 이 문자 앞 갭 중 제목 차례 표시(titleMark)가 차지하는 유닛은 슬롯 몫이
        // 아니다. titleMark 는 `render_hp_t_content` 안 char_idx 위치에 방출되는데(슬롯이
        // 아님), 슬롯 루프가 그 유닛까지 갭으로 보고 각주 등 슬롯을 먼저 가로채면 각주가
        // 제목보다 앞서 나간다(08435: 각주가 문단 맨 앞으로). titleMark 유닛(각 8)을 갭에서
        // 빼면 각주는 자기 실제 갭(제목·본문 뒤)으로 내려가 원본·h2h 순서(제목 → 본문 →
        // 각주)가 산다.
        let title_gap_units = cursor.title_marks[cursor.mark_idx..]
            .iter()
            .take_while(|m| m.char_idx == idx)
            .count() as u32
            * 8;
        while slot_idx < slots.len()
            && char_pos
                >= expected_utf16_pos
                    .saturating_add(title_gap_units)
                    .saturating_add(8)
        {
            // [Issue #1948] 이 갭(expected_utf16_pos)이 미방출 **고아(교차 문단)
            // fieldEnd** 소유면 슬롯 방출을 양보한다. 종전엔 field_ranges 의 fieldEnd
            // 만 갭을 지켰고(위 주석 #1407) 고아 fieldEnd 는 while 뒤(char_idx==idx)에서
            // 방출돼, 말미 슬롯(표 등)이 고아 fieldEnd 의 8유닛 갭을 먼저 가로채
            // char_offsets 가 +8 밀렸다(36380743 문단 0.10: 표가 fieldEnd 자리로 당겨짐).
            // 갭 소유자인 고아 fieldEnd 를 먼저 방출하고 while 을 재평가한다.
            //
            // [#4902] 단, 그 갭을 다투는 슬롯이 **이 문단의 fieldBegin** 이면 양보하지
            // 않는다. 한 자리에서 begin 과 (앞 문단 필드를 닫는) 고아 end 가 겹치면
            // 원본 순서는 언제나 `begin → end → end` 다 — HWP5 PARA_TEXT 실측
            // (08368 문단: `<0x0003 %clk><0x0004><0x0004>해 도 별 목 차`).
            // 고아를 앞세우면 `<hp:fieldEnd>` 가 짝 `<hp:fieldBegin>` 보다 먼저 나가고,
            // 한글은 그 지점에서 구역 파싱을 포기해 **이후 본문을 통째로 버린다**
            // (실측: 19쪽 35,205자 → 2쪽 7,838자, 개체 45→1. 고아를 짝 뒤로 옮기거나
            // 지우면 100% 복원되고, beginIDRef 값만 고치는 것으로는 복원되지 않는다).
            // #1948 이 막으려던 것은 **표 등 다른 슬롯**이 갭을 가로채는 경우다.
            let field_begin_owns_gap = matches!(slots[slot_idx], Control::Field(_));
            if let Some(oi) = para
                .orphan_field_ends
                .iter()
                .enumerate()
                .position(|(i, ofe)| ofe.char_idx == idx && !orphan_emitted[i])
                .filter(|_| !field_begin_owns_gap)
            {
                flush_text_fragment_with_storage(
                    &mut splitter.content,
                    &mut text_buf,
                    &para.tab_extended,
                    &mut cursor,
                    storage,
                )?;
                splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
                emit_orphan_field_end_with_storage(
                    &mut splitter.content,
                    &para.orphan_field_ends[oi],
                    storage,
                )?;
                expected_utf16_pos = expected_utf16_pos.saturating_add(8);
                orphan_emitted[oi] = true;
                continue;
            }
            flush_text_fragment_with_storage(
                &mut splitter.content,
                &mut text_buf,
                &para.tab_extended,
                &mut cursor,
                storage,
            )?;
            // 슬롯 시작 위치의 경계 — 슬롯은 새 run 소속 (규칙 1)
            splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
            markpens.flush_with_storage(
                expected_utf16_pos,
                &mut splitter,
                &mut text_buf,
                para,
                &mut cursor,
                storage,
            )?;
            render_control_slot_tracked_with_storage(
                &mut splitter.content,
                slots[slot_idx],
                ctx,
                expected_utf16_pos,
                &mut hwp5_only_slot_positions,
                &mut collapsed_slot_positions,
                storage,
            )?;
            let emitted_ctrl_idx = slot_ctrl_indices[slot_idx];
            slot_idx += 1;
            expected_utf16_pos = expected_utf16_pos.saturating_add(8);
            // [Task #1893] 이 슬롯이 0-length 필드(start==end==idx)의 fieldBegin 이면
            // 그 fieldEnd 를 즉시 이어서 방출 — 같은 갭의 end 몫 8유닛을 다음 슬롯이
            // 가로채 begin 들이 연속 배치되면 재파스 LIFO 페어링이 교차된다
            // (fr(0,0)+(50,50) → fr(0,50)+(0,0), 빈 누름틀 placeholder 소실/줄바꿈 분기).
            // 필드가 표·그림을 감쌌으면 안쪽 슬롯을 지나서 닫는다 — 자기 슬롯 직후에
            // 닫으면 개체가 필드 밖으로 밀려 빈 누름틀이 되고, 한글이 안내문을 본문에
            // 찍는다(G-순수증식). `inner_slot_count` 가 0 이면 종전과 동일하다.
            for (i, fr) in para.field_ranges.iter().enumerate() {
                if !field_end_emitted[i]
                    && fr.start_char_idx == fr.end_char_idx
                    && fr.end_char_idx == idx
                    && fr.control_idx + fr.inner_slot_count == emitted_ctrl_idx
                {
                    let guide_units = emit_field_end_at_with_storage(
                        &mut splitter,
                        para,
                        fr,
                        expected_utf16_pos,
                        storage,
                    )?;
                    expected_utf16_pos = expected_utf16_pos
                        .saturating_add(guide_units)
                        .saturating_add(8);
                    field_end_emitted[i] = true;
                }
            }
        }

        // [Task #1556] 고아 fieldEnd (char_idx == idx): 문자 push 전에 8유닛 슬롯 방출.
        for (i, ofe) in para.orphan_field_ends.iter().enumerate() {
            if ofe.char_idx == idx && !orphan_emitted[i] {
                flush_text_fragment_with_storage(
                    &mut splitter.content,
                    &mut text_buf,
                    &para.tab_extended,
                    &mut cursor,
                    storage,
                )?;
                splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
                emit_orphan_field_end_with_storage(&mut splitter.content, ofe, storage)?;
                expected_utf16_pos = expected_utf16_pos.saturating_add(8);
                orphan_emitted[i] = true;
            }
        }

        // HWP3 원본은 개체가 있는 위치를 U+FFFC 하나로 `text`에도 남기면서,
        // char_offsets에서는 그 한 글자를 HWP5와 같은 8 UTF-16 단위 슬롯으로 센다.
        // HWPX에서는 개체 태그 자체가 그 슬롯이므로 U+FFFC를 <hp:t>로 다시 쓰면
        // 문자 1단위가 중복되고, 다음 문자까지는 슬롯이 감지되지 않아 제어가 문단
        // 끝으로 밀린다. 현재 위치가 슬롯의 시작이고 소비할 control이 있을 때만
        // 표시 문자를 그 control의 HWPX 표현으로 직접 바꾼다. 실제 리터럴 U+FFFC나
        // 위치가 불명확한 합성 IR은 기존 텍스트 경로를 유지한다.
        if c == '\u{fffc}' && slot_idx < slots.len() && char_pos == expected_utf16_pos {
            flush_text_fragment_with_storage(
                &mut splitter.content,
                &mut text_buf,
                &para.tab_extended,
                &mut cursor,
                storage,
            )?;
            splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
            markpens.flush_with_storage(
                expected_utf16_pos,
                &mut splitter,
                &mut text_buf,
                para,
                &mut cursor,
                storage,
            )?;
            render_control_slot_tracked_with_storage(
                &mut splitter.content,
                slots[slot_idx],
                ctx,
                expected_utf16_pos,
                &mut hwp5_only_slot_positions,
                &mut collapsed_slot_positions,
                storage,
            )?;
            slot_idx += 1;
            expected_utf16_pos = expected_utf16_pos.saturating_add(8);
            cursor.nb_space_skipped_source_scalars += 1;
            continue;
        }

        // 0-length 필드(start == end == idx): fieldBegin 방출 직후, 문자 push 전에 fieldEnd 방출.
        // post-char 검사(next_idx 기준)는 end-1 번째 문자 처리 후 방출하므로 0-length 필드에서
        // fieldEnd가 fieldBegin 앞에 나오거나 텍스트 뒤로 밀리는 문제가 생긴다.
        for (i, fr) in para.field_ranges.iter().enumerate() {
            if fr.start_char_idx == fr.end_char_idx
                && fr.end_char_idx == idx
                && !field_end_emitted[i]
            {
                flush_text_fragment_with_storage(
                    &mut splitter.content,
                    &mut text_buf,
                    &para.tab_extended,
                    &mut cursor,
                    storage,
                )?;
                let guide_units = emit_field_end_at_with_storage(
                    &mut splitter,
                    para,
                    fr,
                    expected_utf16_pos,
                    storage,
                )?;
                expected_utf16_pos = expected_utf16_pos
                    .saturating_add(guide_units)
                    .saturating_add(8);
                field_end_emitted[i] = true;
            }
        }

        // AutoNumber 슬롯 (#1382): placeholder 공백이 슬롯 8유닛의 첫 유닛을 점유
        // (HWP5/HWPX 파서 공통 규약 — placeholder at P, 다음 문자 P+8). 슬롯 위치
        // (char_pos == expected)의 placeholder 에서 ctrl 을 방출하고, placeholder 는
        // 파서가 IR 에 합성한 문자이므로 텍스트로 내보내지 않는다 (한컴 원본 XML 동형:
        // `<hp:ctrl><hp:autoNum/></hp:ctrl>` 뒤에 실제 텍스트만 이어진다).
        // placeholder 판별: 일반 공백과 구분하기 위해 직후 offset 의 +8 jump 를 본다
        // (마지막 문자면 jump 가 char_offsets 에 없으므로 placeholder 로 간주).
        let is_autonum_placeholder = c == ' '
            && char_pos == expected_utf16_pos
            && para
                .char_offsets
                .get(idx + 1)
                .copied()
                .unwrap_or_else(|| char_pos.saturating_add(8))
                >= char_pos.saturating_add(8);
        if slot_idx < slots.len()
            && matches!(slots[slot_idx], Control::AutoNumber(_))
            && is_autonum_placeholder
        {
            flush_text_fragment_with_storage(
                &mut splitter.content,
                &mut text_buf,
                &para.tab_extended,
                &mut cursor,
                storage,
            )?;
            splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
            markpens.flush_with_storage(
                expected_utf16_pos,
                &mut splitter,
                &mut text_buf,
                para,
                &mut cursor,
                storage,
            )?;
            render_control_slot_tracked_with_storage(
                &mut splitter.content,
                slots[slot_idx],
                ctx,
                expected_utf16_pos,
                &mut hwp5_only_slot_positions,
                &mut collapsed_slot_positions,
                storage,
            )?;
            slot_idx += 1;
            expected_utf16_pos = expected_utf16_pos.saturating_add(8);
            cursor.nb_space_skipped_source_scalars += 1;
            continue;
        }

        // 문자 위치의 경계 — 문자는 새 run 소속 (규칙 1)
        if splitter.needs_cut(char_pos) {
            flush_text_fragment_before_cut_with_storage(
                &mut splitter,
                &mut text_buf,
                &para.tab_extended,
                &mut cursor,
                char_pos,
                storage,
            )?;
            splitter.cut_before_with_storage(char_pos, storage)?;
        }

        markpens.flush_with_storage(
            char_pos,
            &mut splitter,
            &mut text_buf,
            para,
            &mut cursor,
            storage,
        )?;
        storage.push_char(&mut text_buf, c).map_err(xml_error)?;
        let width = char_utf16_width(c);
        if char_pos >= expected_utf16_pos {
            expected_utf16_pos = char_pos.saturating_add(width);
        } else {
            expected_utf16_pos = expected_utf16_pos.saturating_add(width);
        }

        // end_char_idx는 미포함(exclusive): 현재 문자가 필드 범위의 마지막이면 fieldEnd 삽입.
        // 0-length 필드(start == end)는 위의 pre-char 검사에서 처리하므로 제외한다.
        let next_idx = idx + 1;
        for (i, fr) in para.field_ranges.iter().enumerate() {
            if fr.end_char_idx == next_idx
                && !field_end_emitted[i]
                && fr.start_char_idx < fr.end_char_idx
            {
                flush_text_fragment_with_storage(
                    &mut splitter.content,
                    &mut text_buf,
                    &para.tab_extended,
                    &mut cursor,
                    storage,
                )?;
                let guide_units = emit_field_end_at_with_storage(
                    &mut splitter,
                    para,
                    fr,
                    expected_utf16_pos,
                    storage,
                )?;
                // [#1407] fieldEnd 는 8유닛 슬롯을 소비한다. expected 를 +8 진행하지
                // 않으면 다음 idx 에서 텍스트-끝 슬롯(newNum 등)이 이 8유닛 갭을
                // 가로채 텍스트가 +8 밀린다 (143E 문단 0.14: char_offsets[3] 27→35).
                expected_utf16_pos = expected_utf16_pos
                    .saturating_add(guide_units)
                    .saturating_add(8);
                field_end_emitted[i] = true;
            }
        }
    }

    flush_text_fragment_with_storage(
        &mut splitter.content,
        &mut text_buf,
        &para.tab_extended,
        &mut cursor,
        storage,
    )?;
    expected_utf16_pos = flush_trailing_title_marks_with_storage(
        &mut splitter,
        &mut cursor,
        expected_utf16_pos,
        storage,
    )?;

    // end_char_idx >= text.len() 인 경우 루프에서 감지되지 않으므로 루프 후에 처리.
    // [Task #1893] 단, 문단 끝의 0-length 필드(start == end == text.len())는 자기
    // fieldBegin 슬롯이 아직 아래 잔여 슬롯 루프에 남아 있다 — 여기서 먼저 방출하면
    // fieldEnd 가 fieldBegin 앞에 놓여 재파스가 고아 end + 미닫힘 begin 으로 해석,
    // field_range 가 소실된다(빈 누름틀 안내문 placeholder 미렌더 → 라운드트립 렌더
    // 분기). begin 슬롯 방출 직후로 지연한다(중간 위치 0-length 는 pre-char 경로가
    // 동일 규칙으로 처리 — #1407).
    for (i, fr) in para.field_ranges.iter().enumerate() {
        if !field_end_emitted[i] {
            let begin_slot_pending = fr.start_char_idx == fr.end_char_idx
                && slot_ctrl_indices[slot_idx..].contains(&fr.control_idx);
            if begin_slot_pending {
                continue;
            }
            let guide_units = emit_field_end_at_with_storage(
                &mut splitter,
                para,
                fr,
                expected_utf16_pos,
                storage,
            )?;
            expected_utf16_pos = expected_utf16_pos
                .saturating_add(guide_units)
                .saturating_add(8);
            field_end_emitted[i] = true;
        }
    }

    // [Task #1556] 텍스트 끝(char_idx == text_char_count) 의 고아 fieldEnd — para 0.16 케이스.
    for (i, ofe) in para.orphan_field_ends.iter().enumerate() {
        if !orphan_emitted[i] {
            debug_assert!(
                ofe.char_idx >= text_char_count,
                "미방출 고아 fieldEnd 는 텍스트 끝이어야 함"
            );
            splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
            emit_orphan_field_end_with_storage(&mut splitter.content, ofe, storage)?;
            expected_utf16_pos = expected_utf16_pos.saturating_add(8);
            orphan_emitted[i] = true;
        }
    }

    while slot_idx < slots.len() {
        splitter.cut_before_with_storage(expected_utf16_pos, storage)?;
        markpens.flush_with_storage(
            expected_utf16_pos,
            &mut splitter,
            &mut text_buf,
            para,
            &mut cursor,
            storage,
        )?;
        render_control_slot_tracked_with_storage(
            &mut splitter.content,
            slots[slot_idx],
            ctx,
            expected_utf16_pos,
            &mut hwp5_only_slot_positions,
            &mut collapsed_slot_positions,
            storage,
        )?;
        let emitted_ctrl_idx = slot_ctrl_indices[slot_idx];
        slot_idx += 1;
        expected_utf16_pos = expected_utf16_pos.saturating_add(8);
        // [Task #1893] 위에서 지연한 문단 끝 0-length 필드의 fieldEnd 를 자기
        // fieldBegin 슬롯 **뒤**에 방출 — begin→end 순서 보존.
        //
        // 필드가 표·그림을 감싸면 텍스트 축은 0길이지만 안쪽에 컨트롤 슬롯이 있다.
        // `inner_slot_count` 만큼 지나서 닫아야 개체가 필드 안에 남는다. 자기 슬롯
        // 직후에 닫으면 개체가 밖으로 밀려 빈 누름틀이 되고, 한글이 안내문을 본문에
        // 찍는다(G-순수증식 16경로).
        for (i, fr) in para.field_ranges.iter().enumerate() {
            if !field_end_emitted[i]
                && fr.start_char_idx == fr.end_char_idx
                && fr.control_idx + fr.inner_slot_count == emitted_ctrl_idx
            {
                let guide_units = emit_field_end_at_with_storage(
                    &mut splitter,
                    para,
                    fr,
                    expected_utf16_pos,
                    storage,
                )?;
                expected_utf16_pos = expected_utf16_pos
                    .saturating_add(guide_units)
                    .saturating_add(8);
                field_end_emitted[i] = true;
            }
        }
    }
    // [Task #1893] 방어: 지연분이 슬롯 루프에서 매칭되지 못했으면 말미에 방출(종전 동작).
    for (i, fr) in para.field_ranges.iter().enumerate() {
        if !field_end_emitted[i] {
            let guide_units = emit_field_end_at_with_storage(
                &mut splitter,
                para,
                fr,
                expected_utf16_pos,
                storage,
            )?;
            expected_utf16_pos = expected_utf16_pos
                .saturating_add(guide_units)
                .saturating_add(8);
            field_end_emitted[i] = true;
        }
    }
    markpens.flush_with_storage(
        u32::MAX,
        &mut splitter,
        &mut text_buf,
        para,
        &mut cursor,
        storage,
    )?;
    Ok((
        splitter.finish_with_storage(storage)?,
        axis_faithful,
        expected_utf16_pos,
        hwp5_only_slot_positions,
        collapsed_slot_positions,
    ))
}

fn inferred_control_slot_count(para: &Paragraph) -> usize {
    // [#1382] AutoNumber 는 placeholder 공백이 슬롯 8유닛의 첫 유닛을 점유한다
    // (HWP5 body_text / HWPX offsets 조립 공통 규약). placeholder 가 텍스트 폭에
    // 이미 1유닛으로 집계되므로 두 축 모두에서 autoNum 1개당 잉여가 8이 아닌 7로
    // 측정된다 → autoNum 수만큼 더해 보정한 뒤 8로 나눈다. placeholder 없는
    // 합성 IR(편집기 생성)은 잉여 0이라 보정해도 0 — 기존 mismatch 경로 유지.
    let autonum_count = para
        .controls
        .iter()
        .filter(|c| matches!(c, Control::AutoNumber(_)))
        .count() as u32;

    let text_units: u32 = para.text.chars().map(char_utf16_width).sum();
    // 암호 HWP3 parser는 개체 자리에 U+FFFC 하나를 남기되, 실제 offset은 HWP5와
    // 같은 8단위로 전진시킨다. 이 표식은 HWPX에서 개체 슬롯으로 치환되므로, 1단위
    // 텍스트로만 세면 `(char_count - text_units) / 8`가 0으로 내림되어 mismatch
    // fallback(텍스트 뒤에 control 몰아쓰기)으로 빠진다. control이 없는 리터럴 U+FFFC는
    // 제외하기 위해 가능한 control 수까지만 슬롯 증거로 반영한다.
    let hwp3_object_marker_slots = para
        .text
        .chars()
        .filter(|c| *c == '\u{fffc}')
        .count()
        .min(para.controls.len()) as u32;
    let from_char_count = para
        .char_count
        .saturating_sub(1)
        // U+FFFC 자체 1단위를 빼면 실제 8단위 control 슬롯만 남는다.
        .saturating_sub(text_units.saturating_sub(hwp3_object_marker_slots))
        .saturating_add(autonum_count)
        / 8;

    let mut offsets_gap = 0u32;
    let mut expected = 0u32;
    for (idx, c) in para.text.chars().enumerate() {
        let pos = para.char_offsets.get(idx).copied().unwrap_or(expected);
        if pos > expected {
            offsets_gap += pos - expected;
        }
        expected = pos.max(expected).saturating_add(char_utf16_width(c));
    }
    // marker 다음 offset gap은 8이 아니라 7(표식 텍스트 1단위를 이미 센 뒤)이므로,
    // 나누기 전에 marker 수를 더해 실제 8단위 슬롯 수로 복원한다.
    let from_offsets = offsets_gap
        .saturating_add(autonum_count)
        .saturating_add(hwp3_object_marker_slots)
        / 8;

    // fieldEnd는 8 code unit 슬롯이지만 para.controls[]에 대응 컨트롤이 없다.
    // field_ranges.len()이 fieldEnd 수와 정확히 일치하므로 빼서 보정한다.
    // [Task #1556] 고아(다단락) fieldEnd 도 컨트롤 없는 8유닛 슬롯이므로 동일하게 차감.
    // 제목 차례 표시(`Mtit`/`Mign`)도 CTRL_HEADER 가 없는 8유닛 슬롯이라 같은 계열이다 —
    // 차감하지 않으면 슬롯 수가 `controls.len()` 보다 커져 문단이 mismatch 경로로 떨어지고,
    // 그 문단의 linesegarray 가 통째로 빠진다.
    from_char_count
        .max(from_offsets)
        .saturating_sub(para.field_ranges.len() as u32)
        .saturating_sub(para.orphan_field_ends.len() as u32)
        .saturating_sub(para.title_marks.len() as u32) as usize
}

/// HWPX 인라인 슬롯(U+FFFC 오브젝트 위치)을 점유하는 컨트롤인지 판정한다.
///
/// 이 목록은 두 곳에서 쓰인다: `render_runs`(이 파일, mismatch-분기 위치 축)와
/// `roundtrip::diff_documents`(포맷 비종속 IR 비교 — `export-hwpx` **뿐 아니라**
/// `convert`(HWP5 대상) `--verify` 도 재사용한다).
///
/// **[#4388] `Control::Hyperlink`/`Control::Unknown` 은 의도적으로 여기 등록하지
/// 않는다.** 둘 다 HWP3/HWP5 PARA_TEXT 상에서는 Picture/Table 과 동형인 U+FFFC
/// 오브젝트 슬롯(위치 점유)이라 처음엔 등록했으나, 등록하면 HWP5 직렬화기가 이미
/// (이슈 범위 밖으로) Hyperlink 의 ctrl_id 를 0 으로 고정해 버려 CTRL_HEADER 자체를
/// 안 쓰는 기존 HWP5 경로 손실까지 `diff_documents` 가 새로 "검출"해,
/// `bookmarks_survive_saving_to_hwp5`(tests/issue_hwp3_bookmark_native.rs) 같이
/// 하이퍼링크와 무관한 기존 회귀 테스트가 hwp3-sample16.hwp 에서 깨졌다(#4388 후속
/// 보고, 실측 재현: s0 문단 27/32/196/657 이 전부 Hyperlink). "조용히 버리지
/// 말라"는 경고 축이지 비교 축이 아니다 — 경고는 `render_control_slot` catch-all과
/// `render_runs` 의 mismatch-분기 제외 지점(`warn_if_unrepresentable_in_hwpx` 호출)
/// 두 곳에서 낸다. 회귀 가드: `roundtrip.rs` 의
/// `issue4388_diff_documents_hyperlink_not_compared_as_control`/
/// `issue4388_diff_documents_unknown_not_compared_as_control`.
/// [#4677] `render_runs` 의 **위치 축** 전용 슬롯 판정 — 책갈피를 포함한다.
///
/// 책갈피는 HWP5 PARA_TEXT 에서 8 유닛 확장 제어문자 자리를 차지한다(한컴 원본 바이트
/// `16 00 6d 6b 6f 62 … 16 00`). 종전엔 zero-width 로 보고 슬롯 축에서 빼는 대신
/// `emit_inorder_bookmarks` 로 따로 끼워 넣었는데, 그러면 HWPX 파서가 자리를 잡는 순간
/// 슬롯 수가 어긋나 위치 추정이 통째로 무너진다(x2x 산출물 6,995자 → 416자).
///
/// [`is_hwpx_inline_slot`] 자체를 넓히지 않는 이유는 그 헬퍼가 `roundtrip::diff_documents`
/// 의 **비교 축**과 공유되기 때문이다 — 비교 축 변경은 #4388 처럼 무관한 회귀를 만든다.
/// 여기서 필요한 것은 위치 축 하나뿐이다.
fn occupies_hwpx_slot_axis(control: &Control) -> bool {
    is_hwpx_inline_slot(control)
        || matches!(
            control,
            // Hyperlink은 HWP3의 8-unit object slot이고 HWPX에서는 fieldBegin으로 승격한다.
            // `is_hwpx_inline_slot`에는 넣지 않는다. 해당 헬퍼는 포맷 비종속 diff에도 공유되어
            // HWP5의 기존 Hyperlink 표현 범위까지 바꾸기 때문이다.
            // 숨은 설명은 HWPX 네이티브 표현(`<hp:hiddenComment>`)이 있고 방출 arm 도
            // 있으나, 이 필터에서 빠지면 mismatch 경로에서 **조용히 버려진다**.
            // HWP3 는 char_count 에 8유닛 슬롯을 배정하지 않아(06397 문단 0.0:
            // `cc=2, text_len=1, controls=3`) 늘 mismatch 경로로 오므로, 여기 없으면
            // HWP3 문서의 숨은 설명이 통째로 사라진다(06397 유지율 2.2%).
            Control::Bookmark(_)
                | Control::Hyperlink(_)
                | Control::HiddenComment(_)
                | Control::IndexMark(_)
        )
}

/// 이 컨트롤이 슬롯 자리에 **실제 XML 을 남기는가**.
///
/// `render_control_slot` 은 표현할 방법이 없는 컨트롤(`Unknown`)을 경고만
/// 내고 버린다. 그런데 위치 슬롯 수가 `controls.len()` 과 같으면 축 정합 경로로 들어가
/// **버려진 컨트롤도 슬롯으로 세어 놓고** `axis_faithful=true` 를 주장한다. 그러면 방출본은
/// 컨트롤 하나당 8유닛씩 짧은데 lineseg 는 원본 좌표 그대로 나가고, 한글 2022 는 범위를
/// 넘는 `textpos` 를 만나면 **파일 자체를 열지 못한다**(본문 폐기보다 강한 실패).
///
/// 실측(06926 section3 문단 347): 찾아보기 표식(`idxm`) 3개가 여기서 사라져 축이 366→342 로
/// 줄었고, 원본에서 유효하던 `textpos=348` 이 범위 밖이 되어 산출물이 열리지 않았다.
fn emits_hwpx_slot_xml(control: &Control) -> bool {
    // `Hyperlink` 는 devel 이 방출 arm 을 갖췄으므로(`render_control_slot`) 여기서
    // 빼면 안 된다 — 빼면 HWP3 변환본의 축이 근거 없이 무너진 것으로 판정돼
    // 저장 lineseg 가 통째로 억제된다(#3739 암호 변환본 계약 파손).
    !matches!(control, Control::Unknown(_))
}

pub(crate) fn is_hwpx_inline_slot(control: &Control) -> bool {
    matches!(
        control,
        Control::Table(_)
            | Control::Shape(_)
            | Control::Picture(_)
            | Control::CharOverlap(_)
            | Control::Ruby(_)
            | Control::Equation(_)
            | Control::Field(_)
            | Control::Form(_)
            | Control::Footnote(_)
            | Control::Endnote(_)
            | Control::PageHide(_)
            | Control::PageNumberPos(_)
            | Control::NewNumber(_)
            | Control::Header(_)
            | Control::Footer(_)
            | Control::AutoNumber(_)
            | Control::PageNumCtrl(_)
    )
}

fn flush_text_fragment(
    out: &mut String,
    text_buf: &mut String,
    tab_extended: &[[u16; 7]],
    cursor: &mut InlineCursor<'_>,
) {
    flush_text_fragment_with_storage(
        out,
        text_buf,
        tab_extended,
        cursor,
        &crate::storage::Unbounded,
    )
    .expect("unbounded run XML")
}

fn flush_text_fragment_with_storage<S: crate::storage::Storage>(
    out: &mut String,
    text_buf: &mut String,
    tab_extended: &[[u16; 7]],
    cursor: &mut InlineCursor<'_>,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#5537] 닫히는 run 소유의 제목 차례 표시(경계 유닛 = 표시 끝 유닛)가 걸려
    // 있으면 버퍼가 비어도 조각을 방출한다 — 건너뛰면 표시가 다음 run 머리로
    // 넘어가 재파싱 char_shapes 경계가 표시 폭(8유닛)만큼 무너진다.
    if !text_buf.is_empty() || cursor.has_pending_prev_owned_mark() {
        storage
            .push_str(
                out,
                &render_hp_t_content_with_storage(text_buf, tab_extended, cursor, storage)?,
            )
            .map_err(xml_error)?;
        text_buf.clear();
    }

    Ok(())
}

/// 문자 위치 `char_pos` 의 글자 모양 경계를 적용하기 전에 쌓인 글을 방출한다.
///
/// [#8305] 이 문자 앞 갭에 **앞 run 소유** 제목 차례 표시가 있고(#5537) 그 표시의
/// 시작 유닛에도 경계가 있으면(한컴 실측: `글 run | 표시만 담은 run | 다음 글 run`),
/// 글 → 표시 시작 경계 → 표시 순으로 낸다. 함께 내면 두 경계가 `char_pos` 에서 한꺼번에
/// 끊겨 표시 run 이 비고 재파싱 경계가 표시 폭(8유닛)만큼 밀린다.
fn flush_text_fragment_before_cut_with_storage<S: crate::storage::Storage>(
    splitter: &mut RunSplitter,
    text_buf: &mut String,
    tab_extended: &[[u16; 7]],
    cursor: &mut InlineCursor<'_>,
    char_pos: u32,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let idx = cursor.char_idx + text_buf.chars().count();
    let pending = cursor.title_marks[cursor.mark_idx..]
        .iter()
        .take_while(|m| m.char_idx == idx)
        .count() as u32;
    let owned_by_prev = cursor
        .mark_owned_by_prev
        .get(cursor.mark_idx)
        .copied()
        .unwrap_or(false);
    let mark_start = char_pos.saturating_sub(pending * 8);
    if pending > 0 && owned_by_prev && mark_start < char_pos && splitter.needs_cut(mark_start) {
        if !text_buf.is_empty() {
            cursor.hold_prev_owned_marks = true;
            let t = render_hp_t_content_with_storage(text_buf, tab_extended, cursor, storage);
            cursor.hold_prev_owned_marks = false;
            storage
                .push_str(&mut splitter.content, &t?)
                .map_err(xml_error)?;
            text_buf.clear();
        }
        splitter.cut_before_with_storage(mark_start, storage)?;
    }
    flush_text_fragment_with_storage(
        &mut splitter.content,
        text_buf,
        tab_extended,
        cursor,
        storage,
    )
}

/// 문단 끝에 남은 제목 차례 표시를 빈 `<hp:t>` 조각으로 방출한다.
///
/// 조각 경계에서 flush 를 건너뛰는 이유는 표시가 **다음** run 소속이기 때문인데,
/// 다음 run 이 없는 문단 말미에서는 그 규칙이 그대로 유실이 된다.
///
/// [#8305] 표시는 UTF-16 축에서 8유닛을 차지한다. `pos` 는 첫 남은 표시의 시작
/// 유닛이다. 표시마다 그 시작 유닛의 글자 모양 경계를 먼저 적용하고(규칙 1 — 경계와
/// 같은 위치의 콘텐츠는 새 run 소속) 방출 뒤 8 을 진행한 위치를 돌려준다. 경계를 나중에
/// 끊으면 표시가 앞 run 에 실려 재파싱 경계가 8 밀리고, 위치를 진행하지 않으면 표시
/// 뒤 말미 슬롯(`newNum` 등)이 표시 끝 경계 앞 run 에 실린다(한컴 9.x HWPX 실측).
fn flush_trailing_title_marks(
    splitter: &mut RunSplitter,
    cursor: &mut InlineCursor<'_>,
    pos: u32,
) -> u32 {
    flush_trailing_title_marks_with_storage(splitter, cursor, pos, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn flush_trailing_title_marks_with_storage<S: crate::storage::Storage>(
    splitter: &mut RunSplitter,
    cursor: &mut InlineCursor<'_>,
    mut pos: u32,
    storage: &S,
) -> Result<u32, SerializeError>
where
    S::Error: std::fmt::Display,
{
    while cursor.mark_idx < cursor.title_marks.len() {
        splitter.cut_before_with_storage(pos, storage)?;
        let mut t_xml = storage.string("<hp:t>").map_err(xml_error)?;
        let mut buf = String::new();
        cursor.flush_markpen_at_fragment_end_with_storage(&mut t_xml, &mut buf, storage)?;
        while let Some(m) = cursor.title_marks.get(cursor.mark_idx) {
            if splitter.needs_cut(pos) {
                break;
            }
            storage
                .push_str(
                    &mut t_xml,
                    &xml_value(
                        storage,
                        format_args!(
                            r#"<hp:titleMark ignore="{}"/>"#,
                            if m.ignore { 1 } else { 0 }
                        ),
                    )?,
                )
                .map_err(xml_error)?;
            cursor.mark_idx += 1;
            pos = pos.saturating_add(8);
        }
        storage.push_str(&mut t_xml, "</hp:t>").map_err(xml_error)?;
        storage
            .push_str(&mut splitter.content, &t_xml)
            .map_err(xml_error)?;
    }
    Ok(pos)
}

fn render_control_slot(out: &mut String, control: &Control, ctx: &mut SerializeContext) {
    render_control_slot_with_storage(out, control, ctx, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn render_control_slot_with_storage<S: crate::storage::Storage>(
    out: &mut String,
    control: &Control,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    match control {
        // [#4677] 책갈피는 위치 슬롯이다 — 슬롯 축에 들어온 이상 여기서 제자리에 방출한다
        // (종전 `emit_inorder_bookmarks` 의 역할을 대체).
        Control::Bookmark(bm) => match checked_xml_result(
            writer_to_string_with_storage(|w| write_bookmark(w, bm), storage),
            storage,
        )? {
            Ok(xml) => {
                storage.push_str(out, "<hp:ctrl>").map_err(xml_error)?;
                storage.push_str(out, &xml).map_err(xml_error)?;
                storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
            }
            Err(e) => eprintln!("[hwpx] Bookmark 직렬화 실패: {e}"),
        },
        Control::Hyperlink(link) => {
            let field_id = ctx.next_generated_hyperlink_id();
            match checked_xml_result(
                writer_to_string_with_storage(
                    |w| write_hyperlink_begin(w, link, field_id),
                    storage,
                ),
                storage,
            )? {
                Ok(xml) => {
                    storage.push_str(out, "<hp:ctrl>").map_err(xml_error)?;
                    storage.push_str(out, &xml).map_err(xml_error)?;
                    storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
                }
                Err(e) => eprintln!("[hwpx] Hyperlink 직렬화 실패: {e}"),
            }
        }
        // 찾아보기 표식 — 한컴 실측(06926, 23건)은 `secondKey` 가 비면 아예 쓰지 않는다.
        Control::IndexMark(im) => {
            storage
                .push_str(out, "<hp:ctrl><hp:indexmark><hp:firstKey>")
                .map_err(xml_error)?;
            storage
                .push_str(out, &xml_escape_with_storage(&im.first_key, storage)?)
                .map_err(xml_error)?;
            storage.push_str(out, "</hp:firstKey>").map_err(xml_error)?;
            if !im.second_key.is_empty() {
                storage.push_str(out, "<hp:secondKey>").map_err(xml_error)?;
                storage
                    .push_str(out, &xml_escape_with_storage(&im.second_key, storage)?)
                    .map_err(xml_error)?;
                storage
                    .push_str(out, "</hp:secondKey>")
                    .map_err(xml_error)?;
            }
            storage
                .push_str(out, "</hp:indexmark></hp:ctrl>")
                .map_err(xml_error)?;
        }
        Control::Equation(eq) => {
            storage
                .push_str(out, &render_equation_with_storage(eq, storage)?)
                .map_err(xml_error)?;
        }
        Control::Table(tbl) => match checked_xml_result(
            writer_to_string_with_storage(
                |w| table::write_table_with_storage(w, tbl, ctx, storage),
                storage,
            ),
            storage,
        )? {
            Ok(xml) => storage.push_str(out, &xml).map_err(xml_error)?,
            Err(e) => eprintln!("[hwpx] Table 직렬화 실패: {e}"),
        },
        Control::Picture(pic) => match checked_xml_result(
            writer_to_string_with_storage(
                |w| picture::write_picture_with_storage(w, pic, ctx, storage),
                storage,
            ),
            storage,
        )? {
            Ok(xml) => storage.push_str(out, &xml).map_err(xml_error)?,
            Err(e) => eprintln!("[hwpx] Picture 직렬화 실패: {e}"),
        },
        Control::Shape(shape) => {
            storage
                .push_str(out, &render_shape_with_storage(shape, ctx, storage)?)
                .map_err(xml_error)?;
        }
        Control::Footnote(note) => {
            storage
                .push_str(out, &render_footnote_with_storage(note, ctx, storage)?)
                .map_err(xml_error)?;
        }
        Control::Endnote(note) => {
            storage
                .push_str(out, &render_endnote_with_storage(note, ctx, storage)?)
                .map_err(xml_error)?;
        }
        Control::Field(f) => {
            // fieldBegin은 <hp:ctrl>...</hp:ctrl>로 감싸야 함 (Table/Picture와 달리)
            storage.push_str(out, "<hp:ctrl>").map_err(xml_error)?;
            // [#5866] HWP5 출처 메모(command `MEMO/…`)는 한글 실측 형상(파라미터
            // 6종 + 빈 subList)으로 방출한다 — CROSSREF 로 굳히면 필드 범위
            // 숨김이 풀려 메모 대상 텍스트가 본문에 붙는다.
            if let Some(memo_children) = super::field::memo_field_children_xml(f) {
                storage
                    .push_str(out, &super::field::field_begin_open_tag(f))
                    .map_err(xml_error)?;
                storage.push_char(out, '>').map_err(xml_error)?;
                storage.push_str(out, &memo_children).map_err(xml_error)?;
                storage
                    .push_str(out, "</hp:fieldBegin>")
                    .map_err(xml_error)?;
                storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
                return Ok(());
            }
            let generated_params = generated_field_parameters(f);
            let has_params = f.raw_parameters_xml.is_some() || generated_params.is_some();
            let has_memo = f.field_type == crate::model::control::FieldType::Memo
                && !f.memo_paragraphs.is_empty();
            if has_params || has_memo {
                // [#1391] 자식(parameters / memo subList)이 있으면 start/end 태그.
                storage
                    .push_str(out, &super::field::field_begin_open_tag(f))
                    .map_err(xml_error)?;
                storage.push_char(out, '>').map_err(xml_error)?;
                if let Some(params) = f
                    .raw_parameters_xml
                    .as_deref()
                    .or(generated_params.as_deref())
                {
                    storage.push_str(out, params).map_err(xml_error)?;
                }
                if has_memo {
                    storage
                        .push_str(
                            out,
                            &render_sub_list_open_with_storage(
                                f.memo_text_direction.as_deref(),
                                storage,
                            )?,
                        )
                        .map_err(xml_error)?;
                    let mut vert_cursor: u32 = 0;
                    for para in &f.memo_paragraphs {
                        ctx.para_shape_ids.reference(para.para_shape_id);
                        let sid = ctx.effective_style_id(para.style_id);
                        ctx.style_ids.reference(sid as u16);
                        let (runs, linesegs, advance) =
                            render_paragraph_parts_with_storage(para, vert_cursor, ctx, storage)?;
                        vert_cursor = advance;
                        let pid = ctx.next_para_id();
                        storage
                            .push_str(
                                out,
                                &render_hp_p_open_with_storage(para, pid, sid, storage)?,
                            )
                            .map_err(xml_error)?;
                        storage.push_str(out, &runs).map_err(xml_error)?;
                        storage.push_str(out, &linesegs).map_err(xml_error)?;
                        storage.push_str(out, "</hp:p>").map_err(xml_error)?;
                    }
                    storage.push_str(out, "</hp:subList>").map_err(xml_error)?;
                }
                storage
                    .push_str(out, "</hp:fieldBegin>")
                    .map_err(xml_error)?;
            } else {
                match checked_xml_result(
                    writer_to_string_with_storage(|w| write_field_begin(w, f), storage),
                    storage,
                )? {
                    Ok(xml) => storage.push_str(out, &xml).map_err(xml_error)?,
                    Err(e) => eprintln!("[hwpx] Field 직렬화 실패: {e}"),
                }
            }
            storage.push_str(out, "</hp:ctrl>").map_err(xml_error)?;
        }
        Control::PageHide(ph) => storage
            .push_str(out, &render_page_hiding_with_storage(ph, storage)?)
            .map_err(xml_error)?,
        Control::PageNumberPos(pn) => {
            // [#6869] 같은 문단의 두 번째 이후 쪽번호 위치 컨트롤은 내지 않는다.
            // XML 을 한 글자도 내지 않으므로 `render_control_slot_tracked` 가 이 슬롯을
            // "HWP5 축에만 있는 슬롯" 으로 세고, `#5943` 의 `textpos` 보정이 그대로 걸린다.
            if !ctx.para_page_num_pos_emitted {
                ctx.para_page_num_pos_emitted = true;
                storage
                    .push_str(out, &render_page_num_with_storage(pn, storage)?)
                    .map_err(xml_error)?;
            }
        }
        Control::PageNumCtrl(pnc) => storage
            .push_str(
                out,
                &xml_value(
                    storage,
                    format_args!(
                        r#"<hp:ctrl><hp:pageNumCtrl pageStartsOn="{}"/></hp:ctrl>"#,
                        pnc.page_starts_on.as_hwpx()
                    ),
                )?,
            )
            .map_err(xml_error)?,
        Control::NewNumber(nn) => storage
            .push_str(out, &render_new_num_with_storage(nn, storage)?)
            .map_err(xml_error)?,
        Control::Header(h) => storage
            .push_str(out, &render_header_with_storage(h, ctx, storage)?)
            .map_err(xml_error)?,
        Control::Footer(f) => storage
            .push_str(out, &render_footer_with_storage(f, ctx, storage)?)
            .map_err(xml_error)?,
        Control::AutoNumber(an) => storage
            .push_str(out, &render_autonum_with_storage(an, storage)?)
            .map_err(xml_error)?,
        Control::Form(form) => match checked_xml_result(
            writer_to_string_with_storage(|w| super::form::write_form(w, form), storage),
            storage,
        )? {
            // 폼은 <hp:run> 직접 자식 (Table/Picture와 동일, <hp:ctrl> 비포장)
            Ok(xml) => storage.push_str(out, &xml).map_err(xml_error)?,
            Err(e) => eprintln!("[hwpx] Form 직렬화 실패: {e}"),
        },
        Control::CharOverlap(co) => storage
            .push_str(out, &render_compose_with_storage(co, storage)?)
            .map_err(xml_error)?,
        // [Task #1587] 덧말(Ruby) 인라인 방출. is_hwpx_inline_slot 에 등록돼 슬롯 위치는
        // 자동이나 종전 방출 arm 부재로 드롭됐다. parse_dutmal 의 역매핑.
        Control::Ruby(r) => storage
            .push_str(out, &render_dutmal_with_storage(r, storage)?)
            .map_err(xml_error)?,
        // 숨은 설명 — 화면에 안 보여도 파일에는 문단 리스트로 존재한다. 방출 arm 이
        // 없던 탓에 저장할 때마다 통째로 사라졌다(자세한 근거는 아래 catch-all 주석).
        Control::HiddenComment(hc) => storage
            .push_str(out, &render_hidden_comment_with_storage(hc, ctx, storage)?)
            .map_err(xml_error)?,
        // [Task #1379/#1584] 인라인 colPr 방출.
        // - subList(depth>0): 전부 인라인 방출(원본 XML 인라인 존재).
        // - 본문(depth 0): 첫 문단의 첫 ColumnDef 1개는 섹션 템플릿 colPr 앵커가 이미
        //   방출했으므로(중복 방지) consume-once 플래그로 XML 만 건너뛴다. 슬롯 자체는
        //   상위(render_runs)에서 유지하므로 char-offset 위치 정합은 보존된다.
        Control::ColumnDef(cd) => {
            if ctx.sub_list_depth == 0 && ctx.body_coldef_template_pending {
                ctx.body_coldef_template_pending = false;
            } else {
                storage
                    .push_str(out, &render_col_pr_ctrl_with_storage(cd, storage)?)
                    .map_err(xml_error)?;
            }
        }
        // [#4388] Unknown은 HWPX 로 옮길 대응 표현이 없어 여기서도 드롭된다.
        // Hyperlink은 위 arm에서 HWPX fieldBegin으로 승격한다. Unknown 경고는
        // `warn_if_unrepresentable_in_hwpx` 하나로 통일한다(mismatch-분기 제외 지점,
        // 위쪽 934행 부근과 동일 호출). 이 함수 아래 catch-all 이 처리한다.
        //
        // [#4388 census] catch-all `_`(warn 호출 포함)에 실제로 도달하는 나머지
        // `Control` 변형은 세 가지 — 새 변형을 추가할 때 이 목록을 갱신할 것:
        //   - `Unknown`: 위 참조. 조용히 버리지 않도록 경고.
        //   - `SectionDef`: 의도적 무해 no-op. 위치 슬롯 축(hidden 슬롯 정합, 이 함수
        //     966행 근처 주석)만 소비하고 XML 은 별도 경로(`<hp:secPr>` 섹션 템플릿)가
        //     방출한다 — 여기서 다시 방출하면 중복이 된다. warn 헬퍼도 이 변형은
        //     무시한다.
        //   - `HiddenComment`: 이제 위 `render_hidden_comment` arm 이 방출한다.
        //     종전 주석은 "폭이 0이라 이 함수에 거의 도달하지 않는다"고 봤지만 그건
        //     **HWPX 파서 기준**이었다. HWP5 에서 `tcmt` 는 8유닛 확장 컨트롤이라
        //     h2x 경로에서는 정상적으로 슬롯에 들어와 여기 도달한다 — 실측(08361
        //     문단 0.0: `cc=33, text_len=0, controls=4` = 4×8+1)이 이를 보인다.
        //     방출 arm 이 없던 탓에 10k 스윕에서 숨은 설명이 통째로 사라졌고
        //     (`tcmt` CTRL_DIFF 13경로), 내용이 본문의 대부분인 문서는 96.9% 를
        //     잃었다(06397). x2x 축(HWPX 파서가 위치 마커를 push 하지 않아 폭 0)은
        //     여전히 별도 작업이 필요하다.
        c => warn_if_unrepresentable_in_hwpx(c),
    }

    ctx.check_storage()?;

    Ok(())
}

/// [#4388] HWPX 로 옮길 대응 표현이 없어 드롭되는 컨트롤(Hyperlink/Unknown)을
/// **조용히 버리지 않도록** 경고만 남긴다. 두 호출 지점(이 함수 위쪽
/// `render_runs` 의 mismatch-분기 제외 시점, `render_control_slot` 의
/// catch-all)에서 공유한다 — 한 문단의 한 컨트롤은 두 분기 중 하나로만
/// 소비되므로 중복 경고는 없다.
///
/// **`is_hwpx_inline_slot` 에는 등록하지 않는다.** 그 목록은
/// `roundtrip::diff_documents` 의 IR 비교(포맷 비종속 — `export-hwpx` 뿐 아니라
/// `convert`(HWP5 대상) `--verify` 도 재사용)에도 쓰이는데, 등록해봤다면 HWP5
/// 직렬화기가 이슈 범위 밖에서 이미 Hyperlink 의 ctrl_id 를 0 으로 고정해 버려
/// CTRL_HEADER 자체를 쓰지 않는 기존 HWP5 손실까지 새로 "검출"되어
/// `tests/issue_hwp3_bookmark_native.rs::bookmarks_survive_saving_to_hwp5`
/// 처럼 하이퍼링크와 무관한 기존 회귀 테스트가 깨진다(#4388 후속 보고, 실측
/// 재현: hwp3-sample16.hwp 문단 27/32/196/657 이 전부 Hyperlink). "조용히
/// 버리지 말라"는 경고 축과 "IR 비교에 넣는다"는 검증 축은 별개다.
fn warn_if_unrepresentable_in_hwpx(control: &Control) {
    match control {
        Control::Hyperlink(hl) => {
            eprintln!(
                "[hwpx] 경고: Hyperlink 컨트롤을 HWPX로 저장할 수 없어 드롭됩니다 \
                 (url={:?}, text={:?}) — HWPX는 하이퍼링크를 Field(HYPERLINK)로 표현하며 \
                 이 변환은 아직 지원되지 않습니다.",
                hl.url, hl.text
            );
        }
        Control::Unknown(u) => {
            eprintln!(
                "[hwpx] 경고: 인식할 수 없는 컨트롤(ctrl_id=0x{:08X})을 HWPX로 저장할 수 \
                 없어 드롭됩니다 — 원본 컨트롤의 세부 데이터가 보존되지 않아 이 변환은 \
                 지원되지 않습니다.",
                u.ctrl_id
            );
        }
        _ => {}
    }
}

/// 덧말(Ruby) `<hp:dutmal>` 직렬화 (#1587). `parse_dutmal` 의 역매핑.
/// 속성 순서는 한컴 실측(posType szRatio option styleIDRef align)을 따른다.
fn render_dutmal(r: &Ruby) -> String {
    render_dutmal_with_storage(r, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_dutmal_with_storage<S: crate::storage::Storage>(
    r: &Ruby,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let pos_type = match r.pos_type {
        1 => "BOTTOM",
        _ => "TOP",
    };
    let align = match r.align {
        1 => "LEFT",
        2 => "RIGHT",
        3 => "CENTER",
        4 => "DISTRIBUTE",
        5 => "DISTRIBUTE_SPACE",
        _ => "JUSTIFY",
    };
    xml_value(
        storage,
        format_args!(
            r#"<hp:dutmal posType="{}" szRatio="{}" option="{}" styleIDRef="{}" align="{}"><hp:mainText>{}</hp:mainText><hp:subText>{}</hp:subText></hp:dutmal>"#,
            pos_type,
            r.sz_ratio,
            r.option,
            r.style_id_ref,
            align,
            xml_escape_with_storage(&r.main_text, storage)?,
            xml_escape_with_storage(&r.ruby_text, storage)?,
        ),
    )
}

/// `raw_parameters_xml` 이 없을 때(HWPX 원문 밖 경로 — HWP5 왕복 또는 API 로 새로
/// 만든 필드) `<hp:parameters>` 를 다시 조립한다.
///
/// [#4396] `field.parameters` 트리(HWPX 파서 또는 HWP5 CTRL_DATA 확장 아이템에서 채워짐)
/// 가 있으면 그 트리를 그대로 재조립 — `Prop`/`Direction`/`Path`/`Category` 등이
/// `Command` 하나로 축소되던 손실을 여기서 막는다. 트리가 없으면(순수 API 생성 필드
/// 등, 파싱 이력이 전혀 없는 경우) 예전처럼 `Command` 하나만 담은 최소 형태로 합성한다.
fn generated_field_parameters(field: &Field) -> Option<String> {
    if field.raw_parameters_xml.is_some() {
        return None;
    }
    if !field.parameters.is_empty() {
        return Some(field.parameters.render_xml("parameters"));
    }
    if field.command.is_empty() {
        return None;
    }
    // HWP5-origin memo fields have their whole identity in the command. Hancom's
    // HWPX shape carries the same values as named parameters; emitting only
    // `Command` loses the author and number for readers that do not split it.
    if field.field_type == crate::model::control::FieldType::Memo
        && field.command.starts_with("MEMO/")
    {
        let tokens: Vec<&str> = field.command.split('/').collect();
        let shape = tokens.get(1).copied().unwrap_or("65535");
        let number = tokens.get(2).copied().unwrap_or("0");
        let author = tokens.get(5).copied().unwrap_or("");
        let date = crate::model::memo_time::date(&field.command);
        return Some(format!(
            concat!(
                r#"<hp:parameters cnt="{count}" name="">"#,
                r#"<hp:integerParam name="Prop">0</hp:integerParam>"#,
                r#"<hp:stringParam name="Command">{command}</hp:stringParam>"#,
                r#"<hp:stringParam name="ID">memo{number}</hp:stringParam>"#,
                r#"<hp:integerParam name="Number">{number}</hp:integerParam>"#,
                r#"<hp:stringParam name="Author">{author}</hp:stringParam>"#,
                r#"<hp:stringParam name="MemoShapeIDRef">{shape}</hp:stringParam>"#,
                r#"{date}</hp:parameters>"#,
            ),
            count = if date.is_some() { 7 } else { 6 },
            date = date
                .map(|d| format!(r#"<hp:stringParam name="CreateDateTime">{d}</hp:stringParam>"#))
                .unwrap_or_default(),
            command = xml_escape(&field.command),
            number = xml_escape(number),
            author = xml_escape(author),
            shape = xml_escape(shape),
        ));
    }
    Some(format!(
        r#"<hp:parameters cnt="1" name=""><hp:stringParam name="Command">{}</hp:stringParam></hp:parameters>"#,
        xml_escape(&field.command),
    ))
}

/// 셀·글상자 subList 인라인 `<hp:ctrl><hp:colPr .../></hp:ctrl>` (#1379 3단계).
/// `parse_col_pr` / `parse_col_line` / `parse_col_sz`(parser/hwpx/section.rs)의 역매핑.
fn render_col_pr_ctrl(cd: &ColumnDef) -> String {
    render_col_pr_ctrl_with_storage(cd, &crate::storage::Unbounded).expect("unbounded section XML")
}

fn render_col_pr_ctrl_with_storage<S: crate::storage::Storage>(
    cd: &ColumnDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let col_type = match cd.column_type {
        ColumnType::Distribute => "BalancedNewspaper",
        ColumnType::Parallel => "Parallel",
        ColumnType::Normal => "NEWSPAPER",
    };
    let layout = match cd.direction {
        ColumnDirection::RightToLeft => "RIGHT",
        ColumnDirection::Mirror => "MIRROR",
        ColumnDirection::LeftToRight => "LEFT",
    };
    let mut out = xml_value(
        storage,
        format_args!(
            r#"<hp:ctrl><hp:colPr id="" type="{}" layout="{}" colCount="{}" sameSz="{}" sameGap="{}""#,
            col_type, layout, cd.column_count, cd.same_width as u8, cd.spacing,
        ),
    )?;
    // [#4387] sameSz="false"(단 너비 개별 지정)일 때 <hp:colSz>(단별 너비·간격,
    // ColumnDefType 스키마상 colLine 다음 자식)를 방출한다. 미방출 시 HWPX
    // 왕복에서 불균등 단 너비가 사라지고 렌더러(page_layout.rs
    // calculate_column_areas)가 균등 분할로 저하한다.
    let mut col_sz_xml = String::new();
    if !cd.same_width {
        for (i, w) in cd.widths.iter().enumerate() {
            let gap = cd.gaps.get(i).copied().unwrap_or(0);
            storage
                .push_str(
                    &mut col_sz_xml,
                    &xml_value(
                        storage,
                        format_args!(r#"<hp:colSz width="{}" gap="{}"/>"#, w, gap),
                    )?,
                )
                .map_err(xml_error)?;
        }
    }
    if cd.separator_type != 0 || !col_sz_xml.is_empty() {
        storage.push_char(&mut out, '>').map_err(xml_error)?;
        if cd.separator_type != 0 {
            storage
                .push_str(
                    &mut out,
                    &xml_value(
                        storage,
                        format_args!(
                            r#"<hp:colLine type="{}" width="{} mm" color="{}"/>"#,
                            col_line_type_str(cd.separator_type),
                            line_width_mm(cd.separator_width),
                            super::shape::color_to_hex_with_storage(cd.separator_color, storage)?,
                        ),
                    )?,
                )
                .map_err(xml_error)?;
        }
        storage.push_str(&mut out, &col_sz_xml).map_err(xml_error)?;
        storage
            .push_str(&mut out, "</hp:colPr></hp:ctrl>")
            .map_err(xml_error)?;
    } else {
        storage
            .push_str(&mut out, "/></hp:ctrl>")
            .map_err(xml_error)?;
    }
    Ok(out)
}

/// `parse_hwpx_line_type` 역매핑 (colLine type).
fn col_line_type_str(t: u8) -> &'static str {
    match t {
        2 => "DASH",
        3 => "DOT",
        4 => "DASH_DOT",
        5 => "DASH_DOT_DOT",
        6 => "LONG_DASH",
        7 => "CIRCLE",
        _ => "SOLID",
    }
}

/// HWP 선 굵기 인덱스 → mm 수치 문자열 (`parse_hwpx_line_width` 역매핑).
fn line_width_mm(w: u8) -> &'static str {
    match w {
        0 => "0.1",
        1 => "0.12",
        2 => "0.15",
        3 => "0.2",
        4 => "0.25",
        5 => "0.3",
        6 => "0.4",
        7 => "0.5",
        8 => "0.6",
        9 => "0.7",
        10 => "1.0",
        11 => "1.5",
        12 => "2.0",
        13 => "3.0",
        14 => "4.0",
        _ => "5.0",
    }
}

/// `<hp:compose>` 글자겹침(CharOverlap) — `<hp:run>` 직접 자식 (<hp:ctrl> 비포장).
/// `parse_compose`(parser/hwpx/section.rs)의 역매핑. charPr 목록은 미설정(u32::MAX)
/// 항목 포함 원본 그대로 방출한다 (ID 참조 등록 비대상).
fn render_compose(co: &CharOverlap) -> String {
    render_compose_with_storage(co, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_compose_with_storage<S: crate::storage::Storage>(
    co: &CharOverlap,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let circle_type = match co.border_type {
        1 => "SHAPE_CIRCLE",
        2 => "SHAPE_REVERSAL_CIRCLE",
        3 => "SHAPE_RECTANGLE",
        4 => "SHAPE_REVERSAL_RECTANGLE",
        5 => "SHAPE_TRIANGLE",
        6 => "SHAPE_REVERSAL_TIRANGLE",
        7 => "SHAPE_LIGHT",
        8 => "SHAPE_RHOMBUS",
        9 => "SHAPE_REVERSAL_RHOMBUS",
        10 => "SHAPE_ROUNDED_RECTANGLE",
        11 => "SHAPE_EMPTY_CIRCULATE_TRIANGLE",
        12 => "SHAPE_THIN_CIRCULATE_TRIANGLE",
        13 => "SHAPE_THICK_CIRCULATE_TRIANGLE",
        _ => "CHAR",
    };
    let compose_type = if co.expansion == 1 {
        "OVERLAP"
    } else {
        "SPREAD"
    };
    // [#5140] 겹침 글자도 사용자 정의 기호일 수 있다. 속성이라 위치 축과 무관하므로
    // 본문과 같은 표를 그대로 적용한다. HWP 원문 배열의 표지와 PUA 숫자는 한컴
    // HWPX처럼 친 글로 돌린다.
    let plain = crate::renderer::composer::char_overlap_plain_text(co);
    let text = storage
        .chars(plain.chars().map(hancom_symbol_for_hwpx))
        .map_err(xml_error)?;
    let mut out = xml_value(
        storage,
        format_args!(
            r#"<hp:compose circleType="{}" charSz="{}" composeType="{}" charPrCnt="{}" composeText="{}">"#,
            circle_type,
            co.inner_char_size,
            compose_type,
            co.char_shape_ids.len(),
            xml_escape_with_storage(&text, storage)?,
        ),
    )?;
    for id in &co.char_shape_ids {
        storage
            .push_str(
                &mut out,
                &xml_value(storage, format_args!(r#"<hp:charPr prIDRef="{}"/>"#, id))?,
            )
            .map_err(xml_error)?;
    }
    storage
        .push_str(&mut out, "</hp:compose>")
        .map_err(xml_error)?;
    Ok(out)
}

/// 장식 문자(userChar/prefixChar/suffixChar)용 속성값. '\0'(미설정)은 빈 문자열.
fn ctrl_char_attr(c: char) -> String {
    ctrl_char_attr_with_storage(c, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn ctrl_char_attr_with_storage<S: crate::storage::Storage>(
    c: char,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    Ok(if c == '\0' {
        String::new()
    } else {
        xml_escape_with_storage(&xml_value(storage, c)?, storage)?
    })
}

/// `<hp:ctrl><hp:autoNum num=".." numType=".."><hp:autoNumFormat .../></hp:autoNum></hp:ctrl>`
/// 자동 번호(AutoNumber) 컨트롤. format은 pageNum formatType과 동일한 코드→문자열 매핑.
fn render_autonum(an: &AutoNumber) -> String {
    render_autonum_with_storage(an, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_autonum_with_storage<S: crate::storage::Storage>(
    an: &AutoNumber,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            concat!(
                r#"<hp:ctrl><hp:autoNum num="{num}" numType="{nt}">"#,
                r#"<hp:autoNumFormat type="{ty}" userChar="{u}" prefixChar="{p}" "#,
                r#"suffixChar="{s}" supscript="{sup}"/></hp:autoNum></hp:ctrl>"#
            ),
            num = an.number,
            nt = auto_number_type_to_str(an.number_type),
            ty = if an.format == 18 {
                // [#6872] 사용자 기호(`NumberFormat::UserChar` 서수).
                "USER_CHAR"
            } else {
                page_num_format_to_str(an.format)
            },
            u = ctrl_char_attr_with_storage(an.user_symbol, storage)?,
            p = ctrl_char_attr_with_storage(an.prefix_char, storage)?,
            s = ctrl_char_attr_with_storage(an.suffix_char, storage)?,
            sup = an.superscript as u8,
        ),
    )
}

/// 머리말/꼬리말 적용 범위 → HWPX `applyPageType`. `parse_apply_page_type`의 역매핑.
fn apply_page_type_to_str(a: HeaderFooterApply) -> &'static str {
    match a {
        HeaderFooterApply::Both => "BOTH",
        HeaderFooterApply::Even => "EVEN",
        HeaderFooterApply::Odd => "ODD",
    }
}

/// `<hp:ctrl><hp:{header|footer} applyPageType=".."><hp:subList ...>문단들</hp:subList>...`
/// 머리말/꼬리말은 중첩 문단(subList)을 가진다 — render_note_sublist와 동일한 문단 직렬화
/// 경로(render_paragraph_parts)를 쓰되, subList 텍스트 영역 속성은 IR 보존값을 사용한다.
fn render_header_footer(
    tag: &str,
    h: HeaderFooterFields<'_>,
    ctx: &mut SerializeContext,
) -> String {
    render_header_footer_with_storage(tag, h, ctx, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_header_footer_with_storage<S: crate::storage::Storage>(
    tag: &str,
    h: HeaderFooterFields<'_>,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = xml_value(
        storage,
        format_args!(
            concat!(
                r#"<hp:ctrl><hp:{tag} id="{id}" applyPageType="{apply}">"#,
                r#"<hp:subList id="" textDirection="HORIZONTAL" lineWrap="BREAK" vertAlign="{va}" "#,
                r#"linkListIDRef="0" linkListNextIDRef="0" textWidth="{tw}" textHeight="{th}" "#,
                r#"hasTextRef="{tr}" hasNumRef="{nr}">"#
            ),
            tag = tag,
            id = h.id,
            apply = apply_page_type_to_str(h.apply_to),
            // [#6186] 종전에는 늘 "TOP" 으로 굳혀 저장해 세로 정렬이 왕복에서 유실됐다.
            va = match (h.list_attr >> 21) & 0b11 {
                1 => "CENTER",
                2 => "BOTTOM",
                _ => "TOP",
            },
            tw = h.text_width,
            th = h.text_height,
            tr = h.text_ref,
            nr = h.num_ref,
        ),
    )?;
    let mut vert_cursor: u32 = 0;
    for p in h.paragraphs.iter() {
        let (runs, linesegs, advance) =
            render_paragraph_parts_with_storage(p, vert_cursor, ctx, storage)?;
        vert_cursor = advance;
        let pid = ctx.next_para_id();
        let sid = ctx.effective_style_id(p.style_id);
        storage
            .push_str(
                &mut out,
                &render_hp_p_open_with_storage(p, pid, sid, storage)?,
            )
            .map_err(xml_error)?;
        storage.push_str(&mut out, &runs).map_err(xml_error)?;
        storage.push_str(&mut out, &linesegs).map_err(xml_error)?;
        storage.push_str(&mut out, "</hp:p>").map_err(xml_error)?;
    }
    storage
        .push_str(
            &mut out,
            &xml_value(
                storage,
                format_args!("</hp:subList></hp:{tag}></hp:ctrl>", tag = tag),
            )?,
        )
        .map_err(xml_error)?;
    Ok(out)
}

/// render_header_footer 공통 인자 묶음 (Header/Footer가 동일 필드를 가짐).
struct HeaderFooterFields<'a> {
    id: u32,
    apply_to: HeaderFooterApply,
    /// HWPX subList list_attr — 세로 정렬(비트 21~22) 보존용.
    list_attr: u32,
    text_width: u32,
    text_height: u32,
    text_ref: u8,
    num_ref: u8,
    paragraphs: &'a [Paragraph],
}

fn hwpx_header_footer_id(raw_ctrl_extra: &[u8]) -> u32 {
    raw_ctrl_extra
        .get(..4)
        .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
        .unwrap_or(0)
}

fn render_header(h: &Header, ctx: &mut SerializeContext) -> String {
    render_header_with_storage(h, ctx, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_header_with_storage<S: crate::storage::Storage>(
    h: &Header,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    render_header_footer_with_storage(
        "header",
        HeaderFooterFields {
            id: hwpx_header_footer_id(&h.raw_ctrl_extra),
            apply_to: h.apply_to,
            list_attr: h.list_attr,
            text_width: h.text_width,
            text_height: h.text_height,
            text_ref: h.text_ref,
            num_ref: h.num_ref,
            paragraphs: &h.paragraphs,
        },
        ctx,
        storage,
    )
}

fn render_footer(f: &Footer, ctx: &mut SerializeContext) -> String {
    render_footer_with_storage(f, ctx, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_footer_with_storage<S: crate::storage::Storage>(
    f: &Footer,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    render_header_footer_with_storage(
        "footer",
        HeaderFooterFields {
            id: hwpx_header_footer_id(&f.raw_ctrl_extra),
            apply_to: f.apply_to,
            list_attr: f.list_attr,
            text_width: f.text_width,
            text_height: f.text_height,
            text_ref: f.text_ref,
            num_ref: f.num_ref,
            paragraphs: &f.paragraphs,
        },
        ctx,
        storage,
    )
}

/// `<hp:ctrl><hp:pageHiding .../></hp:ctrl>` — 감추기(PageHide) 컨트롤.
/// `parse_page_hiding_attrs`의 역매핑. bool → "0"/"1" (한컴 정합).
fn render_page_hiding(ph: &PageHide) -> String {
    render_page_hiding_with_storage(ph, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_page_hiding_with_storage<S: crate::storage::Storage>(
    ph: &PageHide,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            concat!(
                r#"<hp:ctrl><hp:pageHiding hideHeader="{}" hideFooter="{}" "#,
                r#"hideMasterPage="{}" hideBorder="{}" hideFill="{}" hidePageNum="{}"/></hp:ctrl>"#
            ),
            ph.hide_header as u8,
            ph.hide_footer as u8,
            ph.hide_master_page as u8,
            ph.hide_border as u8,
            ph.hide_fill as u8,
            ph.hide_page_num as u8,
        ),
    )
}

/// 쪽 번호 위치 코드(표 150) → HWPX `pos` 문자열. `parse_page_num_attrs`의 역매핑.
fn page_num_pos_to_str(pos: u8) -> &'static str {
    match pos {
        0 => "NONE",
        1 => "TOP_LEFT",
        2 => "TOP_CENTER",
        3 => "TOP_RIGHT",
        4 => "BOTTOM_LEFT",
        5 => "BOTTOM_CENTER",
        6 => "BOTTOM_RIGHT",
        7 => "OUTSIDE_TOP",
        8 => "OUTSIDE_BOTTOM",
        9 => "INSIDE_TOP",
        10 => "INSIDE_BOTTOM",
        _ => "BOTTOM_CENTER",
    }
}

/// 번호 형식 코드(표 134) → HWPX `formatType` 문자열. `parse_page_num_attrs`의 역매핑.
/// 문단 번호와 같은 OWPML 이름을 쓴다(원 문자는 스펙 철자 "CIRCLED_DIGIT").
fn page_num_format_to_str(fmt: u8) -> &'static str {
    super::header::numbering_format_str(fmt)
}

/// `<hp:ctrl><hp:pageNum .../></hp:ctrl>` — 쪽 번호 위치(PageNumberPos) 컨트롤.
fn render_page_num(pn: &PageNumberPos) -> String {
    render_page_num_with_storage(pn, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_page_num_with_storage<S: crate::storage::Storage>(
    pn: &PageNumberPos,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#7633] HWP5 `pgnp` 의 줄표 문자가 0 이면 줄표 없는 쪽 번호다(한컴 PDF `1`, hwpspec).
    // 한/글은 `sideChar=""` 를 줄표 없음으로 그린다 — 종전처럼 `'-'` 로 채우면 `- 1 -` 가 된다.
    // 속성을 생략하면 스키마 기본값 `"-"` 로 읽힐 수 있으므로 빈 값을 명시한다.
    let side = if pn.dash_char == '\0' || pn.dash_char.is_whitespace() {
        String::new()
    } else {
        xml_value(storage, pn.dash_char)?
    };
    xml_value(
        storage,
        format_args!(
            r#"<hp:ctrl><hp:pageNum pos="{}" formatType="{}" sideChar="{}"/></hp:ctrl>"#,
            page_num_pos_to_str(pn.position),
            page_num_format_to_str(pn.format),
            xml_escape_with_storage(&side, storage)?,
        ),
    )
}

/// 번호 종류 → HWPX `numType` 문자열. `parse_num_type`의 역매핑.
///
/// [#1387] Picture 는 "PICTURE" — 한컴 실물 표기. 종전 "FIGURE" 는 한컴 생산 파일에
/// 비실재(samples/hwpx 전수 0건)하고 한컴에디터가 그림 번호로 인식하지 못해 캡션
/// 번호가 미출력됐다 (한컴 판정 실증). 파서는 FIGURE/PICTURE 양쪽 수용 유지.
fn auto_number_type_to_str(t: AutoNumberType) -> &'static str {
    match t {
        AutoNumberType::Page => "PAGE",
        AutoNumberType::Footnote => "FOOTNOTE",
        AutoNumberType::Endnote => "ENDNOTE",
        AutoNumberType::Picture => "PICTURE",
        AutoNumberType::Table => "TABLE",
        AutoNumberType::Equation => "EQUATION",
        AutoNumberType::TotalPage => "TOTAL_PAGE",
    }
}

/// `<hp:ctrl><hp:newNum .../></hp:ctrl>` — 새 번호 지정(NewNumber) 컨트롤.
fn render_new_num(nn: &NewNumber) -> String {
    render_new_num_with_storage(nn, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_new_num_with_storage<S: crate::storage::Storage>(
    nn: &NewNumber,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            r#"<hp:ctrl><hp:newNum num="{}" numType="{}"/></hp:ctrl>"#,
            nn.number,
            auto_number_type_to_str(nn.number_type),
        ),
    )
}

fn checked_xml_result<S: crate::storage::Storage, T>(
    result: Result<T, SerializeError>,
    storage: &S,
) -> Result<Result<T, SerializeError>, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // Existing semantic-error branches remain; request exhaustion must escape them.
    storage.bytes(0).map_err(xml_error)?;
    Ok(result)
}
fn writer_to_string_with_storage<S: crate::storage::Storage, F>(
    f: F,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
    F: FnOnce(
        &mut Writer<crate::serializer::budget_cursor::BudgetCursor<'_, S>>,
    ) -> Result<(), SerializeError>,
{
    let mut writer = Writer::new(crate::serializer::budget_cursor::BudgetCursor::new(
        storage,
        usize::MAX,
    ));
    f(&mut writer)?;
    String::from_utf8(writer.into_inner().into_inner()).map_err(|error| {
        SerializeError::XmlError(format!("invalid UTF-8 from XML writer: {error}"))
    })
}

fn writer_to_string<F>(f: F) -> Result<String, SerializeError>
where
    F: FnOnce(&mut Writer<Vec<u8>>) -> Result<(), SerializeError>,
{
    let mut writer = Writer::new(Vec::new());
    f(&mut writer)?;
    let bytes = writer.into_inner();
    String::from_utf8(bytes)
        .map_err(|e| SerializeError::XmlError(format!("invalid UTF-8 from XML writer: {e}")))
}

fn render_shape(shape: &ShapeObject, ctx: &mut SerializeContext) -> String {
    render_shape_with_storage(shape, ctx, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_shape_with_storage<S: crate::storage::Storage>(
    shape: &ShapeObject,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // Rectangle: Writer-based serializer (drawText 포함)
    if let ShapeObject::Rectangle(r) = shape {
        return Ok(
            match checked_xml_result(
                writer_to_string_with_storage(
                    |w| super::shape::write_rect_with_storage(w, r, ctx, storage),
                    storage,
                ),
                storage,
            )? {
                Ok(xml) => xml,
                Err(e) => {
                    eprintln!("[hwpx] Shape::Rectangle 직렬화 실패: {e}");
                    String::new()
                }
            },
        );
    }
    // Line: Writer-based serializer
    if let ShapeObject::Line(l) = shape {
        return Ok(
            match checked_xml_result(
                writer_to_string_with_storage(
                    |w| super::shape::write_line_with_storage(w, l, ctx, storage),
                    storage,
                ),
                storage,
            )? {
                Ok(xml) => xml,
                Err(e) => {
                    eprintln!("[hwpx] Shape::Line 직렬화 실패: {e}");
                    String::new()
                }
            },
        );
    }
    if let ShapeObject::Group(g) = shape {
        let mut xml = match checked_xml_result(
            writer_to_string_with_storage(
                |w| {
                    super::shape::write_container_open_with_storage(
                        w,
                        &g.common,
                        &g.shape_attr,
                        storage,
                    )
                },
                storage,
            ),
            storage,
        )? {
            Ok(xml) => xml,
            Err(e) => {
                eprintln!("[hwpx] Shape::Group 직렬화 실패: {e}");
                String::new()
            }
        };
        for child in &g.children {
            storage
                .push_str(&mut xml, &render_shape_with_storage(child, ctx, storage)?)
                .map_err(xml_error)?;
        }
        // 캡션 (#1403) 은 자식 도형 뒤에 방출 — 한컴 실물(aift.hwpx) 순서
        // 설명(#1392)은 캡션 직후 (write_container_close 내부)
        match checked_xml_result(
            writer_to_string_with_storage(
                |w| {
                    super::shape::write_container_close_with_storage(
                        w,
                        g.caption.as_ref(),
                        &g.common,
                        ctx,
                        storage,
                    )
                },
                storage,
            ),
            storage,
        )? {
            Ok(close) => storage.push_str(&mut xml, &close).map_err(xml_error)?,
            Err(e) => eprintln!("[hwpx] Shape::Group 닫기 실패: {e}"),
        }
        return Ok(xml);
    }
    const NO_PTS: &[crate::model::Point] = &[];
    let (tag, c, caption, drawing, points): (
        _,
        _,
        _,
        Option<&crate::model::shape::DrawingObjAttr>,
        &[crate::model::Point],
    ) = match shape {
        ShapeObject::Rectangle(_) | ShapeObject::Line(_) => unreachable!(),
        ShapeObject::Ellipse(e) => (
            "ellipse",
            &e.common,
            &e.drawing.caption,
            Some(&e.drawing),
            NO_PTS,
        ),
        ShapeObject::Arc(a) => (
            "arc",
            &a.common,
            &a.drawing.caption,
            Some(&a.drawing),
            NO_PTS,
        ),
        ShapeObject::Polygon(p) => (
            "polygon",
            &p.common,
            &p.drawing.caption,
            Some(&p.drawing),
            &p.points,
        ),
        // [#4676] curve 의 점은 `<hc:pt>` 가 아니라 `<hp:seg>` 체인으로 나간다(geom_tail).
        ShapeObject::Curve(cv) => (
            "curve",
            &cv.common,
            &cv.drawing.caption,
            Some(&cv.drawing),
            NO_PTS,
        ),
        ShapeObject::Group(_) => unreachable!(),
        ShapeObject::Picture(pic) => {
            return Ok(
                match checked_xml_result(
                    writer_to_string_with_storage(
                        |w| picture::write_picture_with_storage(w, pic, ctx, storage),
                        storage,
                    ),
                    storage,
                )? {
                    Ok(xml) => xml,
                    Err(e) => {
                        eprintln!("[hwpx] Shape::Picture 직렬화 실패: {e}");
                        String::new()
                    }
                },
            );
        }
        ShapeObject::Chart(ch) => ("chart", &ch.common, &ch.caption, None, NO_PTS),
        ShapeObject::Ole(o) => {
            // [#3546] hp:chart 출신(chart_id_ref 표식)은 hp:ole 이 아니라 원형
            // hp:chart(+switch) 구조로 재방출한다.
            return Ok(
                match checked_xml_result(
                    writer_to_string_with_storage(
                        |w| super::shape::write_ole_or_chart_with_storage(w, o, ctx, storage),
                        storage,
                    ),
                    storage,
                )? {
                    Ok(xml) => xml,
                    Err(e) => {
                        eprintln!("[hwpx] Shape::Ole 직렬화 실패: {e}");
                        String::new()
                    }
                },
            );
        }
    };
    // [Task #1598] ellipse / arc 전용 지오메트리(center/축/시작끝점) — 미방출 시 한글이
    // 타원/호를 다르게 렌더 → 누적 레이아웃 변동 → 페이지 붕괴(#1589 잔여). hc:pt(polygon/
    // curve) 와 상호배타이므로 동일 위치(shadow 직후, sz 직전)에 방출.
    let hc = |t: &str, p: &crate::model::Point| {
        xml_value(
            storage,
            format_args!(r#"<hc:{t} x="{}" y="{}"/>"#, p.x, p.y),
        )
    };
    let geom_tail = match shape {
        ShapeObject::Ellipse(e) => xml_value(
            storage,
            format_args!(
                "{}{}{}{}{}{}{}",
                hc("center", &e.center)?,
                hc("ax1", &e.axis1)?,
                hc("ax2", &e.axis2)?,
                hc("start1", &e.start1)?,
                hc("end1", &e.end1)?,
                hc("start2", &e.start2)?,
                hc("end2", &e.end2)?,
            ),
        )?,
        ShapeObject::Arc(a) => xml_value(
            storage,
            format_args!(
                "{}{}{}",
                hc("center", &a.center)?,
                hc("ax1", &a.axis1)?,
                hc("ax2", &a.axis2)?,
            ),
        )?,
        // [#4676] curve 는 점을 `<hp:seg>` 체인으로 방출한다 — `<hc:pt>` 나열은 한글이
        // 열다 죽는다(RPC 0x800706BE). 한컴 원본 실측: hp:curve 는 seg 만 쓰고 hc:pt 는
        // 한 번도 쓰지 않는다. seg 는 이웃한 두 점을 잇는 구간이므로 점 N 개 → seg N-1 개.
        ShapeObject::Curve(cv) => {
            curve_segs_xml_with_storage(&cv.points, &cv.segment_types, storage)?
        }
        _ => String::new(),
    };
    // [#4388] `<hp:arc>` 전용 `type` 속성(NORMAL/PIE/CHORD) — OWPML `CArcType` 계약.
    // 종전엔 이 속성 자체가 방출되지 않아 `arc_type` 이 항상 0(NORMAL)으로 저장됐다.
    let extra_attrs = match shape {
        ShapeObject::Arc(a) => xml_value(
            storage,
            format_args!(r#" type="{}""#, arc_type_hwpx_str(a.arc_type)),
        )?,
        _ => String::new(),
    };
    render_common_shape_xml_with_storage(
        tag,
        c,
        caption,
        drawing,
        points,
        &geom_tail,
        &extra_attrs,
        ctx,
        storage,
    )
}

/// [#4676] `CurveShape` 의 점 목록을 OWPML `<hp:seg>` 체인으로 방출한다.
///
/// 한글은 `<hp:curve>` 안의 `<hc:pt>` 나열을 만나면 여는 도중 죽는다(COM RPC 0x800706BE,
/// 10k 오라클 스윕에서 크래시 산출물 다수의 공통 원인). 한컴 원본은 언제나 seg 를 쓴다:
///
/// ```xml
/// <hp:seg type="CURVE" x1="0" y1="1680" x2="10440" y2="0"/>
/// <hp:seg type="LINE"  x1="10440" y1="0" x2="20940" y2="1800"/>
/// ```
///
/// `segment_types[i]`는 인접한 두 점 사이의 구간 종류(0: 직선, 1: 곡선)다.
/// HWP5와 HWPX가 같은 점 체인을 보존하며, 비어 있으면 기존 한글 호환 CURVE로 방출한다.
fn curve_segs_xml(points: &[crate::model::Point], segment_types: &[u8]) -> String {
    curve_segs_xml_with_storage(points, segment_types, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn curve_segs_xml_with_storage<S: crate::storage::Storage>(
    points: &[crate::model::Point],
    segment_types: &[u8],
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = String::new();
    for (i, w) in points.windows(2).enumerate() {
        let kind = match segment_types.get(i) {
            Some(0) => "LINE",
            _ => "CURVE",
        };
        storage
            .push_str(
                &mut out,
                &xml_value(
                    storage,
                    format_args!(
                        r#"<hp:seg type="{}" x1="{}" y1="{}" x2="{}" y2="{}"/>"#,
                        kind, w[0].x, w[0].y, w[1].x, w[1].y
                    ),
                )?,
            )
            .map_err(xml_error)?;
    }
    Ok(out)
}

/// [#4388] `ArcShape.arc_type` (0: Arc, 1: CircularSector, 2: Bow) →
/// `<hp:arc>` 의 `type` 속성값. `parse_arc_type_attr` 의 역매핑.
fn arc_type_hwpx_str(arc_type: u8) -> &'static str {
    match arc_type {
        1 => "PIE",
        2 => "CHORD",
        _ => "NORMAL",
    }
}

fn render_common_shape_xml(
    tag: &str,
    c: &CommonObjAttr,
    caption: &Option<crate::model::shape::Caption>,
    drawing: Option<&crate::model::shape::DrawingObjAttr>,
    points: &[crate::model::Point],
    geom_tail: &str,
    // [#4388] 태그별 부가 속성(현재는 `<hp:arc type="...">` 전용) — 없으면 "".
    extra_attrs: &str,
    ctx: &mut SerializeContext,
) -> String {
    render_common_shape_xml_with_storage(
        tag,
        c,
        caption,
        drawing,
        points,
        geom_tail,
        extra_attrs,
        ctx,
        &crate::storage::Unbounded,
    )
    .expect("unbounded object XML")
}

fn render_common_shape_xml_with_storage<S: crate::storage::Storage>(
    tag: &str,
    c: &CommonObjAttr,
    caption: &Option<crate::model::shape::Caption>,
    drawing: Option<&crate::model::shape::DrawingObjAttr>,
    points: &[crate::model::Point],
    geom_tail: &str,
    // [#4388] 태그별 부가 속성(현재는 `<hp:arc type="...">` 전용) — 없으면 "".
    extra_attrs: &str,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let shape_block = if let Some(d) = drawing {
        checked_xml_result(
            writer_to_string_with_storage(
                |w| {
                    super::shape::write_shape_component_block_with_storage(
                        w,
                        &d.shape_attr,
                        storage,
                    )
                },
                storage,
            ),
            storage,
        )?
        .unwrap_or_default()
    } else {
        String::new()
    };
    let geometry = if let Some(d) = drawing {
        let ls = checked_xml_result(
            writer_to_string_with_storage(
                |w| super::shape::write_line_shape_with_storage(w, &d.border_line, storage),
                storage,
            ),
            storage,
        )?
        .unwrap_or_default();
        let fb = checked_xml_result(
            writer_to_string_with_storage(
                |w| super::shape::write_fill_brush_with_storage(w, &d.fill, ctx, storage),
                storage,
            ),
            storage,
        )?
        .unwrap_or_default();
        let sh = checked_xml_result(
            writer_to_string_with_storage(
                |w| super::shape::write_shadow_with_storage(w, d, storage),
                storage,
            ),
            storage,
        )?
        .unwrap_or_default();
        let dt = if let Some(tb) = d.text_box.as_ref().filter(|tb| !tb.paragraphs.is_empty()) {
            checked_xml_result(
                writer_to_string_with_storage(
                    |w| super::shape::write_draw_text_with_storage(w, tb, ctx, storage),
                    storage,
                ),
                storage,
            )?
            .unwrap_or_default()
        } else {
            String::new()
        };
        let mut pts = String::new();
        for p in points {
            storage
                .push_str(
                    &mut pts,
                    &xml_value(storage, format_args!(r#"<hc:pt x="{}" y="{}"/>"#, p.x, p.y))?,
                )
                .map_err(xml_error)?;
        }
        xml_value(storage, format_args!("{ls}{fb}{sh}{dt}{pts}{geom_tail}"))?
    } else {
        String::new()
    };
    // 태그 부수 속성 — numberingType/dropcapstyle/href/groupLevel/instid (rect/line 동형).
    let group_level = drawing.map(|d| d.shape_attr.group_level).unwrap_or(0);
    let instid = drawing
        .map(|d| d.inst_id)
        .filter(|&i| i != 0)
        .unwrap_or(c.instance_id);
    let mut out = xml_value(
        storage,
        format_args!(
            concat!(
                r#"<hp:{tag} id="{id}" zOrder="{zo}" numberingType="{nt}" textWrap="{tw}" textFlow="{tf}" lock="{lock}" dropcapstyle="{dcs}" href="" groupLevel="{gl}" instid="{iid}"{extra}>"#,
                "{block}",
                "{geometry}",
                r#"<hp:sz width="{w}" height="{h}" widthRelTo="{wrt}" heightRelTo="{hrt}" protect="{prot}"/>"#,
                r#"<hp:pos treatAsChar="{tac}" affectLSpacing="0" flowWithText="{fwt}" allowOverlap="{ao}" holdAnchorAndSO="{hold}" vertRelTo="{vr}" vertAlign="{va}" horzRelTo="{hr}" horzAlign="{ha}" vertOffset="{vo}" horzOffset="{ho}"/>"#,
                r#"<hp:outMargin left="{ml}" right="{mr}" top="{mt}" bottom="{mb}"/>"#,
            ),
            tag = tag,
            extra = extra_attrs,
            block = shape_block,
            geometry = geometry,
            id = c.instance_id,
            zo = c.z_order,
            nt = super::shape::numbering_type_str(c.numbering_type),
            // [#2840] lock(개체 잠금) — IR 보존 값 방출 (종전 "0" 하드코딩).
            lock = if c.locked { "1" } else { "0" },
            dcs = super::shape::drop_cap_style_str(c.drop_cap_style),
            gl = group_level,
            iid = instid,
            tw = text_wrap_to_hwpx(c.text_wrap),
            // [#2790] textFlow(글 흐름) — 종전 "BOTH_SIDES" 리터럴은 파서
            // (parse_object_element_attrs:2962)가 IR 에 적재한 값을 저장에서만 버리는 순손실이었다.
            // write_rect/write_line(shape.rs)·render_equation 은 이미 IR 기반이다.
            tf = text_flow_to_hwpx(c.text_flow),
            tac = if c.treat_as_char { "1" } else { "0" },
            fwt = if c.flow_with_text { "1" } else { "0" },
            ao = if c.allow_overlap { "1" } else { "0" },
            hold = if c.prevent_page_break != 0 { "1" } else { "0" },
            w = c.width,
            h = c.height,
            // [#2726] 종전 widthRelTo/heightRelTo 는 "ABSOLUTE" 리터럴, protect 는 아예
            // 미방출이었다. 파서(parse_object_layout_child:2909)가 이미 3값을 IR 에 적재하므로
            // 저장에서만 버려지는 순손실이었다. #2697(표)·#2712(rect/line/container/pic) 와 동형.
            wrt = size_criterion_str(c.width_criterion),
            hrt = height_criterion_str(c.height_criterion),
            prot = if c.size_protect { "1" } else { "0" },
            vr = vert_rel_to_hwpx(c.vert_rel_to),
            va = vert_align_to_hwpx(c.vert_align),
            hr = horz_rel_to_hwpx(c.horz_rel_to),
            ha = horz_align_to_hwpx(c.horz_align),
            vo = c.vertical_offset,
            ho = c.horizontal_offset,
            ml = c.margin.left,
            mr = c.margin.right,
            mt = c.margin.top,
            mb = c.margin.bottom,
        ),
    )?;
    // 캡션 (#1403) — HWP5 파서는 모든 도형의 캡션을 적재하므로(parser/control/shape.rs)
    // legacy 경로(ellipse/arc/polygon/curve/chart/ole)도 방출해야 소실되지 않는다.
    if let Some(cap) = caption {
        match checked_xml_result(
            writer_to_string_with_storage(
                |w| super::table::write_caption_with_storage(w, cap, ctx, storage),
                storage,
            ),
            storage,
        )? {
            Ok(xml) => storage.push_str(&mut out, &xml).map_err(xml_error)?,
            Err(e) => eprintln!("[hwpx] Shape({tag}) 캡션 직렬화 실패: {e}"),
        }
    }
    // 설명 (#1451) — caption 직후 (OWPML AbstractShapeObjectType: outMargin→caption→shapeComment).
    // picture.rs:104 선례와 동일 순서. legacy 경로(ellipse/arc/polygon/curve/chart/ole) 보존.
    // 빈 description 미방출은 write_shape_comment 내부 가드로 보장된다.
    match checked_xml_result(
        writer_to_string_with_storage(
            |w| super::shape::write_shape_comment_with_storage(w, c, storage),
            storage,
        ),
        storage,
    )? {
        Ok(xml) => storage.push_str(&mut out, &xml).map_err(xml_error)?,
        Err(e) => eprintln!("[hwpx] Shape({tag}) shapeComment 직렬화 실패: {e}"),
    }
    storage
        .push_str(&mut out, &xml_value(storage, format_args!("</hp:{tag}>"))?)
        .map_err(xml_error)?;
    Ok(out)
}

/// [#2716] `<hp:footNote>` / `<hp:endNote>` 의 IR 보존 속성 묶음.
///
/// 종전에는 `number` 스칼라 하나만 `render_note_sublist` 로 넘겨 나머지 4개 필드가
/// 구조적으로 방출 불가였다. 같은 파일의 `render_header_footer` 가 쓰는
/// `HeaderFooterFields` 와 동일한 묶음 전달 패턴이다.
struct NoteAttrs {
    number: u16,
    /// `before_decoration_letter` — 0 이면 속성 생략(한컴 계약).
    prefix_char: u16,
    /// `after_decoration_letter` — 항상 방출.
    suffix_char: u16,
    /// [#6872] true 면 `suffixChar` 가 아니라 `userChar` 라는 이름으로 방출한다.
    decoration_is_user_char: bool,
    /// HWP5 `numberShape` — 0 이면 속성 생략(한컴 계약).
    number_shape: u32,
    /// HWP5 `instanceId` — 항상 방출.
    inst_id: u32,
}

/// [#2716] 각주/미주 ctrl 속성 문자열.
///
/// 한컴 저장본 실측 계약(samples 16파일 · note 828개, 3-09월_교육_통합_2023 의 HWP5/HWPX
/// 쌍 46개 필드 단위 전수 대조 일치):
/// - `number` / `suffixChar` / `instId` 는 항상 존재(828/828)
/// - `prefixChar` 는 `before_decoration_letter != 0` 일 때만 존재(598/828)
/// - `flag`(= HWP5 `numberShape`) 는 `number_shape != 0` 일 때만 존재(27/828)
/// - 속성 순서는 `flag → number → prefixChar → suffixChar → instId`
///
/// `suffixChar` 를 생략하면 파서(`parse_ctrl_footnote`)가 기본값 `0x0029` `)` 를 넣어
/// 닫는 장식이 없는(0) 각주가 오염된다 — HWP5 직렬화기가 `serializer/control.rs` 에서
/// 같은 이유로 고친 문제이므로 0 이어도 항상 방출한다.
fn render_note_attrs(attrs: &NoteAttrs) -> String {
    render_note_attrs_with_storage(attrs, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_note_attrs_with_storage<S: crate::storage::Storage>(
    attrs: &NoteAttrs,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = String::new();
    if attrs.number_shape != 0 {
        storage
            .push_str(
                &mut out,
                &xml_value(storage, format_args!(r#" flag="{}""#, attrs.number_shape))?,
            )
            .map_err(xml_error)?;
    }
    storage
        .push_str(
            &mut out,
            &xml_value(storage, format_args!(r#" number="{}""#, attrs.number))?,
        )
        .map_err(xml_error)?;
    if attrs.prefix_char != 0 {
        storage
            .push_str(
                &mut out,
                &xml_value(
                    storage,
                    format_args!(r#" prefixChar="{}""#, attrs.prefix_char),
                )?,
            )
            .map_err(xml_error)?;
    }
    // [#6872] 사용자 기호로 온 장식 문자는 같은 이름으로 되돌린다. 한컴은 번호 모양이
    // 사용자 기호일 때 `suffixChar` 를 아예 쓰지 않으므로(156513948 각주 5개 실측),
    // 이름을 바꿔 내보내면 표시가 `*` 에서 `*)` 로 바뀐다.
    let deco_name = if attrs.decoration_is_user_char {
        "userChar"
    } else {
        "suffixChar"
    };
    storage
        .push_str(
            &mut out,
            &xml_value(
                storage,
                format_args!(
                    r#" {}="{}" instId="{}""#,
                    deco_name, attrs.suffix_char, attrs.inst_id
                ),
            )?,
        )
        .map_err(xml_error)?;
    Ok(out)
}

/// [#2726] 너비 기준 → HWPX `widthRelTo`. 파서 `parse_size_criterion(_, true)` 의 정확한 역.
///
/// `table.rs:147` 이 `#2697` 로 정립한 관례와 **동일 의미**다. 해당 사본이 private 이라
/// 이 모듈에서 도달할 수 없어 부득이 복제했다. 공용 위치 1벌 통합은 잔여다(이슈 7장).
fn size_criterion_str(c: SizeCriterion) -> &'static str {
    match c {
        SizeCriterion::Paper => "PAPER",
        SizeCriterion::Page => "PAGE",
        SizeCriterion::Column => "COLUMN",
        SizeCriterion::Para => "PARA",
        SizeCriterion::Absolute => "ABSOLUTE",
    }
}

/// [#2726] 높이 기준 → HWPX `heightRelTo`. 파서는 높이를
/// `parse_size_criterion(_, allow_column_para = false)` 로 읽으므로(`parser/hwpx/section.rs:1860`)
/// 치역이 `{PAPER, PAGE, ABSOLUTE}` 3값뿐이다. 방출도 같은 3값으로 접어야 왕복이 정확한
/// 역이 된다 — `COLUMN`/`PARA` 를 내면 되읽기에서 `Absolute` 로 접혀 비-멱등이 된다.
/// HWP5 측 `height_criterion_to_bits`(`common_obj_attr_writer.rs:160`)도 동일하게 접는다.
fn height_criterion_str(c: SizeCriterion) -> &'static str {
    match c {
        SizeCriterion::Paper => "PAPER",
        SizeCriterion::Page => "PAGE",
        SizeCriterion::Column | SizeCriterion::Para | SizeCriterion::Absolute => "ABSOLUTE",
    }
}

fn render_note_sublist(
    tag: &str,
    attrs: NoteAttrs,
    paragraphs: &[Paragraph],
    ctx: &mut SerializeContext,
) -> String {
    render_note_sublist_with_storage(tag, attrs, paragraphs, ctx, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_note_sublist_with_storage<S: crate::storage::Storage>(
    tag: &str,
    attrs: NoteAttrs,
    paragraphs: &[Paragraph],
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = xml_value(
        storage,
        format_args!(
            r#"<hp:ctrl><hp:{tag}{attrs}><hp:subList id="" textDirection="HORIZONTAL" lineWrap="BREAK" vertAlign="TOP" linkListIDRef="0" linkListNextIDRef="0" textWidth="0" textHeight="0" hasTextRef="0" hasNumRef="0">"#,
            tag = tag,
            attrs = render_note_attrs_with_storage(&attrs, storage)?,
        ),
    )?;
    let mut vert_cursor: u32 = 0;
    for p in paragraphs.iter() {
        let (runs, linesegs, advance) =
            render_paragraph_parts_with_storage(p, vert_cursor, ctx, storage)?;
        vert_cursor = advance;
        let pid = ctx.next_para_id();
        let sid = ctx.effective_style_id(p.style_id);
        storage
            .push_str(
                &mut out,
                &render_hp_p_open_with_storage(p, pid, sid, storage)?,
            )
            .map_err(xml_error)?;
        storage.push_str(&mut out, &runs).map_err(xml_error)?;
        storage.push_str(&mut out, &linesegs).map_err(xml_error)?;
        storage.push_str(&mut out, "</hp:p>").map_err(xml_error)?;
    }
    storage
        .push_str(
            &mut out,
            &xml_value(
                storage,
                format_args!("</hp:subList></hp:{tag}></hp:ctrl>", tag = tag),
            )?,
        )
        .map_err(xml_error)?;
    Ok(out)
}

/// 숨은 설명(`<hp:hiddenComment>`) — 스키마상 `subList` 하나만 갖는다
/// (ParaList XML schema.xml:217-224). 각주와 달리 속성이 없다.
fn render_hidden_comment(
    hc: &crate::model::control::HiddenComment,
    ctx: &mut SerializeContext,
) -> String {
    render_hidden_comment_with_storage(hc, ctx, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_hidden_comment_with_storage<S: crate::storage::Storage>(
    hc: &crate::model::control::HiddenComment,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = String::from("<hp:ctrl><hp:hiddenComment>");
    storage
        .push_str(&mut out, &render_sub_list_open_with_storage(None, storage)?)
        .map_err(xml_error)?;
    let mut vert_cursor: u32 = 0;
    for p in hc.paragraphs.iter() {
        ctx.para_shape_ids.reference(p.para_shape_id);
        let sid = ctx.effective_style_id(p.style_id);
        ctx.style_ids.reference(sid as u16);
        let (runs, linesegs, advance) =
            render_paragraph_parts_with_storage(p, vert_cursor, ctx, storage)?;
        vert_cursor = advance;
        let pid = ctx.next_para_id();
        storage
            .push_str(
                &mut out,
                &render_hp_p_open_with_storage(p, pid, sid, storage)?,
            )
            .map_err(xml_error)?;
        storage.push_str(&mut out, &runs).map_err(xml_error)?;
        storage.push_str(&mut out, &linesegs).map_err(xml_error)?;
        storage.push_str(&mut out, "</hp:p>").map_err(xml_error)?;
    }
    storage
        .push_str(&mut out, "</hp:subList></hp:hiddenComment></hp:ctrl>")
        .map_err(xml_error)?;
    Ok(out)
}

fn render_footnote(note: &Footnote, ctx: &mut SerializeContext) -> String {
    render_footnote_with_storage(note, ctx, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_footnote_with_storage<S: crate::storage::Storage>(
    note: &Footnote,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#2716] IR 이 보존한 장식 문자/번호 모양/고유 ID 를 모두 방출한다. 종전엔 number 만
    // 써서 저장 왕복마다 앞 장식('문')이 사라지고 뒤 장식이 ')' 로 변조됐다.
    render_note_sublist_with_storage(
        "footNote",
        NoteAttrs {
            number: note.number,
            prefix_char: note.before_decoration_letter,
            suffix_char: note.after_decoration_letter,
            decoration_is_user_char: note.decoration_is_user_char,
            number_shape: note.number_shape,
            inst_id: note.instance_id,
        },
        &note.paragraphs,
        ctx,
        storage,
    )
}

fn render_endnote(note: &Endnote, ctx: &mut SerializeContext) -> String {
    render_endnote_with_storage(note, ctx, &crate::storage::Unbounded)
        .expect("unbounded object XML")
}

fn render_endnote_with_storage<S: crate::storage::Storage>(
    note: &Endnote,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // [#2716] Footnote 와 동일 계약.
    render_note_sublist_with_storage(
        "endNote",
        NoteAttrs {
            number: note.number,
            prefix_char: note.before_decoration_letter,
            suffix_char: note.after_decoration_letter,
            decoration_is_user_char: note.decoration_is_user_char,
            number_shape: note.number_shape,
            inst_id: note.instance_id,
        },
        &note.paragraphs,
        ctx,
        storage,
    )
}

fn render_equation(eq: &Equation) -> String {
    render_equation_with_storage(eq, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn render_equation_with_storage<S: crate::storage::Storage>(
    eq: &Equation,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let c = &eq.common;
    // 한컴 저장본이 보존하는 크기 보호를 내보내기에서도 유지한다.
    // false는 기존과 같이 생략한다.
    let size_protect = if c.size_protect {
        r#" protect="1""#
    } else {
        ""
    };
    let id = xml_value(storage, c.instance_id)?;
    let z_order = xml_value(storage, c.z_order)?;
    let version = xml_escape_with_storage(&eq.version_info, storage)?;
    let baseline = xml_value(storage, eq.baseline)?;
    let text_color = color_ref_to_hwpx_with_storage(eq.color, storage)?;
    let base_unit = xml_value(storage, eq.font_size)?;
    let font = xml_escape_with_storage(&eq.font_name, storage)?;
    let script = xml_escape_with_storage(&eq.script, storage)?;
    let width = xml_value(storage, c.width)?;
    let height = xml_value(storage, c.height)?;
    let treat = if c.treat_as_char { "1" } else { "0" };
    let flow_with_text = if c.flow_with_text { "1" } else { "0" };
    let vert_offset = xml_value(storage, c.vertical_offset)?;
    let horz_offset = xml_value(storage, c.horizontal_offset)?;
    let margin_left = xml_value(storage, c.margin.left)?;
    let margin_right = xml_value(storage, c.margin.right)?;
    let margin_top = xml_value(storage, c.margin.top)?;
    let margin_bottom = xml_value(storage, c.margin.bottom)?;

    // 설명 (#1392) — outMargin 직후, 빈 description 은 미방출
    let shape_comment = if c.description.is_empty() {
        String::new()
    } else {
        xml_value(
            storage,
            format_args!(
                "<hp:shapeComment>{}</hp:shapeComment>",
                xml_escape_with_storage(&c.description, storage)?
            ),
        )?
    };

    // [#1594] holdAnchorAndSO 는 IR(prevent_page_break)을 보존(종전 "0" 하드코딩 제거).
    let hold = if c.prevent_page_break != 0 { "1" } else { "0" };

    // [#2727] lineMode(수식이 차지하는 범위) 를 EQEDIT attribute bit0 에서 방출한다.
    // 종전엔 속성 자체를 내보내지 않아 LINE 설정이 왕복마다 CHAR 로 되돌아갔다.
    // 한컴 저장본과 동일하게 baseUnit 과 font 사이에 위치시킨다.
    let line_mode = if eq.attr & EQUATION_LINE_MODE_BIT != 0 {
        "LINE"
    } else {
        "CHAR"
    };

    // 개체 공통 속성을 그대로 보존한다. 원본 수식의 줄간격 참여가 저장에서 풀리면
    // 같은 선언 높이·스크립트여도 한컴의 후속 문단 원점이 달라진다.
    let affect_line_spacing = if c.affect_line_spacing { "1" } else { "0" };

    // [#2840] 개체 잠금(lock) — 종전 하드코딩 "0" 제거, IR(common.locked) 값을 방출.
    let lock = if c.locked { "1" } else { "0" };
    let drop_cap = super::shape::drop_cap_style_str(c.drop_cap_style);

    // [#2778] 크기 기준(widthRelTo/heightRelTo) — 종전 "ABSOLUTE" 리터럴은 파서
    // (parse_object_layout_child:3023)가 IR 에 적재한 단/열/쪽 상대 기준을 저장에서만
    // 버렸다. #2697(표)·#2712(그림/도형)·#2726(공용 도형)과 동형이다. 높이는 파서가
    // `parse_size_criterion(_, false)` 로 읽어 치역이 3값이므로 같은 접기 함수를 쓴다.
    let width_rel_to = size_criterion_str(c.width_criterion);
    let height_rel_to = height_criterion_str(c.height_criterion);

    // [#2782] 개체 겹침 허용(allowOverlap) — 종전 하드코딩 "0" 제거, IR 값을 방출.
    // 같은 요소의 treatAsChar·flowWithText 는 이미 IR 기반이었다.
    let allow_overlap = if c.allow_overlap { "1" } else { "0" };
    xml_value(
        storage,
        format_args!(
            r#"<hp:equation id="{id}" zOrder="{z_order}" numberingType="EQUATION" textWrap="{}" textFlow="{}" lock="{lock}" dropcapstyle="{drop_cap}" version="{version}" baseLine="{baseline}" textColor="{text_color}" baseUnit="{base_unit}" lineMode="{line_mode}" font="{font}"><hp:script>{script}</hp:script><hp:sz width="{width}" widthRelTo="{width_rel_to}" height="{height}" heightRelTo="{height_rel_to}"{size_protect}/><hp:pos treatAsChar="{treat}" affectLSpacing="{affect_line_spacing}" flowWithText="{flow_with_text}" allowOverlap="{allow_overlap}" holdAnchorAndSO="{hold}" vertRelTo="{}" horzRelTo="{}" vertAlign="{}" horzAlign="{}" vertOffset="{vert_offset}" horzOffset="{horz_offset}"/><hp:outMargin left="{margin_left}" right="{margin_right}" top="{margin_top}" bottom="{margin_bottom}"/>{shape_comment}</hp:equation>"#,
            text_wrap_to_hwpx(c.text_wrap),
            text_flow_to_hwpx(c.text_flow),
            vert_rel_to_hwpx(c.vert_rel_to),
            horz_rel_to_hwpx(c.horz_rel_to),
            vert_align_to_hwpx(c.vert_align),
            horz_align_to_hwpx(c.horz_align),
        ),
    )
}

fn char_utf16_width(c: char) -> u32 {
    if c == '\t' {
        8
    } else if (c as u32) > 0xFFFF {
        2
    } else {
        1
    }
}

fn color_ref_to_hwpx(color: u32) -> String {
    color_ref_to_hwpx_with_storage(color, &crate::storage::Unbounded).expect("unbounded object XML")
}

fn color_ref_to_hwpx_with_storage<S: crate::storage::Storage>(
    color: u32,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    if color == 0xFFFFFFFF {
        return xml_value(storage, "none");
    }

    let a = (color >> 24) & 0xFF;
    let r = color & 0xFF;
    let g = (color >> 8) & 0xFF;
    let b = (color >> 16) & 0xFF;
    Ok(if a == 0 {
        xml_value(storage, format_args!("#{r:02X}{g:02X}{b:02X}"))?
    } else {
        xml_value(storage, format_args!("#{a:02X}{r:02X}{g:02X}{b:02X}"))?
    })
}

fn text_wrap_to_hwpx(wrap: TextWrap) -> &'static str {
    match wrap {
        TextWrap::Square => "SQUARE",
        TextWrap::Tight => "TIGHT",
        TextWrap::Through => "THROUGH",
        TextWrap::TopAndBottom => "TOP_AND_BOTTOM",
        TextWrap::BehindText => "BEHIND_TEXT",
        TextWrap::InFrontOfText => "IN_FRONT_OF_TEXT",
    }
}

fn text_flow_to_hwpx(flow: crate::model::shape::TextFlow) -> &'static str {
    use crate::model::shape::TextFlow;
    match flow {
        TextFlow::BothSides => "BOTH_SIDES",
        TextFlow::LeftOnly => "LEFT_ONLY",
        TextFlow::RightOnly => "RIGHT_ONLY",
        TextFlow::LargestOnly => "LARGEST_ONLY",
    }
}

fn vert_rel_to_hwpx(rel: VertRelTo) -> &'static str {
    match rel {
        VertRelTo::Paper => "PAPER",
        VertRelTo::Page => "PAGE",
        VertRelTo::Para => "PARA",
    }
}

fn horz_rel_to_hwpx(rel: HorzRelTo) -> &'static str {
    match rel {
        HorzRelTo::Paper => "PAPER",
        HorzRelTo::Page => "PAGE",
        HorzRelTo::Column => "COLUMN",
        HorzRelTo::Para => "PARA",
    }
}

fn vert_align_to_hwpx(align: VertAlign) -> &'static str {
    match align {
        VertAlign::Top => "TOP",
        VertAlign::Center => "CENTER",
        VertAlign::Bottom => "BOTTOM",
        VertAlign::Inside => "INSIDE",
        VertAlign::Outside => "OUTSIDE",
    }
}

fn horz_align_to_hwpx(align: HorzAlign) -> &'static str {
    match align {
        HorzAlign::Left => "LEFT",
        HorzAlign::Center => "CENTER",
        HorzAlign::Right => "RIGHT",
        HorzAlign::Inside => "INSIDE",
        HorzAlign::Outside => "OUTSIDE",
    }
}

/// IR의 `line_segs` 를 그대로 XML로 직렬화 (9개 필드 전부 IR 값 사용).
///
/// rhwp 는 자신의 문서에서 비표준 lineseg 를 **새로 생산하지 않는다**.
/// 원본 한컴 파일의 lineseg 값이 파서에 의해 `Paragraph.line_segs` 에 담겼다면,
/// 저장 시 그 값을 훼손 없이 보존한다.
/// [#5847] `vpos_override` 가 있으면 각 줄의 `vertpos` 를 그 값(원본 쪽-상대
/// 좌표 스냅샷)으로 낸다 — reflow 재계산이 덮어쓴 IR 값 대신.
fn render_lineseg_array_from_ir(segs: &[LineSeg], vpos_override: Option<&[i32]>) -> String {
    render_lineseg_array_from_ir_with_storage(segs, vpos_override, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn render_lineseg_array_from_ir_with_storage<S: crate::storage::Storage>(
    segs: &[LineSeg],
    vpos_override: Option<&[i32]>,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let mut out = String::new();
    for (i, seg) in segs.iter().enumerate() {
        let vpos = vpos_override
            .and_then(|v| v.get(i).copied())
            .unwrap_or(seg.vertical_pos);
        storage
            .push_str(
                &mut out,
                &render_one_lineseg_with_storage(seg, seg.text_start, vpos, storage)?,
            )
            .map_err(xml_error)?;
    }
    Ok(out)
}

/// `<hp:lineseg>` 한 줄 — `textpos` 만 호출부가 정하고 나머지 8필드는 IR 값 그대로.
fn render_one_lineseg(seg: &LineSeg, text_start: u32, vertical_pos: i32) -> String {
    render_one_lineseg_with_storage(seg, text_start, vertical_pos, &crate::storage::Unbounded)
        .expect("unbounded run XML")
}

fn render_one_lineseg_with_storage<S: crate::storage::Storage>(
    seg: &LineSeg,
    text_start: u32,
    vertical_pos: i32,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    xml_value(
        storage,
        format_args!(
            r#"<hp:lineseg textpos="{}" vertpos="{}" vertsize="{}" textheight="{}" baseline="{}" spacing="{}" horzpos="{}" horzsize="{}" flags="{}"/>"#,
            text_start,
            vertical_pos,
            seg.line_height,
            seg.text_height,
            seg.baseline_distance,
            seg.line_spacing,
            seg.column_start,
            seg.segment_width,
            seg.tag,
        ),
    )
}

/// IR 기반 다음 문단의 vert_start 계산 — 마지막 lineseg 의 vpos + lh 사용.
/// [#5847] `vpos_override` 는 방출 vertpos 와 커서를 일치시키기 위한 원본 스냅샷.
fn next_vert_cursor_from_ir(
    segs: &[LineSeg],
    vpos_override: Option<&[i32]>,
    vert_start: u32,
) -> u32 {
    if segs.len() == 1 && segs[0].is_missing_lineseg_placeholder() {
        return vert_start;
    }

    if let Some(last) = segs.last() {
        let last_vpos = vpos_override
            .and_then(|v| v.last().copied())
            .unwrap_or(last.vertical_pos);
        // vertical_pos 는 섹션 시작 기준 절대값일 수도, 문단 기준 상대값일 수도 있음.
        // 현재 rhwp 는 섹션 절대값이므로 그대로 + lh 로 다음 커서 산출.
        let next = (last_vpos as i64) + (last.line_height.max(0) as i64);
        if next > vert_start as i64 {
            next as u32
        } else {
            vert_start + VERT_STEP
        }
    } else {
        vert_start + VERT_STEP
    }
}

fn flush_buf(t_xml: &mut String, buf: &mut String) {
    flush_buf_with_storage(t_xml, buf, &crate::storage::Unbounded).expect("unbounded run XML")
}

fn flush_buf_with_storage<S: crate::storage::Storage>(
    t_xml: &mut String,
    buf: &mut String,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    if !buf.is_empty() {
        storage
            .push_str(t_xml, &xml_escape_with_storage(buf, storage)?)
            .map_err(xml_error)?;
        buf.clear();
    }

    Ok(())
}

/// 템플릿의 첫 `<hp:linesegarray>...</hp:linesegarray>` **요소 전체**를
/// `new_element` 로 치환한다. `new_element` 가 빈 문자열이면 요소가 제거된다
/// (#1380 — line_segs 빈 문단의 linesegarray 방출 생략).
fn replace_first_linesegs(xml: &str, new_element: &str) -> String {
    replace_first_linesegs_with_storage(xml, new_element, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_first_linesegs_with_storage<S: crate::storage::Storage>(
    xml: &str,
    new_element: &str,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let open = xml
        .find(LINESEG_SLOT_OPEN)
        .expect("template has linesegarray");
    let close_rel = xml[open..]
        .find(LINESEG_SLOT_CLOSE)
        .expect("template has closing linesegarray");
    let elem_end = open + close_rel + LINESEG_SLOT_CLOSE.len();
    xml_value(
        storage,
        format_args!("{}{}{}", &xml[..open], new_element, &xml[elem_end..]),
    )
}

/// [#1166] 템플릿 pagePr 의 고정 용지 속성(landscape/width/height)을 IR page_def
/// 값으로 치환한다. 종전엔 템플릿 하드코딩값(landscape="WIDELY" width=59528
/// height=84186)이 그대로 출력되어 HWPX 저장 시 가로/세로 + 용지 크기가 손실됐다.
///
/// OWPML landscape: WIDELY=세로(landscape=false), NARROWLY=가로(landscape=true).
/// width/height 는 짧은변/긴변 그대로 (HWP 바이너리 동일 규약).
///
/// [#1388] 확장: gutterType(제본 방향) + `<hp:margin>` 여백 7필드를 IR 값으로 치환.
/// 종전엔 템플릿 고정 여백(left/right=8504 등)이 그대로 출력되어 원본 여백이
/// 변형됐다 (samples/hwpx 전수 51/74 섹션 영향, 본문 +56.7px 시프트·페이지 수 변동).
/// gutterType ↔ binding 매핑은 parser/hwpx/section.rs `parse_page_pr` 의 역매핑.
fn replace_page_pr(xml: &str, page_def: &crate::model::page::PageDef) -> String {
    replace_page_pr_with_storage(xml, page_def, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_page_pr_with_storage<S: crate::storage::Storage>(
    xml: &str,
    page_def: &crate::model::page::PageDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    // 템플릿의 pagePr 여는 태그(고정 문자열) → IR 기반으로 교체.
    const TEMPLATE_PAGE_PR: &str =
        r#"<hp:pagePr landscape="WIDELY" width="59528" height="84186" gutterType="LEFT_ONLY">"#;
    let landscape = if page_def.landscape {
        "NARROWLY"
    } else {
        "WIDELY"
    };
    let gutter_type = match page_def.binding {
        crate::model::page::BindingMethod::SingleSided => "LEFT_ONLY",
        crate::model::page::BindingMethod::DuplexSided => "LEFT_RIGHT",
        crate::model::page::BindingMethod::TopFlip => "TOP_BOTTOM",
    };
    let new_page_pr = xml_value(
        storage,
        format_args!(
            r#"<hp:pagePr landscape="{}" width="{}" height="{}" gutterType="{}">"#,
            landscape, page_def.width, page_def.height, gutter_type,
        ),
    )?;
    let out = if xml.contains(TEMPLATE_PAGE_PR) {
        xml_replacen(xml, TEMPLATE_PAGE_PR, &new_page_pr, 1, storage)?
    } else {
        // 템플릿이 변경됐거나 이미 치환된 경우 — 원본 유지(회귀 방지).
        xml_value(storage, xml)?
    };

    // 템플릿의 hp:margin(고정 문자열) → IR 여백 7필드로 교체 (#1388).
    // write_section 은 콘텐츠 삽입 전에 호출하므로 템플릿 내 유일 1회 등장이 보장된다.
    const TEMPLATE_PAGE_MARGIN: &str = r#"<hp:margin header="4252" footer="4252" gutter="0" left="8504" right="8504" top="5668" bottom="4252"/>"#;
    let new_margin = xml_value(
        storage,
        format_args!(
            r#"<hp:margin header="{}" footer="{}" gutter="{}" left="{}" right="{}" top="{}" bottom="{}"/>"#,
            page_def.margin_header,
            page_def.margin_footer,
            page_def.margin_gutter,
            page_def.margin_left,
            page_def.margin_right,
            page_def.margin_top,
            page_def.margin_bottom,
        ),
    )?;
    Ok(if out.contains(TEMPLATE_PAGE_MARGIN) {
        xml_replacen(out, TEMPLATE_PAGE_MARGIN, &new_margin, 1, storage)?
    } else {
        // 템플릿이 변경됐거나 이미 치환된 경우 — 원본 유지(회귀 방지).
        out
    })
}

/// 템플릿의 3개 `pageBorderFill`(BOTH/EVEN/ODD, 하드코딩 borderFillIDRef="1") 을 IR 값으로
/// 치환한다. 누락 시 문서의 실제 쪽 테두리가 소실된다. 파서는 `type` 속성 값을 기준으로
/// `page_border_fill`(BOTH) / `extra_page_border_fills`(EVEN/ODD) 슬롯을 배정한다(#2885).
///
/// `extra_page_border_fills` 에 실제 EVEN/ODD 데이터가 없는 경우(절대다수 — 실제 한컴
/// 문서는 `pageBorderFill` 을 1개(BOTH)만 갖는다) `page_border_fill` 값을 그대로 복제해
/// EVEN/ODD 자리를 채우면, 원본에 없던 요소가 왕복 후 생겨나고 그 값(=BOTH 복제본)이
/// 재파싱 시 `extra_page_border_fills` 로 다시 흡수되어 존재하지 않던 필드가 왕복마다
/// 늘어난다(#2896 CI 발견 — IR 필드 스윕 baseline 발산). 대신 그 자리는 템플릿에서
/// 통째로 제거해 원본 문서 구조(단일 BOTH)를 보존한다.
fn replace_page_border_fill(xml: &str, sec_def: &crate::model::document::SectionDef) -> String {
    replace_page_border_fill_with_storage(xml, sec_def, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn replace_page_border_fill_with_storage<S: crate::storage::Storage>(
    xml: &str,
    sec_def: &crate::model::document::SectionDef,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let entries: [(&str, Option<&crate::model::page::PageBorderFill>); 3] = [
        ("BOTH", Some(&sec_def.page_border_fill)),
        ("EVEN", sec_def.extra_page_border_fills.first()),
        ("ODD", sec_def.extra_page_border_fills.get(1)),
    ];
    let mut out = xml_value(storage, xml)?;
    for (ty, pbf) in entries {
        // 템플릿 고정 문자열 (empty_section0.xml 와 정확히 일치해야 함).
        let template = xml_value(
            storage,
            format_args!(
                r#"<hp:pageBorderFill type="{ty}" borderFillIDRef="1" textBorder="PAPER" headerInside="0" footerInside="0" fillArea="PAPER"><hp:offset left="1417" right="1417" top="1417" bottom="1417"/></hp:pageBorderFill>"#
            ),
        )?;
        if out.contains(&template) {
            let replacement = match pbf {
                Some(pbf) => render_page_border_fill_with_storage(ty, pbf, storage)?,
                // IR 에 이 슬롯의 실데이터가 없음 — BOTH 를 복제해 채우는 대신
                // 요소 자체를 제거한다(원본 없던 EVEN/ODD 요소를 만들어내지 않음).
                None => String::new(),
            };
            out = xml_replacen(out, &template, &replacement, 1, storage)?;
        }
        // 미일치 시 원본 유지(회귀 방지) — replace_page_pr 패턴과 동형.
    }
    Ok(out)
}

/// 단일 `pageBorderFill` 요소를 IR 에서 재구성한다. attr 비트 → textBorder/fillArea/
/// headerInside/footerInside (parser `page_border_fill_attr` 의 역).
fn render_page_border_fill(ty: &str, pbf: &crate::model::page::PageBorderFill) -> String {
    render_page_border_fill_with_storage(ty, pbf, &crate::storage::Unbounded)
        .expect("unbounded section XML")
}

fn render_page_border_fill_with_storage<S: crate::storage::Storage>(
    ty: &str,
    pbf: &crate::model::page::PageBorderFill,
    storage: &S,
) -> Result<String, SerializeError>
where
    S::Error: std::fmt::Display,
{
    let text_border = if pbf.attr & 0x0000_0001 != 0 {
        "PAPER"
    } else {
        "CONTENT"
    };
    let fill_area = if pbf.attr & 0x0000_0008 != 0 {
        "PAGE"
    } else if pbf.attr & 0x0000_0010 != 0 {
        "BORDER"
    } else {
        "PAPER"
    };
    let header_inside = if pbf.attr & 0x0000_0002 != 0 {
        "1"
    } else {
        "0"
    };
    let footer_inside = if pbf.attr & 0x0000_0004 != 0 {
        "1"
    } else {
        "0"
    };
    xml_value(
        storage,
        format_args!(
            r#"<hp:pageBorderFill type="{ty}" borderFillIDRef="{}" textBorder="{}" headerInside="{}" footerInside="{}" fillArea="{}"><hp:offset left="{}" right="{}" top="{}" bottom="{}"/></hp:pageBorderFill>"#,
            pbf.border_fill_id,
            text_border,
            header_inside,
            footer_inside,
            fill_area,
            pbf.spacing_left,
            pbf.spacing_right,
            pbf.spacing_top,
            pbf.spacing_bottom,
        ),
    )
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::paragraph::{CharShapeRef, Paragraph};

    /// [#XXXX] `<hp:pageNum formatType="...">`의 원문자(circled digit) 값은 OWPML Core
    /// 스키마 NumberType1 표기인 "CIRCLED_DIGIT"이어야 한다. 종전엔 "CIRCLE_DIGIT"(D 없음)
    /// 오탈자로 방출돼 한컴이 값을 인식하지 못했다.
    #[test]
    fn page_num_circled_digit_format_reflects_spec_spelling() {
        use crate::model::control::PageNumberPos;
        let mut pn = PageNumberPos::default();
        pn.format = 1; // circled digit
        let xml = render_page_num(&pn);
        assert!(
            xml.contains(r#"formatType="CIRCLED_DIGIT""#),
            "pageNum formatType 이 스펙 철자(CIRCLED_DIGIT)여야 함: {xml}"
        );
        assert!(
            !xml.contains(r#"formatType="CIRCLE_DIGIT""#),
            "CIRCLE_DIGIT 오탈자 잔존 금지: {xml}"
        );
    }

    /// [#4895] 소프트 하이픈(U+00AD)은 `<hp:hyphen/>` 요소가 아니라 **리터럴 문자**로 나간다.
    ///
    /// #4776 이 요소로 바꿨다가 10k 전수에서 36경로가 깨졌다. 한글 2022 대조 실측(01628,
    /// 하이픈 표기만 교체): 요소 → 본문 2,477자(글자 소실) / 리터럴 → 2,478자로 원본과
    /// textSha 일치. 한컴 원본 hwpx 도 `<hp:t>` 안에 raw U+00AD 를 담는다.
    #[test]
    fn soft_hyphen_stays_literal_in_hp_t() {
        let mut cursor = InlineCursor::default();
        let xml = render_hp_t_content("축사로\u{00AD}한우", &[], &mut cursor);
        assert!(
            !xml.contains("<hp:hyphen/>") && !xml.contains("<hp:hypen/>"),
            "리터럴 출처 소프트 하이픈을 요소로 바꾸면 원본에 없던 표기가 생긴다: {xml}"
        );
        assert!(
            xml.contains('\u{00AD}'),
            "소프트 하이픈이 리터럴로 실려야 한다: {xml:?}"
        );
    }

    /// [#4895] 출처가 제어 표기(HWP5 control_mask 비트 24)인 문단만 `<hp:hyphen/>` 로
    /// 되돌린다 — 원본에 없던 글자를 만들지 않기 위해서다.
    #[test]
    fn soft_hyphen_from_control_origin_is_written_as_element() {
        let mut cursor = InlineCursor {
            soft_hyphen_as_element: true,
            ..Default::default()
        };
        let xml = render_hp_t_content("축사로\u{00AD}한우", &[], &mut cursor);
        // [#7993] 요소 이름은 한/글 표기 `hp:hypen` — `hp:hyphen` 은 한/글이 버린다.
        assert!(
            xml.contains("<hp:hypen/>") && !xml.contains("<hp:hyphen/>"),
            "제어 표기 출처는 한/글 요소 이름 `hp:hypen` 으로 보존되어야 한다: {xml}"
        );
        assert!(
            !xml.contains('\u{00AD}'),
            "요소로 내렸으면 리터럴은 남지 않는다: {xml:?}"
        );
    }

    // [#5174] 묶음 빈칸 표기 보존 계약(`nb_space_as_element`)은 실제 문서 왕복으로
    // `tests/cases/issue_5174_nbspace_representation.rs` 가 지킨다. 제품 소스의
    // 단위시험을 늘리지 않으려고 여기 두지 않았다 — `render_hp_t_content` 가
    // `pub(crate)` 라 통합 테스트는 저장·재로드 축으로 같은 계약을 검사한다.

    /// 쪽 번호 시작 쪽 컨트롤(`pgct`)은 `<hp:ctrl><hp:pageNumCtrl>` 로 나가야 한다.
    ///
    /// 구역 속성의 `pageStartsOn`(`<hp:secPr>`)과는 다른 자리다 — 이쪽은 문단 위
    /// 8유닛 슬롯을 차지하는 컨트롤이라, 방출하지 않으면 축이 그만큼 짧아진다.
    #[test]
    fn page_num_ctrl_is_emitted_as_a_ctrl_element() {
        let mut ctx = SerializeContext::default();
        for (want, text) in [
            (PageStartsOn::Both, "BOTH"),
            (PageStartsOn::Even, "EVEN"),
            (PageStartsOn::Odd, "ODD"),
        ] {
            let mut out = String::new();
            render_control_slot(
                &mut out,
                &Control::PageNumCtrl(PageNumCtrl {
                    page_starts_on: want,
                }),
                &mut ctx,
            );
            assert_eq!(
                out,
                format!(r#"<hp:ctrl><hp:pageNumCtrl pageStartsOn="{text}"/></hp:ctrl>"#)
            );
        }
    }

    /// 제목 차례 표시는 `<hp:t>` 안 인라인 요소로 되살아나야 한다 — 스키마상
    /// `<hp:ctrl>` 이 아니라 `<hp:t>` 의 자식이다(ParaList XML schema.xml:238).
    #[test]
    fn title_mark_is_emitted_inside_hp_t() {
        let mut cursor = InlineCursor {
            title_marks: &[TitleMark {
                char_idx: 0,
                ignore: true,
            }],
            ..Default::default()
        };
        let xml = render_hp_t_content("가나", &[], &mut cursor);
        assert_eq!(xml, "<hp:t><hp:titleMark ignore=\"1\"/>가나</hp:t>");
    }

    /// `ignore="0"`(`Mign`)도 구별해 낸다 — 한글 2022 양방향 실측(06699).
    #[test]
    fn title_mark_ignore_off_round_trips() {
        let mut cursor = InlineCursor {
            title_marks: &[TitleMark {
                char_idx: 1,
                ignore: false,
            }],
            ..Default::default()
        };
        let xml = render_hp_t_content("가나", &[], &mut cursor);
        assert_eq!(xml, "<hp:t>가<hp:titleMark ignore=\"0\"/>나</hp:t>");
    }

    /// 표시가 주장하는 8유닛 슬롯을 슬롯 수에서 빼지 않으면 문단이 mismatch 경로로
    /// 떨어져 `<hp:linesegarray>` 가 통째로 빠진다 — F-절단군의 근인이다.
    #[test]
    fn title_mark_slot_is_not_counted_as_a_control_slot() {
        let mut para = Paragraph {
            text: "가나".to_string(),
            char_offsets: vec![8, 9],
            // 표시 8 + 글자 2 + 끝 마커 1
            char_count: 11,
            title_marks: vec![TitleMark {
                char_idx: 0,
                ignore: true,
            }],
            ..Default::default()
        };
        assert_eq!(
            inferred_control_slot_count(&para),
            0,
            "표시 슬롯은 controls[] 에 대응이 없으므로 차감돼야 한다"
        );

        para.title_marks.clear();
        assert_eq!(
            inferred_control_slot_count(&para),
            1,
            "표시를 모르면 같은 문단이 컨트롤 슬롯 1개를 주장한다(종전 동작)"
        );
    }

    #[test]
    fn equation_text_flow_reflects_ir() {
        use crate::model::control::Equation;
        use crate::model::shape::TextFlow;
        // 수식의 textFlow 가 IR(common.text_flow)에서 방출돼야 한다.
        // 종전엔 "BOTH_SIDES" 하드코딩으로 왕복 시 유실됐다(textWrap 은 이미 IR 구동).
        let mut eq = Equation::default();
        eq.common.text_flow = TextFlow::LeftOnly;
        let xml = render_equation(&eq);
        assert!(
            xml.contains(r#"textFlow="LEFT_ONLY""#),
            "수식 textFlow 이 IR 값이어야 함: {xml}"
        );
        assert!(
            !xml.contains(r#"textFlow="BOTH_SIDES""#),
            "BOTH_SIDES 하드코딩 잔존 금지"
        );
    }

    /// [Issue #2727] 수식의 lineMode(수식이 차지하는 범위)가 IR(EQEDIT attribute bit0)에서
    /// 방출돼야 한다. 종전엔 속성 자체를 내보내지 않아 LINE 설정이 왕복마다 CHAR 로 돌아갔다.
    /// 한컴 저장본은 값이 기본값(CHAR)이어도 예외 없이 baseUnit 과 font 사이에 기록한다.
    #[test]
    fn equation_line_mode_reflects_ir() {
        use crate::model::control::{Equation, EQUATION_LINE_MODE_BIT};

        let char_xml = render_equation(&Equation::default());
        assert!(
            char_xml.contains(r#"lineMode="CHAR""#),
            "기본값도 lineMode 속성을 방출해야 함(한컴 저장본 정합): {char_xml}"
        );

        let eq = Equation {
            attr: EQUATION_LINE_MODE_BIT,
            font_size: 1000,
            ..Default::default()
        };
        let line_xml = render_equation(&eq);
        assert!(
            line_xml.contains(r#"baseUnit="1000" lineMode="LINE" font="""#),
            "lineMode 는 IR 값으로, 한컴과 같은 baseUnit·font 사이 자리에 와야 함: {line_xml}"
        );
        assert!(
            !line_xml.contains(r#"lineMode="CHAR""#),
            "CHAR 하드코딩 잔존 금지"
        );
    }

    /// [Issue #2840] 수식의 lock(개체 잠금)이 IR(common.locked)에서 방출돼야 한다.
    /// 종전엔 파서가 lock 속성을 읽지 않아 하드코딩 "0"으로 왕복마다 잠금이 풀렸다.
    #[test]
    fn equation_lock_reflects_ir() {
        use crate::model::control::Equation;

        let mut eq = Equation::default();
        eq.common.locked = true;
        let xml = render_equation(&eq);
        assert!(
            xml.contains(r#"lock="1""#),
            "locked=true 면 lock=\"1\" 을 방출해야 함(하드코딩 \"0\" 잔존 금지): {xml}"
        );
    }

    /// [Issue #2778] 수식의 크기 기준(`hp:sz` widthRelTo/heightRelTo)이 IR
    /// (common.width_criterion/height_criterion)에서 방출돼야 한다. 종전엔 "ABSOLUTE"
    /// 하드코딩이라 단/열/쪽 상대 크기 기준이 왕복마다 소실됐다.
    #[test]
    fn equation_size_criterion_reflects_ir() {
        use crate::model::control::Equation;
        use crate::model::shape::SizeCriterion;

        let mut eq = Equation::default();
        eq.common.width_criterion = SizeCriterion::Column;
        eq.common.height_criterion = SizeCriterion::Page;
        let xml = render_equation(&eq);
        assert!(
            xml.contains(r#"widthRelTo="COLUMN""#),
            "수식 widthRelTo 이 IR 값이어야 함: {xml}"
        );
        assert!(
            xml.contains(r#"heightRelTo="PAGE""#),
            "수식 heightRelTo 이 IR 값이어야 함: {xml}"
        );

        // 파서는 높이를 `parse_size_criterion(_, allow_column_para = false)` 로 읽어
        // 치역이 {PAPER, PAGE, ABSOLUTE} 3값뿐이므로, 방출도 같은 3값으로 접어야 멱등이다.
        let mut folded = Equation::default();
        folded.common.height_criterion = SizeCriterion::Column;
        assert!(
            render_equation(&folded).contains(r#"heightRelTo="ABSOLUTE""#),
            "heightRelTo 는 COLUMN/PARA 를 ABSOLUTE 로 접어야 왕복이 멱등"
        );
    }

    /// [Issue #2782] 수식의 allowOverlap(개체 겹침 허용)이 IR(common.allow_overlap)에서
    /// 방출돼야 한다. 종전 하드코딩 "0" 은 겹침 허용 설정을 왕복마다 껐다.
    #[test]
    fn equation_allow_overlap_reflects_ir() {
        use crate::model::control::Equation;

        let mut eq = Equation::default();
        eq.common.allow_overlap = true;
        let xml = render_equation(&eq);
        assert!(
            xml.contains(r#"allowOverlap="1""#),
            "allow_overlap=true 면 allowOverlap=\"1\" 을 방출해야 함: {xml}"
        );
        assert!(
            render_equation(&Equation::default()).contains(r#"allowOverlap="0""#),
            "기본값(false)은 종전대로 allowOverlap=\"0\" 이어야 함(회귀 방지)"
        );
    }

    /// [Issue #3543] 수식(`hp:equation`)은 스키마 비허용 `instid` 속성을 방출하지
    /// 않아야 한다. instid 는 도형 컴포넌트 공통(KS X 6101:2024 표 209) 소관이고
    /// equation 요소 정의(표 207·샘플 114)에는 없다 — 한컴 저장본도 수식에는
    /// 방출하지 않는다. 파서는 수식의 instid 를 버리므로 제거해도 왕복 불변.
    #[test]
    fn equation_omits_instid() {
        use crate::model::control::Equation;

        let xml = render_equation(&Equation::default());
        assert!(
            !xml.contains("instid"),
            "수식은 스키마 비허용 instid 를 방출하면 안 됨(KS X 6101 표 207): {xml}"
        );
        assert!(xml.contains(r#" id=""#), "id 속성은 유지돼야 함: {xml}");
    }

    /// [Issue #2790] legacy 공용 도형 경로(ellipse/arc/polygon/curve/chart/ole)의 textFlow
    /// 가 IR(common.text_flow)에서 방출돼야 한다. 종전 "BOTH_SIDES" 하드코딩으로 한쪽
    /// 배치(LEFT_ONLY 등) 설정이 왕복마다 소실됐다.
    #[test]
    fn common_shape_text_flow_reflects_ir() {
        use crate::model::shape::{CommonObjAttr, TextFlow};

        let mut c = CommonObjAttr::default();
        c.text_flow = TextFlow::LargestOnly;
        let mut ctx = SerializeContext::default();
        let xml = render_common_shape_xml("ellipse", &c, &None, None, &[], "", "", &mut ctx);
        assert!(
            xml.contains(r#"textFlow="LARGEST_ONLY""#),
            "공용 도형 textFlow 이 IR 값이어야 함: {xml}"
        );
        assert!(
            !xml.contains(r#"textFlow="BOTH_SIDES""#),
            "BOTH_SIDES 하드코딩 잔존 금지"
        );

        // 기본값(BothSides)은 종전 출력과 동일해야 한다(회귀 방지).
        let default_xml = render_common_shape_xml(
            "ellipse",
            &CommonObjAttr::default(),
            &None,
            None,
            &[],
            "",
            "",
            &mut ctx,
        );
        assert!(
            default_xml.contains(r#"textFlow="BOTH_SIDES""#),
            "기본값은 BOTH_SIDES 를 유지해야 함: {default_xml}"
        );
    }

    /// [Issue #1944] legacy 공용 도형 경로(polygon/ellipse/arc/curve)가 도형 내
    /// 글상자(drawText) 문단을 방출해야 한다 — 종전 누락으로 도형 안 텍스트 소실.
    #[test]
    fn common_shape_emits_draw_text_for_legacy_shapes() {
        use crate::model::shape::{CommonObjAttr, DrawingObjAttr, TextBox};

        let mut para = Paragraph::default();
        para.text = "마름모라벨".to_string();

        let drawing = DrawingObjAttr {
            text_box: Some(TextBox {
                paragraphs: vec![para],
                ..Default::default()
            }),
            ..Default::default()
        };
        let c = CommonObjAttr::default();
        let mut ctx = SerializeContext::default();

        let xml =
            render_common_shape_xml("polygon", &c, &None, Some(&drawing), &[], "", "", &mut ctx);
        assert!(
            xml.contains("<hp:drawText"),
            "polygon 도형이 drawText 를 방출해야 함: {xml}"
        );
        assert!(
            xml.contains("마름모라벨"),
            "글상자 문단 텍스트가 보존되어야 함"
        );
        // 빈 글상자는 미방출 (rect 경로와 동일 계약).
        let empty = DrawingObjAttr {
            text_box: Some(TextBox::default()),
            ..Default::default()
        };
        let xml_empty =
            render_common_shape_xml("polygon", &c, &None, Some(&empty), &[], "", "", &mut ctx);
        assert!(
            !xml_empty.contains("<hp:drawText"),
            "빈 글상자는 drawText 를 방출하지 않아야 함"
        );
    }

    /// [#2726] 공용 도형 경로(ellipse/arc/polygon/curve/chart)의 `hp:sz` 가 IR 의
    /// 크기 기준·크기 보호를 보존해야 한다. 종전엔 `widthRelTo`/`heightRelTo` 가
    /// `"ABSOLUTE"` 리터럴이고 `protect` 는 아예 미방출이었다.
    #[test]
    fn issue2726_common_shape_sz_preserves_criteria_and_protect() {
        use crate::model::shape::{CommonObjAttr, DrawingObjAttr};

        let c = CommonObjAttr {
            width: 4000,
            height: 3000,
            width_criterion: SizeCriterion::Column,
            height_criterion: SizeCriterion::Page,
            size_protect: true,
            ..Default::default()
        };
        let drawing = DrawingObjAttr::default();
        let mut ctx = SerializeContext::default();

        for tag in ["ellipse", "arc", "polygon", "curve", "chart"] {
            let xml =
                render_common_shape_xml(tag, &c, &None, Some(&drawing), &[], "", "", &mut ctx);
            assert!(
                xml.contains(r#"widthRelTo="COLUMN""#),
                "{tag}: 너비 기준 COLUMN 이 보존되어야 함: {xml}"
            );
            assert!(
                xml.contains(r#"heightRelTo="PAGE""#),
                "{tag}: 높이 기준 PAGE 가 보존되어야 함: {xml}"
            );
            assert!(
                xml.contains(r#"protect="1""#),
                "{tag}: 크기 보호가 보존되어야 함: {xml}"
            );
        }
    }

    /// [#2726] `protect` 는 값이 0 이어도 **속성 자체가** 방출되어야 한다.
    /// `samples/hwpx` 실제 한글 파일 60개의 `hp:sz` 1583개가 **전부** `protect` 를 갖는다
    /// (1583/1583). 종전 미방출은 그중 `hp:polygon` 150개(8파일)에서 한컴 원본 대비
    /// 구조 이탈을 만들었다.
    #[test]
    fn issue2726_common_shape_sz_always_emits_protect_attribute() {
        use crate::model::shape::{CommonObjAttr, DrawingObjAttr};

        let c = CommonObjAttr {
            size_protect: false,
            ..Default::default()
        };
        let drawing = DrawingObjAttr::default();
        let mut ctx = SerializeContext::default();

        let xml =
            render_common_shape_xml("polygon", &c, &None, Some(&drawing), &[], "", "", &mut ctx);
        assert!(
            xml.contains(r#"protect="0""#),
            "size_protect=false 여도 protect=\"0\" 속성이 방출되어야 함: {xml}"
        );
    }

    /// [#2726] `heightRelTo` 는 파서(`parse_size_criterion(_, allow_column_para=false)`)의
    /// **정확한 역**이어야 한다. 파서 치역이 `{PAPER, PAGE, ABSOLUTE}` 3값뿐이므로
    /// 방출도 절대 `COLUMN`/`PARA` 를 내면 안 된다 — 내면 되읽기에서 `Absolute` 로 접혀
    /// 왕복이 비-멱등이 된다. 5값 전수 대조로 못 박는다.
    #[test]
    fn issue2726_height_criterion_never_emits_column_or_para() {
        use crate::model::shape::{CommonObjAttr, DrawingObjAttr};

        let cases = [
            (SizeCriterion::Paper, "PAPER"),
            (SizeCriterion::Page, "PAGE"),
            (SizeCriterion::Column, "ABSOLUTE"),
            (SizeCriterion::Para, "ABSOLUTE"),
            (SizeCriterion::Absolute, "ABSOLUTE"),
        ];
        let drawing = DrawingObjAttr::default();
        let mut ctx = SerializeContext::default();

        for (criterion, expected) in cases {
            assert_eq!(
                height_criterion_str(criterion),
                expected,
                "높이 기준 {criterion:?} 는 {expected} 로 방출되어야 함"
            );

            let c = CommonObjAttr {
                height_criterion: criterion,
                ..Default::default()
            };
            let xml = render_common_shape_xml(
                "polygon",
                &c,
                &None,
                Some(&drawing),
                &[],
                "",
                "",
                &mut ctx,
            );
            assert!(
                xml.contains(&format!(r#"heightRelTo="{expected}""#)),
                "{criterion:?} → heightRelTo=\"{expected}\" 이어야 함: {xml}"
            );
            assert!(
                !xml.contains(r#"heightRelTo="COLUMN""#) && !xml.contains(r#"heightRelTo="PARA""#),
                "heightRelTo 는 COLUMN/PARA 를 방출하면 안 됨: {xml}"
            );
        }
    }

    /// [#2726] `widthRelTo` 는 5값 전부를 그대로 방출한다 — 파서
    /// `parse_size_criterion(_, allow_column_para=true)` 의 정확한 역.
    #[test]
    fn issue2726_width_criterion_emits_all_five_values() {
        let cases = [
            (SizeCriterion::Paper, "PAPER"),
            (SizeCriterion::Page, "PAGE"),
            (SizeCriterion::Column, "COLUMN"),
            (SizeCriterion::Para, "PARA"),
            (SizeCriterion::Absolute, "ABSOLUTE"),
        ];
        for (criterion, expected) in cases {
            assert_eq!(
                size_criterion_str(criterion),
                expected,
                "너비 기준 {criterion:?} 는 {expected} 로 방출되어야 함"
            );
        }
    }

    /// [Task #1627] empty-text(객체-only) 문단에서 bookmark 는 문단 시작으로 끌려가지 않고
    /// para.controls 순서대로 in-order 방출되어야 한다(원본 컨트롤 순서 보존).
    #[test]
    fn task1627_empty_para_bookmark_serialized_after_preceding_table() {
        use crate::model::control::{Bookmark, Control};

        let mut para = Paragraph::default();
        // empty text, controls 순서 = [Table, Bookmark]
        para.controls = vec![
            Control::Table(Box::default()),
            Control::Bookmark(Bookmark {
                name: "BM_AFTER_TBL".to_string(),
            }),
        ];
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        let tbl_pos = xml.find("<hp:tbl");
        let bm_pos = xml.find("BM_AFTER_TBL");
        assert!(
            tbl_pos.is_some(),
            "table 직렬화 필요: {}",
            &xml[..400.min(xml.len())]
        );
        assert!(bm_pos.is_some(), "bookmark 직렬화 필요");
        assert!(
            tbl_pos < bm_pos,
            "bookmark 가 table 뒤(원본 순서)에 와야 함 — 문단 시작 강제 회귀 (#1627)"
        );
    }

    fn make_doc_with_paragraph(para: Paragraph) -> (Document, Section) {
        let mut section = Section::default();
        section.paragraphs.push(para);
        let mut doc = Document::default();
        doc.sections.push(section.clone());
        (doc, section)
    }

    #[test]
    fn footnote_endnote_beneath_text_reflects_ir() {
        // beneathText(본문 아래 바로 이어 출력)가 IR 에서 방출돼야 한다.
        // 종전엔 템플릿 "0" 고정이라 저장할 때마다 이 설정이 꺼졌다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.footnote_shape.print_inline_after_text = true;
        section.section_def.endnote_shape.print_inline_after_text = true;
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:placement place="EACH_COLUMN" beneathText="1"/>"#),
            "각주 beneathText 가 IR 값이어야 함"
        );
        assert!(
            xml.contains(r#"<hp:placement place="END_OF_DOCUMENT" beneathText="1"/>"#),
            "미주 beneathText 가 IR 값이어야 함"
        );
        assert!(
            !xml.contains(r#"beneathText="0""#),
            "템플릿 기본 beneathText=0 잔존 금지"
        );
    }

    /// [#2779] placement 의 `place`(배치 방법)가 템플릿 상수가 아니라 IR 값으로
    /// 방출돼야 한다. 각주/미주는 같은 코드 공간(attr bits 8-9)을 쓰지만 OWPML 토큰이
    /// 서로 달라, 컨텍스트 키 역매핑이 필요하다:
    ///   각주 1=MERGED_COLUMN(통단) / 2=RIGHT_MOST_COLUMN, 미주 1=END_OF_SECTION.
    /// 재파싱까지 확인해 rhwp 자기 왕복이 무손실인지 본다.
    #[test]
    fn issue2779_note_place_reflects_ir() {
        use crate::model::footnote::FootnotePlacement;
        use crate::parser::hwpx::section::parse_hwpx_section;

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.footnote_shape.placement = FootnotePlacement::BelowText;
        section.section_def.endnote_shape.placement = FootnotePlacement::BelowText;
        doc.sections = vec![section.clone()];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:placement place="MERGED_COLUMN" beneathText="0"/>"#),
            "각주 통단 배치가 IR 값으로 방출돼야 함"
        );
        assert!(
            xml.contains(r#"<hp:placement place="END_OF_SECTION" beneathText="0"/>"#),
            "미주 구역끝 배치가 IR 값으로 방출돼야 함"
        );
        assert!(
            !xml.contains(r#"place="EACH_COLUMN""#),
            "템플릿 상수 EACH_COLUMN 잔존 금지"
        );
        assert!(
            !xml.contains(r#"place="END_OF_DOCUMENT""#),
            "템플릿 상수 END_OF_DOCUMENT 잔존 금지"
        );

        let reparsed = parse_hwpx_section(&xml).unwrap();
        assert_eq!(
            reparsed.section_def.footnote_shape.placement,
            FootnotePlacement::BelowText,
            "각주 배치가 재파싱에서 보존돼야 함"
        );
        assert_eq!(
            reparsed.section_def.endnote_shape.placement,
            FootnotePlacement::BelowText,
            "미주 배치가 재파싱에서 보존돼야 함"
        );
    }

    /// #4403: `tab_extended` 항목이 없던 "암묵적 기본 탭"은 HWPX 라운드트립(직렬화→재파싱)
    /// 후에도 `tab_extended` 가 비어 있어야 한다. 예전에는 폴백으로 고정 상수
    /// `width="4000"` 를 방출해 재파싱 시 `tab_extended` 항목이 새로 생겼다 — 렌더러는
    /// 그 항목이 있으면 폭을 "실제 계산된 값"으로 신뢰해(`total + width`) 문단의 진짜
    /// `TabDef`(예: 목차의 우측 정렬 쪽번호 탭)를 무시하고 커서 위치와 무관한 고정 거리만
    /// 전진시킨다(실측: `samples/SO-SUEOP.hwp` 자기 라운드트립 목차 페이지 최대 변위 470px).
    /// 지금은 "데이터 없음" 마커(`width="0"`)를 방출하고, 파서가 그 마커를 인식해
    /// `tab_extended` 항목을 만들지 않는다 — 렌더러가 실제 `TabDef` 기준으로 탭 정지를
    /// 다시 계산하게 한다.
    #[test]
    fn issue4403_implicit_tab_stays_a_placeholder_after_hwpx_roundtrip() {
        use crate::parser::hwpx::section::parse_hwpx_section;

        let mut para = Paragraph::default();
        para.text = "I.소설의 이해\t3".to_string();
        assert!(
            para.tab_extended.is_empty(),
            "전제: 원본은 tab_extended 데이터가 없는 암묵적 기본 탭"
        );
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:tab width="0" leader="0" type="1"/>"#),
            "데이터 없음 탭은 width=0 마커로 방출돼야 함: {}",
            &xml[..600.min(xml.len())]
        );

        let reparsed = parse_hwpx_section(&xml).unwrap();
        let reparsed_para = &reparsed.paragraphs[0];
        assert_eq!(reparsed_para.text, "I.소설의 이해\t3");
        // [#7170] 마커는 버리지 않고 자리표로 싣는다 — 버리면 그 뒤 탭의 확장이
        // 순번으로 밀린다. 저장 폭이 아니라는 판정은 `tab_ext_is_placeholder` 가 준다.
        assert_eq!(
            reparsed_para.tab_extended.len(),
            1,
            "탭 1개의 자리표가 남아야 함: {:?}",
            reparsed_para.tab_extended
        );
        assert!(
            crate::model::paragraph::tab_ext_is_placeholder(&reparsed_para.tab_extended[0]),
            "width=0 마커는 자리표로 읽혀야 함: {:?}",
            reparsed_para.tab_extended
        );
    }

    /// #4675: 고정폭 빈칸(U+2007)은 리터럴 문자가 아니라 `<hp:fwSpace/>` 요소로
    /// 직렬화돼야 한다. 리터럴 방출은 한글의 텍스트 추출·재조판 결과를 원본과 다르게
    /// 만든다(10k 스윕 TEXT_MISMATCH 의 76%). 왕복(직렬화→재파싱) 후 IR 텍스트는
    /// 동일해야 한다 — 파서가 요소를 같은 코드포인트로 되돌린다.
    ///
    /// 묶음 빈칸(U+00A0)은 **리터럴로 남긴다**. 한컴 원본은 U+2007 을 항상 요소로
    /// 쓰지만(실측 hwpx 300건: 요소 530 · 리터럴 0), U+00A0 은 요소 15 · 리터럴 9 로
    /// 섞여 쓴다 — IR 이 두 표기를 구분하지 못하는데 요소로 강제하면 리터럴이던 원본의
    /// 추출 텍스트에서 NBSP 가 사라진다(한글 2022 오라클 실측 23건).
    #[test]
    fn issue4675_fixed_width_space_serializes_as_element() {
        use crate::parser::hwpx::section::parse_hwpx_section;

        let mut para = Paragraph::default();
        para.text = "보\u{2007}도\u{2007}자\u{2007}료\u{00A0}끝".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert_eq!(
            xml.matches("<hp:fwSpace/>").count(),
            3,
            "U+2007 은 전부 fwSpace 요소로 방출돼야 함: {}",
            &xml[..800.min(xml.len())]
        );
        assert!(
            !xml.contains('\u{2007}'),
            "리터럴 U+2007 이 XML 에 남으면 안 됨"
        );
        assert!(
            xml.contains('\u{00A0}') && !xml.contains("<hp:nbSpace/>"),
            "U+00A0 은 리터럴 유지 — 요소로 바꾸면 한글 추출에서 사라진다"
        );

        let reparsed = parse_hwpx_section(&xml).unwrap();
        assert_eq!(
            reparsed.paragraphs[0].text, "보\u{2007}도\u{2007}자\u{2007}료\u{00A0}끝",
            "요소 왕복 후 IR 텍스트 불변"
        );
    }

    /// #4676: `<hp:curve>` 의 점은 `<hc:pt>` 나열이 아니라 `<hp:seg>` 체인으로 나가야 한다.
    /// `<hc:pt>` 로 저장하면 한글이 파일을 여는 도중 프로세스째 죽는다(COM RPC 0x800706BE).
    /// 한컴 원본 실측: `hp:curve` 는 seg 만 쓰고 `hc:pt` 는 한 번도 쓰지 않는다.
    /// HWP5 유래 구간 종류(LINE/CURVE)는 IR의 `segment_types`에서 나온다.
    #[test]
    fn issue4676_curve_emits_seg_chain_not_pts() {
        use crate::model::shape::{CommonObjAttr, CurveShape, DrawingObjAttr};
        use crate::model::Point;

        let curve = CurveShape {
            common: CommonObjAttr::default(),
            drawing: DrawingObjAttr::default(),
            points: vec![
                Point { x: 0, y: 100 },
                Point { x: 500, y: 0 },
                Point { x: 900, y: 250 },
            ],
            segment_types: vec![1, 0],
        };
        let mut ctx = SerializeContext::default();
        let xml = render_shape(&ShapeObject::Curve(curve), &mut ctx);

        assert!(
            !xml.contains("<hc:pt "),
            "curve 는 hc:pt 를 방출하면 안 된다(한글 크래시): {xml}"
        );
        assert!(
            xml.contains(r#"<hp:seg type="CURVE" x1="0" y1="100" x2="500" y2="0"/>"#),
            "첫 구간은 곡선: {xml}"
        );
        assert!(
            xml.contains(r#"<hp:seg type="LINE" x1="500" y1="0" x2="900" y2="250"/>"#),
            "둘째 구간은 직선(segment_types 보존): {xml}"
        );
        // 점 N 개 → 구간 N-1 개
        assert_eq!(xml.matches("<hp:seg ").count(), 2, "{xml}");
    }

    /// [#4676, #8153] XML → IR → XML 경계에서 점과 구간 종류를 보존한다.
    /// 한컴이 읽는 `hp:seg` 형식도 유지하며 `hc:pt`로 되돌리지 않는다.
    #[test]
    fn issue4676_hwpx_curve_chain_preserves_segment_types() {
        use crate::parser::hwpx::section::parse_hwpx_section;

        let source = r##"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph"
        xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">
  <hp:p paraPrIDRef="0" styleIDRef="0">
    <hp:run charPrIDRef="0">
      <hp:curve id="0" zOrder="0" numberingType="NONE" textWrap="TOP_AND_BOTTOM"
                textFlow="BOTH_SIDES" lock="0" href="" groupLevel="0" instid="1">
        <hp:offset x="0" y="0"/>
        <hp:orgSz width="100" height="100"/>
        <hp:curSz width="100" height="100"/>
        <hp:lineShape color="#000000" width="113" style="SOLID"/>
        <hp:seg type="CURVE" x1="0" y1="0" x2="10" y2="20"/>
        <hp:seg type="CURVE" x1="10" y1="20" x2="40" y2="30"/>
        <hp:seg type="CURVE" x1="40" y1="30" x2="90" y2="80"/>
      </hp:curve>
    </hp:run>
  </hp:p>
</hs:sec>"##;

        let section = parse_hwpx_section(source).expect("HWPX curve 파싱");
        let mut doc = Document::default();
        doc.sections.push(section.clone());
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap())
            .expect("section XML");

        assert_eq!(
            xml.matches("<hp:seg ").count(),
            3,
            "점 체인 길이 보존: {xml}"
        );
        assert!(
            !xml.contains("<hc:pt "),
            "curve에는 hc:pt를 다시 쓰면 안 됨: {xml}"
        );

        let reparsed = parse_hwpx_section(&xml).expect("재파싱");
        let curve = reparsed.paragraphs[0]
            .controls
            .iter()
            .find_map(|control| match control {
                Control::Shape(shape) => match shape.as_ref() {
                    ShapeObject::Curve(curve) => Some(curve),
                    _ => None,
                },
                _ => None,
            })
            .expect("curve shape");
        assert_eq!(curve.points.len(), 4, "첫 점과 세 segment 끝점이 남아야 함");
        assert_eq!(curve.segment_types, vec![1, 1, 1], "원본 CURVE 구간 보존");
    }

    /// [#2779] 각주 코드 2(가장 오른쪽 단)는 각주 전용 토큰이 있으나, 미주에는 스키마상
    /// 대응 토큰이 없어 기본값 END_OF_DOCUMENT 로 강등한다(주석 참조).
    #[test]
    fn issue2779_note_place_right_column_footnote_only() {
        use crate::model::footnote::FootnotePlacement;

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.footnote_shape.placement = FootnotePlacement::RightColumn;
        section.section_def.endnote_shape.placement = FootnotePlacement::RightColumn;
        doc.sections = vec![section.clone()];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:placement place="RIGHT_MOST_COLUMN" beneathText="0"/>"#),
            "각주 오른쪽단 배치가 IR 값으로 방출돼야 함"
        );
        assert!(
            xml.contains(r#"<hp:placement place="END_OF_DOCUMENT" beneathText="0"/>"#),
            "미주는 스키마 밖 코드 2 를 기본값으로 강등해야 함"
        );
    }

    /// [#2779] 기본 SectionDef(placement=EachColumn, beneathText=0)의 출력은 템플릿과
    /// 동일해야 한다 — 무변경 가드.
    #[test]
    fn issue2779_note_place_keeps_template_defaults() {
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:placement place="EACH_COLUMN" beneathText="0"/>"#),
            "각주 기본 배치는 템플릿과 동일해야 함"
        );
        assert!(
            xml.contains(r#"<hp:placement place="END_OF_DOCUMENT" beneathText="0"/>"#),
            "미주 기본 배치는 템플릿과 동일해야 함"
        );
    }

    #[test]
    fn issue1984_footnote_shape_reflects_ir() {
        // [#1984] footNotePr 의 noteLine/noteSpacing 이 템플릿 기본값(aboveLine=850,
        // betweenNotes=283 등)이 아니라 IR FootnoteShape 값으로 방출돼야 한다. 미치환 시
        // 각주 zone 높이가 달라져 각주 있는 페이지의 표 분할·페이지 수가 갈린다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, mut section) = make_doc_with_paragraph(para);
        let fs = &mut section.section_def.footnote_shape;
        fs.separator_margin_top = 1417; // aboveLine
        fs.note_spacing = 850; // belowLine
        fs.raw_unknown = 566; // betweenNotes
        fs.separator_line_width = 9; // 0.7 mm
        fs.separator_length = -2;
        fs.separator_line_type = 1; // SOLID
        fs.separator_color = 0x99_99_99; // #999999
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(
                r#"<hp:noteSpacing betweenNotes="566" belowLine="850" aboveLine="1417"/>"#
            ),
            "각주 noteSpacing 이 IR 값이어야 함: {}",
            &xml[..xml
                .find("footNote")
                .map(|i| i + 300)
                .unwrap_or(600)
                .min(xml.len())]
        );
        assert!(
            xml.contains(
                r##"<hp:noteLine length="-2" type="SOLID" width="0.7 mm" color="#999999"/>"##
            ),
            "각주 noteLine 이 IR 값이어야 함"
        );
        assert!(
            !xml.contains(r#"betweenNotes="283""#),
            "템플릿 기본 betweenNotes=283 잔존 금지"
        );
    }

    #[test]
    fn footnote_endnote_numbering_and_start_reflect_ir() {
        // 템플릿 기본(type="CONTINUOUS" newNum="1")이 아니라 IR FootnoteShape 의
        // 번호 종류·시작 번호로 방출돼야 한다(각주/미주 각각). fn/en 템플릿 문자열이
        // 동일하므로 위치 기반 치환이 정확히 각 슬롯을 채우는지도 함께 검증한다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.footnote_shape.numbering =
            crate::model::footnote::FootnoteNumbering::RestartPage;
        section.section_def.footnote_shape.start_number = 3;
        section.section_def.endnote_shape.numbering =
            crate::model::footnote::FootnoteNumbering::RestartSection;
        section.section_def.endnote_shape.start_number = 5;
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:numbering type="ON_PAGE" newNum="3"/>"#),
            "각주 numbering 이 IR 값이어야 함"
        );
        assert!(
            xml.contains(r#"<hp:numbering type="ON_SECTION" newNum="5"/>"#),
            "미주 numbering 이 IR 값이어야 함"
        );
        assert!(
            !xml.contains(r#"<hp:numbering type="CONTINUOUS" newNum="1"/>"#),
            "템플릿 기본 numbering 잔존 금지"
        );
    }

    #[test]
    fn issue2742_auto_num_format_reflects_ir() {
        // [#2742] footNotePr/endNotePr 의 autoNumFormat 5속성(type·userChar·prefixChar·
        // suffixChar·supscript)이 템플릿 상수가 아니라 IR FootnoteShape 값으로 방출돼야
        // 한다. 미치환 시 구역 각주/미주 모양이 저장마다 한컴 기본값으로 리셋돼, 실측
        // 코퍼스에서 미주 장식문자 「문…)」(17파일)와 위첨자 설정(1파일)이 사라졌다.
        // fn/en 템플릿 문자열이 동일하므로 위치 기반 치환이 각 슬롯을 정확히 채우는지도
        // 함께 검증한다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, mut section) = make_doc_with_paragraph(para);
        let fs = &mut section.section_def.footnote_shape;
        fs.number_format = crate::model::footnote::NumberFormat::CircledDigit;
        fs.number_code_superscript = true;
        let es = &mut section.section_def.endnote_shape;
        es.number_format = crate::model::footnote::NumberFormat::UserChar;
        es.user_char = '★';
        es.prefix_char = '문';
        es.suffix_char = ')'; // U+FF09 전각 — 한컴 실물 표기
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(
                r#"<hp:autoNumFormat type="CIRCLED_DIGIT" userChar="" prefixChar="" suffixChar=")" supscript="1"/>"#
            ),
            "각주 autoNumFormat 이 IR 값이어야 함: {}",
            &xml[..xml
                .find("footNotePr")
                .map(|i| i + 200)
                .unwrap_or(600)
                .min(xml.len())]
        );
        assert!(
            xml.contains(
                r#"<hp:autoNumFormat type="USER_CHAR" userChar="★" prefixChar="문" suffixChar=")" supscript="0"/>"#
            ),
            "미주 autoNumFormat 이 IR 값이어야 함(장식문자 보존)"
        );
        assert!(
            !xml.contains(TEMPLATE_AUTO_NUM_FORMAT),
            "템플릿 기본 autoNumFormat 잔존 금지"
        );
    }

    #[test]
    fn issue2742_auto_num_format_keeps_template_when_ir_unset() {
        // 파싱을 거치지 않은 기본 SectionDef(number_format=Digit, 장식문자 '\0',
        // supscript=false)에서는 템플릿과 바이트 동일해야 한다 — '\0' = 미지정 규약.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        assert_eq!(
            section.section_def.endnote_shape.suffix_char, '\0',
            "전제: 기본 장식문자는 '\\0'"
        );
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert_eq!(
            xml.matches(TEMPLATE_AUTO_NUM_FORMAT).count(),
            2,
            "IR 미설정 시 각주/미주 모두 템플릿 문자열 유지: {xml:.900}"
        );
    }

    #[test]
    fn hp_p_attrs_reflect_para_shape_id_and_style_id() {
        let mut para = Paragraph::default();
        para.para_shape_id = 7;
        para.style_id = 3;
        para.text = "hi".to_string();
        let (mut doc, section) = make_doc_with_paragraph(para);
        // style_id=3 이 등록되도록 스타일 4개 확보 (미등록 강등 #1933 회피).
        doc.doc_info.styles = vec![crate::model::style::Style::default(); 4];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains(r#"paraPrIDRef="7""#),
            "<hp:p> must reflect para_shape_id=7: {}",
            &xml[..200.min(xml.len())]
        );
        assert!(
            xml.contains(r#"styleIDRef="3""#),
            "<hp:p> must reflect style_id=3"
        );
    }

    /// [Issue #1933] 스타일 목록 밖 styleIDRef 는 기본(0)으로 강등되어 직렬화가
    /// 하드 실패하지 않는다 (한글 정합 — 열리는데 저장 불가 해소).
    #[test]
    fn out_of_range_style_id_downgraded_to_default() {
        let mut para = Paragraph::default();
        para.style_id = 96; // 스타일 목록(4개, idx 0..3) 밖
        para.text = "hi".to_string();
        let (mut doc, section) = make_doc_with_paragraph(para);
        doc.doc_info.styles = vec![crate::model::style::Style::default(); 4];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        // 참조 정합 단언 — 강등 없으면 styleIDRef:[96] 미등록으로 하드 실패한다.
        ctx.assert_all_refs_resolved()
            .expect("#1933: 미등록 styleIDRef 강등으로 참조 정합해야 함");
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains(r#"styleIDRef="0""#),
            "미등록 style_id=96 은 0 으로 강등되어야 함"
        );
        assert!(
            !xml.contains(r#"styleIDRef="96""#),
            "미등록 style_id 는 방출되지 않아야 함"
        );
    }

    #[test]
    fn secpr_emits_ir_text_direction_vertical() {
        // 파서는 textDirection="VERTICAL" → text_direction=1 로 읽지만 직렬화기가 재출력하지
        // 않아 세로쓰기 구역이 .hwpx 저장 시 HORIZONTAL 로 유실됐다. 1 이면 VERTICAL 방출.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, _) = make_doc_with_paragraph(para);
        doc.sections[0].section_def.text_direction = 1;
        let section = doc.sections[0].clone();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"textDirection="VERTICAL""#),
            "세로쓰기 구역은 textDirection=VERTICAL 로 방출돼야 함: {xml:.400}"
        );
        assert!(
            !xml.contains(r#"textDirection="HORIZONTAL""#),
            "secPr 의 HORIZONTAL 이 남아있으면 안 됨: {xml:.400}"
        );
    }

    #[test]
    fn secpr_keeps_horizontal_when_text_direction_unset() {
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, _) = make_doc_with_paragraph(para);
        let section = doc.sections[0].clone();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"textDirection="HORIZONTAL""#),
            "기본(text_direction=0) 은 HORIZONTAL 유지: {xml:.400}"
        );
    }

    #[test]
    fn secpr_emits_ir_tab_stop_grid_and_start_num() {
        // 템플릿 secPr 의 grid / startNum / tabStop 은 [#1987] 의 spaceColumns·
        // outlineShapeIDRef 치환에서 빠져 있어, IR 값과 무관하게 늘 템플릿 상수로
        // 나갔다. 열었다 저장하면 구역 그리드·시작 번호·기본 탭 폭이 사라진다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, _) = make_doc_with_paragraph(para);
        {
            let sd = &mut doc.sections[0].section_def;
            sd.default_tab_spacing = 4000;
            sd.line_grid = 1200;
            sd.char_grid = 900;
            sd.page_num = 47;
            sd.picture_num = 3;
            sd.table_num = 5;
            sd.equation_num = 7;
        }
        let section = doc.sections[0].clone();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"tabStop="4000""#),
            "기본 탭 폭이 IR 값이어야 함: {xml:.600}"
        );
        assert!(
            xml.contains(r#"<hp:grid lineGrid="1200" charGrid="900" wonggojiFormat="0"/>"#),
            "구역 그리드가 IR 값이어야 함: {xml:.600}"
        );
        // 원고지 정서법(HWP5 flags bit 22)도 HWPX 속성으로 나간다.
        let mut wonggoji = doc.sections[0].clone();
        wonggoji.section_def.set_wonggoji_format(true);
        let xml = String::from_utf8(write_section(&wonggoji, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:grid lineGrid="1200" charGrid="900" wonggojiFormat="1"/>"#),
            "원고지 정서법이 IR 값이어야 함: {xml:.600}"
        );
        assert!(
            xml.contains(
                r#"<hp:startNum pageStartsOn="BOTH" page="47" pic="3" tbl="5" equation="7"/>"#
            ),
            "시작 번호가 IR 값이어야 함: {xml:.600}"
        );
    }

    #[test]
    fn secpr_keeps_template_tab_stop_when_ir_unset() {
        // SectionDef 는 derive(Default) 라 파싱을 거치지 않은 문서에서 0 이다.
        // 0 을 그대로 내보내면 탭 폭이 0 이 되어 지금보다 나빠지므로 템플릿 기본값을 유지한다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        assert_eq!(
            section.section_def.default_tab_spacing, 0,
            "전제: 기본값은 0"
        );
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"tabStop="8000""#),
            "IR 미설정 시 템플릿 상수 유지: {xml:.600}"
        );
    }

    #[test]
    fn secpr_emits_tab_stop_val_and_unit() {
        // [Finding 14] 원본 secPr 의 tabStopVal="4000" tabStopUnit="HWPUNIT" (한컴
        // 기본 탭 폭 상수) 이 직렬화에서 누락되지 않아야 한다. 순서는
        // tabStop → tabStopVal → tabStopUnit → outlineShapeIDRef.
        // [#1987] outlineShapeIDRef 는 이제 IR 값 치환 대상 — 기본 SectionDef 는
        // outline_numbering_id=0 이므로 "0" 이 방출된다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(
                r#"tabStop="8000" tabStopVal="4000" tabStopUnit="HWPUNIT" outlineShapeIDRef="0""#
            ),
            "secPr 에 tabStopVal/tabStopUnit 이 정확 순서로 있어야 함: {}",
            &xml[..600.min(xml.len())]
        );
    }

    #[test]
    fn issue1987_secpr_scalars_reflect_ir() {
        // [#1987] secPr 의 spaceColumns/outlineShapeIDRef 가 템플릿 하드코딩(1134/1)이
        // 아니라 IR 값으로 방출돼야 한다. 미치환 시 멀티구역 문서 후반부 렌더 붕괴.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.column_spacing = 1130;
        section.section_def.outline_numbering_id = 0;
        doc.sections = vec![section.clone()];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"spaceColumns="1130""#),
            "spaceColumns=1130 방출: {}",
            &xml[..400]
        );
        assert!(
            xml.contains(r#"outlineShapeIDRef="0""#),
            "outlineShapeIDRef=0 방출"
        );
        assert!(
            !xml.contains(r#"spaceColumns="1134""#),
            "템플릿 1134 잔존 금지"
        );
    }

    /// [#2779] secPr@memoShapeIDRef 가 템플릿 상수 "0" 이 아니라 IR 값으로 방출되고
    /// 재파싱까지 살아남아야 한다. 종전엔 3계층(모델/파서/직렬화기) 모두 결손이라
    /// 메모 모양 참조가 저장마다 0 으로 리셋됐다(실측 14 secPr/9 파일).
    #[test]
    fn issue2779_secpr_memo_shape_id_reflects_ir() {
        use crate::parser::hwpx::section::parse_hwpx_section;

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (mut doc, mut section) = make_doc_with_paragraph(para);
        section.section_def.memo_shape_id = 3;
        doc.sections = vec![section.clone()];
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"memoShapeIDRef="3""#),
            "memoShapeIDRef 가 IR 값이어야 함: {}",
            &xml[..600.min(xml.len())]
        );
        assert!(
            !xml.contains(r#"memoShapeIDRef="0""#),
            "템플릿 상수 memoShapeIDRef=0 잔존 금지"
        );

        let reparsed = parse_hwpx_section(&xml).unwrap();
        assert_eq!(
            reparsed.section_def.memo_shape_id, 3,
            "memoShapeIDRef 가 재파싱에서 보존돼야 함"
        );
    }

    /// [#2779] 기본 SectionDef(memo_shape_id=0)의 출력은 템플릿과 동일해야 한다 —
    /// 무변경 가드.
    #[test]
    fn issue2779_secpr_memo_shape_id_keeps_template_default() {
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"outlineShapeIDRef="0" memoShapeIDRef="0""#),
            "기본 문서는 템플릿 그대로여야 함: {}",
            &xml[..600.min(xml.len())]
        );
    }

    #[test]
    fn section_root_declares_hwpunitchar_namespace() {
        // [Finding 15] hs:sec 루트의 xmlns:hwpunitchar 선언(원본에 존재, 미사용
        // 이지만 무손실 위해 보존)이 누락되지 않아야 한다.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"xmlns:hwpunitchar="http://www.hancom.co.kr/hwpml/2016/HwpUnitChar""#),
            "hs:sec 에 xmlns:hwpunitchar 선언이 있어야 함"
        );
    }

    #[test]
    fn task1407_body_col_pr_reflects_ir_column_def() {
        // [#1407] 본문 첫 문단 IR 에 2단 ColumnDef 가 있으면 템플릿 하드코딩
        // colPr(colCount=1)이 IR 값(colCount=2)으로 치환돼야 한다. 미치환 시
        // 2단→1단 손실로 페이지 넘침(143E RT 1→2).
        use crate::model::page::{ColumnDef, ColumnType};
        let mut cd = ColumnDef::default();
        cd.column_type = ColumnType::Normal;
        cd.column_count = 2;
        cd.same_width = true;
        cd.spacing = 2268;

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        para.controls.push(Control::ColumnDef(cd));

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"colCount="2""#) && xml.contains(r#"sameGap="2268""#),
            "본문 colPr 이 IR 2단 정의로 치환돼야 함: {}",
            &xml[..900.min(xml.len())]
        );
        assert!(
            !xml.contains(r#"colCount="1""#),
            "하드코딩 colCount=1 이 남으면 안 됨 (회귀 가드): {}",
            &xml[..900.min(xml.len())]
        );
    }

    #[test]
    fn task1407_single_column_doc_unaffected() {
        // ColumnDef IR 이 없는 문단(단일 단)은 템플릿 colCount=1 유지 — 회귀 없음.
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"colCount="1""#),
            "ColumnDef 없으면 템플릿 colCount=1 유지"
        );
    }

    #[test]
    fn hp_run_reflects_first_char_shape_id() {
        let mut para = Paragraph::default();
        para.text = "hello".to_string();
        para.char_shapes.push(CharShapeRef {
            start_pos: 0,
            char_shape_id: 42,
        });
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains(r#"<hp:run charPrIDRef="42"><hp:t>hello</hp:t>"#),
            "first run must use char_shape_id 42, xml excerpt around <hp:t>: {:?}",
            xml.find("<hp:t>")
                .map(|i| &xml[i.saturating_sub(50)..(i + 50).min(xml.len())])
        );
    }

    // ---------- #1382: autoNum placeholder 슬롯 ----------

    /// autoNum IR 규약 문단: 텍스트 "가·placeholder·나", offsets [0,1,9].
    fn autonum_para() -> Paragraph {
        let mut para = Paragraph::default();
        para.text = "가 나".to_string(); // 가(0) + placeholder 공백(1) + 나(9)
        para.char_offsets = vec![0, 1, 9];
        para.char_count = 11; // offsets 축 총 10 + 끝 마커 1
        para.controls
            .push(crate::model::control::Control::AutoNumber(
                crate::model::control::AutoNumber {
                    number_type: crate::model::control::AutoNumberType::Footnote,
                    ..Default::default()
                },
            ));
        para
    }

    #[test]
    fn task1382_inference_counts_autonum_placeholder_slot() {
        // placeholder 가 8유닛 중 1유닛을 점유해 잉여가 7로 측정되는 패턴 —
        // autoNum 보정으로 슬롯 1개로 집계되어야 한다 (종전 0 → mismatch 경로).
        assert_eq!(inferred_control_slot_count(&autonum_para()), 1);
    }

    #[test]
    fn task1382_autonum_slot_emitted_at_placeholder() {
        // ctrl 이 placeholder 원위치(mid-text)에 방출되고 placeholder 는 텍스트로
        // 내보내지 않는다 (한컴 원본 XML 동형).
        let (doc, section) = make_doc_with_paragraph(autonum_para());
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains("<hp:t>가</hp:t><hp:ctrl><hp:autoNum"),
            "ctrl 은 placeholder 위치(가 직후)에 방출: {}",
            xml
        );
        assert!(
            xml.contains("</hp:ctrl><hp:t>나</hp:t>"),
            "placeholder 공백은 텍스트로 미방출, 후속 텍스트만 이어짐: {}",
            xml
        );
        assert!(
            !xml.contains("<hp:t>가 나</hp:t>"),
            "종전 결함(슬롯 끝 방출 + placeholder 텍스트 이중 방출) 재발 금지"
        );
    }

    #[test]
    fn task1382_synthetic_autonum_without_placeholder_keeps_legacy_path() {
        // 합성 IR(placeholder/offset 없는 편집기 생성 문단)은 보정 후에도 추론 0 —
        // 기존 mismatch 경로(끝 방출) 유지로 회귀 없음.
        let mut para = Paragraph::default();
        para.text = "가나".to_string();
        para.char_offsets = vec![0, 1];
        para.char_count = 3;
        para.controls
            .push(crate::model::control::Control::AutoNumber(
                crate::model::control::AutoNumber::default(),
            ));
        assert_eq!(inferred_control_slot_count(&para), 0);
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains("<hp:t>가나</hp:t><hp:ctrl><hp:autoNum"),
            "합성 IR 은 텍스트 후 끝 방출(기존 동작): {}",
            xml
        );
    }

    // ---------- #1388: replace_page_pr — secPr 페이지 여백 원본 보존 ----------

    #[test]
    fn task1388_page_margin_reflects_page_def() {
        let mut para = Paragraph::default();
        para.text = "m".to_string();
        let (doc, mut section) = make_doc_with_paragraph(para);
        let pd = &mut section.section_def.page_def;
        pd.width = 59527;
        pd.height = 84189;
        pd.margin_header = 4251;
        pd.margin_footer = 4251;
        pd.margin_gutter = 0;
        pd.margin_left = 7086;
        pd.margin_right = 14173;
        pd.margin_top = 4251;
        pd.margin_bottom = 4251;
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains(
                r#"<hp:margin header="4251" footer="4251" gutter="0" left="7086" right="14173" top="4251" bottom="4251"/>"#
            ),
            "hp:margin must reflect IR PageDef 7 fields (온새미로 sec0 실측값)"
        );
        assert!(
            !xml.contains(r#"left="8504""#),
            "template margin value must not survive"
        );
        // #1166 동적화 회귀 없음 — width/height 동반 검증.
        assert!(xml.contains(r#"width="59527" height="84189""#));
    }

    #[test]
    fn task1388_gutter_type_reflects_binding() {
        use crate::model::page::BindingMethod;
        for (binding, expected) in [
            (BindingMethod::SingleSided, r#"gutterType="LEFT_ONLY""#),
            (BindingMethod::DuplexSided, r#"gutterType="LEFT_RIGHT""#),
            (BindingMethod::TopFlip, r#"gutterType="TOP_BOTTOM""#),
        ] {
            let mut para = Paragraph::default();
            para.text = "g".to_string();
            let (doc, mut section) = make_doc_with_paragraph(para);
            section.section_def.page_def.binding = binding;
            let mut ctx = SerializeContext::collect_from_document(&doc);
            let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
            let xml = std::str::from_utf8(&bytes).unwrap();
            assert!(
                xml.contains(expected),
                "binding={:?} must emit {}",
                binding,
                expected
            );
        }
    }

    #[test]
    fn task1388_template_mismatch_keeps_original() {
        // 템플릿 anchor 가 없는 입력 — 원본 유지(silent no-op, 회귀 방지 정책).
        let mut pd = crate::model::page::PageDef::default();
        pd.margin_left = 1234;
        let xml = r#"<hp:pagePr landscape="WIDELY" width="1" height="2" gutterType="LEFT_ONLY"><hp:margin header="0" footer="0" gutter="0" left="9" right="9" top="9" bottom="9"/></hp:pagePr>"#;
        assert_eq!(replace_page_pr(xml, &pd), xml);
    }

    #[test]
    fn task1388_template_anchor_present_in_template() {
        // 템플릿 변경 시 silent no-op 으로 빠지지 않도록 anchor 존재를 직접 보장한다.
        let pd = crate::model::page::PageDef {
            margin_header: 1,
            margin_footer: 2,
            margin_gutter: 3,
            margin_left: 4,
            margin_right: 5,
            margin_top: 6,
            margin_bottom: 7,
            ..Default::default()
        };
        let out = replace_page_pr(EMPTY_SECTION_XML, &pd);
        assert!(
            out.contains(
                r#"<hp:margin header="1" footer="2" gutter="3" left="4" right="5" top="6" bottom="7"/>"#
            ),
            "EMPTY_SECTION_XML 의 margin anchor 치환이 실패 — 템플릿이 변경됐는지 확인"
        );
    }

    #[test]
    fn page_break_paragraph_emits_attr() {
        let mut para = Paragraph::default();
        para.text = "p1".to_string();
        para.column_type = crate::model::paragraph::ColumnBreakType::Page;
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(
            xml.contains(r#"pageBreak="1""#),
            "pageBreak must be 1 for Page column_type"
        );
        assert!(xml.contains(r#"columnBreak="0""#));
    }

    #[test]
    fn default_paragraph_keeps_zero_attrs() {
        let mut para = Paragraph::default();
        para.text = "x".to_string();
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&section, &doc, 0, &mut ctx).unwrap();
        let xml = std::str::from_utf8(&bytes).unwrap();
        assert!(xml.contains(r#"paraPrIDRef="0""#));
        assert!(xml.contains(r#"styleIDRef="0""#));
        // char_shapes 가 비어있으면 fallback 0
        assert!(xml.contains(r#"<hp:run charPrIDRef="0">"#));
    }

    #[test]
    fn additional_paragraphs_use_their_own_char_shape() {
        let mut p1 = Paragraph::default();
        p1.text = "first".to_string();
        p1.char_shapes.push(CharShapeRef {
            start_pos: 0,
            char_shape_id: 5,
        });
        let mut p2 = Paragraph::default();
        p2.text = "second".to_string();
        p2.para_shape_id = 2;
        p2.char_shapes.push(CharShapeRef {
            start_pos: 0,
            char_shape_id: 6,
        });
        let mut section = Section::default();
        section.paragraphs.push(p1);
        section.paragraphs.push(p2);
        let mut doc = Document::default();
        doc.sections.push(section.clone());
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        // 두 번째 문단: paraPrIDRef=2, charPrIDRef=6
        assert!(xml.contains(r#"paraPrIDRef="2""#));
        assert!(
            xml.matches(r#"charPrIDRef="6""#).count() >= 1,
            "second paragraph must emit charPrIDRef=6"
        );
    }

    // ---------- #177 Stage 2: IR 기반 lineseg 출력 ----------

    use crate::model::paragraph::LineSeg;

    #[test]
    fn task177_lineseg_reflects_ir_values() {
        // IR에 담긴 lineseg 값이 XML 속성에 그대로 반영되는지 확인.
        let mut para = Paragraph::default();
        para.text = "hello".to_string();
        para.line_segs.push(LineSeg {
            text_start: 0,
            vertical_pos: 5000,
            line_height: 1200,
            text_height: 1100,
            baseline_distance: 900,
            line_spacing: 700,
            column_start: 100,
            segment_width: 50000,
            tag: 999,
        });
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(xml.contains(r#"<hp:lineseg textpos="0" vertpos="5000" vertsize="1200" textheight="1100" baseline="900" spacing="700" horzpos="100" horzsize="50000" flags="999"/>"#),
            "lineseg must reflect IR values exactly, got XML: {}",
            &xml[xml.find("<hp:lineseg").unwrap_or(0)..(xml.find("<hp:lineseg").unwrap_or(0) + 200).min(xml.len())]);
    }

    #[test]
    fn task177_multiple_linesegs_preserved_in_order() {
        let mut para = Paragraph::default();
        para.text = "three\nlines\nhere".to_string();
        for (i, (tp, vp, lh)) in [(0u32, 0i32, 1000), (6, 1500, 1200), (12, 3100, 1100)]
            .iter()
            .enumerate()
        {
            let _ = i;
            para.line_segs.push(LineSeg {
                text_start: *tp,
                vertical_pos: *vp,
                line_height: *lh,
                text_height: *lh,
                baseline_distance: 850,
                line_spacing: 600,
                column_start: 0,
                segment_width: 42520,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
            });
        }
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        // 3개 lineseg 모두 출력되고 각각의 vertsize 값이 IR 값과 일치
        assert_eq!(xml.matches("<hp:lineseg ").count(), 3);
        assert!(xml.contains(r#"textpos="0" vertpos="0" vertsize="1000""#));
        assert!(xml.contains(r#"textpos="6" vertpos="1500" vertsize="1200""#));
        assert!(xml.contains(r#"textpos="12" vertpos="3100" vertsize="1100""#));
    }

    #[test]
    fn text_positions_unshifted_detects_leading_and_mid_controls() {
        // mismatch 경로는 텍스트를 0 부터 연속으로 다시 쓴다. 원본에서도 연속이었으면
        // 좌표가 그대로라 lineseg 를 버릴 이유가 없다.
        let mut para = Paragraph::default();
        para.text = "abcde".to_string();

        // 컨트롤이 전부 텍스트 뒤 — 위치 안 밀림
        para.char_offsets = vec![0, 1, 2, 3, 4];
        assert!(text_positions_unshifted(&para));

        // 앞에 8유닛 슬롯 — 전부 밀림
        para.char_offsets = vec![8, 9, 10, 11, 12];
        assert!(!text_positions_unshifted(&para));

        // 중간에 슬롯 — 뒤쪽만 밀림
        para.char_offsets = vec![0, 1, 2, 11, 12];
        assert!(!text_positions_unshifted(&para));

        // char_offsets 없는 합성 IR 은 종전 동작 유지
        para.char_offsets = vec![];
        assert!(text_positions_unshifted(&para));
    }

    #[test]
    fn task1380_linesegarray_omitted_when_ir_empty() {
        dirty_text_partition_omits_hwpx_linesegarray();
        // IR 의 line_segs 가 비어있으면 linesegarray 요소 자체를 방출 생략 (#1380).
        // 종전 fallback(vertsize=1000 합성)은 원본 무 → RT 유 비대칭을 만들었다.
        let mut para = Paragraph::default();
        para.text = "a\nb".to_string(); // 텍스트가 있어도 IR 에 lineseg 없으면 생략
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            !xml.contains("<hp:linesegarray"),
            "empty line_segs must omit linesegarray entirely: {}",
            xml
        );
        assert!(!xml.contains("<hp:lineseg "));
    }

    fn dirty_text_partition_omits_hwpx_linesegarray() {
        let mut para = Paragraph {
            text: "AB".to_string(),
            char_count: 3,
            char_offsets: vec![0, 1],
            char_shapes: vec![CharShapeRef {
                start_pos: 0,
                char_shape_id: 0,
            }],
            line_segs: vec![LineSeg {
                text_start: 0,
                line_height: 500,
                segment_width: 42_000,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }],
            ..Default::default()
        };
        para.insert_text_at(2, " moderately wider");
        para.invalidate_layout_inputs();
        assert!(para.stored_text_partition_is_dirty());

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(!xml.contains("<hp:linesegarray"));
    }

    #[test]
    fn task1380_empty_section_omits_linesegarray() {
        // 문단이 없는 섹션(비파싱 IR)도 템플릿의 linesegarray 가 제거되어야 함 (#1380).
        let doc = crate::model::document::Document::default();
        let section = crate::model::document::Section::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(!xml.contains("<hp:linesegarray"));
    }

    #[test]
    fn task177_ir_lineseg_takes_precedence_over_text() {
        // text 의 \n 개수가 2개(lineseg 3개 기대)이지만 IR의 line_segs 는 1개만 있음.
        // IR 기반 출력이 우선 — 1개만 출력돼야 함.
        let mut para = Paragraph::default();
        para.text = "a\nb\nc".to_string(); // 3줄
        para.line_segs.push(LineSeg {
            text_start: 0,
            vertical_pos: 0,
            line_height: 2000, // IR 값
            text_height: 2000,
            baseline_distance: 1700,
            line_spacing: 300,
            column_start: 0,
            segment_width: 40000,
            tag: 0,
        });
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        // IR 에 1개만 있으므로 lineseg 도 1개만 출력 (rhwp 는 원본 보존)
        assert_eq!(xml.matches("<hp:lineseg ").count(), 1);
        assert!(
            xml.contains(r#"vertsize="2000""#),
            "IR value 2000 must be used, not fallback 1000"
        );
    }

    // ---------- #1556: 고아(다단락) fieldEnd 방출 ----------

    #[test]
    fn task1556_orphan_field_end_emitted_at_text_end() {
        // 다단락 필드의 end 문단(para 0.16 동형): 텍스트 "끝." 뒤에 고아 fieldEnd 8유닛.
        use crate::model::paragraph::{CharShapeRef, OrphanFieldEnd};
        let mut para = Paragraph::default();
        para.text = "끝.".to_string();
        para.char_offsets = vec![0, 1];
        para.char_count = 11; // 텍스트 2 + fieldEnd 8 + 끝마커 1
        para.char_shapes = vec![
            CharShapeRef {
                start_pos: 0,
                char_shape_id: 3,
            },
            CharShapeRef {
                start_pos: 10,
                char_shape_id: 30,
            },
        ];
        para.orphan_field_ends = vec![OrphanFieldEnd {
            char_idx: 2,
            begin_id_ref: 1_878_228_493,
            field_id: 627_272_811,
            begin_ctrl_id: 0,
            memo_index: 0,
        }];
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:fieldEnd beginIDRef="1878228493" fieldid="627272811"/>"#),
            "고아 fieldEnd 가 attrs 와 함께 방출되어야 함: {xml}"
        );
        // 텍스트가 fieldEnd 보다 앞에 나온다 (run 말미 fieldEnd 패턴).
        let t_pos = xml.find("끝.").expect("텍스트");
        let fe_pos = xml.find("<hp:fieldEnd").expect("fieldEnd");
        assert!(t_pos < fe_pos, "텍스트가 fieldEnd 앞: {xml}");
    }

    #[test]
    fn task1556_multipara_field_parse_serialize_parse_roundtrip() {
        // 합성 다단락 필드(begin=문단0, end=문단1) → parse → serialize → re-parse.
        // end 문단의 char_count/text/char_offsets/orphan 이 보존되어야 한다 (IR diff=0).
        use crate::parser::hwpx::section::parse_hwpx_section;
        let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph"
        xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">
  <hp:p paraPrIDRef="0" styleIDRef="0">
    <hp:run charPrIDRef="0"><hp:ctrl><hp:fieldBegin id="1878228493" type="CLICK_HERE" name="본문" fieldid="627272811"/></hp:ctrl><hp:t>본문</hp:t></hp:run>
  </hp:p>
  <hp:p paraPrIDRef="0" styleIDRef="0">
    <hp:run charPrIDRef="3"><hp:t>끝.</hp:t><hp:ctrl><hp:fieldEnd beginIDRef="1878228493" fieldid="627272811"/></hp:ctrl></hp:run>
    <hp:run charPrIDRef="30"><hp:t/></hp:run>
  </hp:p>
</hs:sec>"#;
        let sec1 = parse_hwpx_section(xml).unwrap();
        let mut doc = Document::default();
        doc.sections.push(sec1.clone());
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let bytes = write_section(&sec1, &doc, 0, &mut ctx).unwrap();
        let xml2 = String::from_utf8(bytes).unwrap();
        let sec2 = parse_hwpx_section(&xml2).unwrap();

        // 두 번째 문단(고아 fieldEnd 보유) IR 보존.
        let a = &sec1.paragraphs[1];
        let b = &sec2.paragraphs[1];
        assert_eq!(b.text, a.text, "text 보존");
        assert_eq!(
            b.char_count, a.char_count,
            "char_count 보존 (8유닛 소실 없음)"
        );
        assert_eq!(b.char_offsets, a.char_offsets, "char_offsets 보존");
        assert_eq!(
            b.char_shapes
                .iter()
                .map(|c| (c.start_pos, c.char_shape_id))
                .collect::<Vec<_>>(),
            a.char_shapes
                .iter()
                .map(|c| (c.start_pos, c.char_shape_id))
                .collect::<Vec<_>>(),
            "char_shape 경계 보존"
        );
        assert_eq!(b.orphan_field_ends.len(), 1, "고아 fieldEnd 재파싱 보존");
        assert_eq!(b.orphan_field_ends[0].begin_id_ref, 1_878_228_493);
    }

    #[test]
    fn task1556_orphan_field_end_zero_fieldid_omits_attr() {
        use crate::model::paragraph::OrphanFieldEnd;
        let mut para = Paragraph::default();
        para.text = "a".to_string();
        para.char_offsets = vec![0];
        para.char_count = 10; // 1 + 8 + 1
        para.orphan_field_ends = vec![OrphanFieldEnd {
            char_idx: 1,
            begin_id_ref: 42,
            field_id: 0,
            begin_ctrl_id: 0,
            memo_index: 0,
        }];
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:fieldEnd beginIDRef="42"/>"#),
            "field_id 0 이면 fieldid 속성 생략: {xml}"
        );
    }

    /// [bookmark-hyperlink] 같은 문단 내 짝(matched) HYPERLINK fieldBegin/fieldEnd 라운드트립 —
    /// fieldEnd 자신의 fieldid(=100)가 fieldBegin 의 id(=42, beginIDRef 로 사용)와 다를 때,
    /// 과거엔 emit_field_end 가 write_field_end(f.field_id) 만 호출해 fieldid 속성을 항상
    /// 누락시켰다(고아 fieldEnd 경로만 보존해 비대칭). fr.end_field_id 를 IR 에 보존하고
    /// 되돌려 쓰면 fieldid="100" 이 살아남아야 한다.
    #[test]
    fn bookmark_hyperlink_matched_field_end_preserves_own_fieldid() {
        let mut f = Field::default();
        f.field_type = FieldType::Hyperlink;
        f.field_id = 42;
        let mut para = Paragraph::default();
        para.text = "링크".to_string();
        para.char_count = 2 + 8 + 8 + 1; // text(2) + FIELD_BEGIN(8) + FIELD_END(8) + para_end(1)
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 2,
            control_idx: 0,
            end_field_id: 100,
            inner_slot_count: 0,
        });
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:fieldEnd beginIDRef="42" fieldid="100"/>"#),
            "matched fieldEnd 는 beginIDRef(=fieldBegin id)와 별개로 자신의 fieldid 를 보존해야 함: {xml}"
        );
    }

    // ---------- #1289: Bookmark / Field dispatcher 연결 ----------

    use crate::model::control::{Bookmark, Control, Field, FieldType};
    use crate::model::paragraph::FieldRange;

    #[test]
    fn task1289_bookmark_emits_ctrl_wrapper() {
        // Bookmark는 슬롯 시스템이 위치를 추적할 수 없으므로 문단 시작에 배치한다.
        let mut para = Paragraph::default();
        para.text = "hello".to_string();
        para.char_count = 6; // "hello"(5) + para_end(1)
        para.controls.push(Control::Bookmark(Bookmark {
            name: "test_bm".to_string(),
        }));
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:ctrl><hp:bookmark name="test_bm"/></hp:ctrl>"#),
            "bookmark must be wrapped in <hp:ctrl>: {}",
            &xml[..300.min(xml.len())]
        );
        assert!(xml.contains("hello"), "text must still be present");
    }

    #[test]
    fn task1391_memo_field_emits_parameters_and_sublist() {
        // MEMO 필드: parameters verbatim + subList 본문 방출, start/end 태그.
        let mut f = Field::default();
        f.field_type = FieldType::Memo;
        f.field_id = 7;
        f.raw_parameters_xml =
            Some(r#"<hp:parameters cnt="1" name=""><hp:stringParam name="ID">memo1</hp:stringParam></hp:parameters>"#.to_string());
        let mut memo_para = Paragraph::default();
        memo_para.text = "메모 본문".to_string();
        f.memo_paragraphs.push(memo_para);

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        para.char_count = 18; // fieldBegin(8) + x(1) + fieldEnd(8) + end(1)
        para.char_offsets = vec![8];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 1,
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:stringParam name="ID">memo1</hp:stringParam>"#),
            "parameters verbatim 방출: {xml}"
        );
        assert!(xml.contains("<hp:t>메모 본문</hp:t>"), "메모 본문 방출");
        assert!(
            xml.contains("</hp:fieldBegin>"),
            "자식 있으면 start/end 태그 (자기닫힘 금지)"
        );
        // 순서: parameters → subList
        let pp = xml.find("<hp:parameters").unwrap();
        let sl = xml.find("<hp:subList").unwrap();
        assert!(pp < sl, "parameters 가 subList 보다 먼저");
    }

    #[test]
    fn memo_vertical_text_direction_roundtrips() {
        // [#task-m100] 세로쓰기 MEMO subList 는 파싱 시 textDirection="VERTICAL" 을
        // 보존해야 하며, 재직렬화 시 하드코딩된 "HORIZONTAL" 로 뒤집히면 안 된다.
        let mut f = Field::default();
        f.field_type = FieldType::Memo;
        f.field_id = 9;
        f.memo_text_direction = Some("VERTICAL".to_string());
        let mut memo_para = Paragraph::default();
        memo_para.text = "메모".to_string();
        f.memo_paragraphs.push(memo_para);

        let mut para = Paragraph::default();
        para.text = "x".to_string();
        para.char_count = 18;
        para.char_offsets = vec![8];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 1,
            control_idx: 0,
            end_field_id: 0,
            inner_slot_count: 0,
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:subList id="" textDirection="VERTICAL""#),
            "세로쓰기 메모 subList 의 textDirection 보존: {xml}"
        );
    }

    #[test]
    fn task1391_field_without_params_keeps_empty_tag() {
        // parameters/memo 없는 필드는 기존 empty_tag 자기닫힘 유지 (회귀 방지).
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 5;
        let mut para = Paragraph::default();
        para.text = "y".to_string();
        para.char_count = 18;
        para.char_offsets = vec![8];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 1,
            control_idx: 0,
            ..Default::default()
        });
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            !xml.contains("</hp:fieldBegin>"),
            "자식 없으면 자기닫힘 유지: {xml}"
        );
    }

    #[test]
    fn task1289_field_begin_end_roundtrip() {
        // HWPX 파서가 생성하는 구조 시뮬레이션:
        // fieldBegin(8 cu) + "hello"(5 cu) + fieldEnd(8 cu) + para_end(1 cu) = 22
        // para.text 에는 "hello"만 있고 char_offsets 가 +8 오프셋으로 시작한다.
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 99;

        let mut para = Paragraph::default();
        para.text = "hello".to_string();
        para.char_count = 22;
        para.char_offsets = vec![8, 9, 10, 11, 12];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 5,
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:ctrl><hp:fieldBegin id="99" type="CLICK_HERE""#),
            "fieldBegin must be emitted: {}",
            &xml[..500.min(xml.len())]
        );
        assert!(
            xml.contains(r#"<hp:ctrl><hp:fieldEnd beginIDRef="99"/></hp:ctrl>"#),
            "fieldEnd must be emitted: {}",
            &xml[..500.min(xml.len())]
        );
        assert!(xml.contains("hello"), "field text must be present");

        // 순서 검증: fieldBegin < "hello" < fieldEnd
        let begin_pos = xml.find("fieldBegin").expect("fieldBegin");
        let hello_pos = xml.find("hello").expect("hello");
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        assert!(begin_pos < hello_pos, "fieldBegin must precede text");
        assert!(hello_pos < end_pos, "text must precede fieldEnd");
    }

    #[test]
    fn task1289_field_end_at_para_boundary() {
        // end_char_idx == text.len() 인 경우: 루프 내 감지 불가 → 루프 후 처리
        let mut f = Field::default();
        f.field_type = FieldType::Date;
        f.field_id = 7;

        let mut para = Paragraph::default();
        para.text = "abc".to_string();
        para.char_count = 20; // fieldBegin(8) + "abc"(3) + fieldEnd(8) + para_end(1)
        para.char_offsets = vec![8, 9, 10];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 3, // == text.len() → 루프 후 처리 경로
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:fieldEnd beginIDRef="7"/>"#),
            "fieldEnd must be emitted even when end_char_idx == text.len(): {}",
            &xml[..400.min(xml.len())]
        );
    }

    // ---------- #1298: 0-length field range fieldBegin/fieldEnd 인터리빙 ----------

    #[test]
    fn task1298_zero_length_field_at_para_start() {
        // 0-length 필드 at position 0 (start=0, end=0):
        // HWP stream: fieldBegin(8cu) fieldEnd(8cu) "hello"(5cu) para_end(1cu) = 22cu
        // char_offsets: [16, 17, 18, 19, 20] (fieldBegin+fieldEnd 갭 16 이후 텍스트)
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 55;

        let mut para = Paragraph::default();
        para.text = "hello".to_string();
        para.char_count = 22;
        para.char_offsets = vec![16, 17, 18, 19, 20];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 0, // 0-length
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:ctrl><hp:fieldBegin id="55""#),
            "fieldBegin must be emitted: {}",
            &xml[..500.min(xml.len())]
        );
        assert!(
            xml.contains(r#"<hp:ctrl><hp:fieldEnd beginIDRef="55"/></hp:ctrl>"#),
            "fieldEnd must be emitted: {}",
            &xml[..500.min(xml.len())]
        );
        assert!(xml.contains("hello"), "text must still be present");

        // 순서 검증: fieldBegin < fieldEnd < "hello"
        let begin_pos = xml.find("fieldBegin").expect("fieldBegin");
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        let hello_pos = xml.find("hello").expect("hello");
        assert!(begin_pos < end_pos, "fieldBegin must precede fieldEnd");
        assert!(
            end_pos < hello_pos,
            "fieldEnd must precede text for 0-length field"
        );
    }

    #[test]
    fn task1298_zero_length_field_mid_text() {
        // 0-length 필드 at position 3 (start=3, end=3), text="ABCDE":
        // HWP stream: A B C fieldBegin(8cu) fieldEnd(8cu) D E para_end
        // char_offsets: [0,1,2, 19,20] (D 앞에 16cu 갭)
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 77;

        let mut para = Paragraph::default();
        para.text = "ABCDE".to_string();
        para.char_count = 5 + 8 + 8 + 1; // text + fieldBegin + fieldEnd + para_end
        para.char_offsets = vec![0, 1, 2, 19, 20];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 3,
            end_char_idx: 3, // 0-length mid-text
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains("ABCDE") || (xml.contains("ABC") && xml.contains("DE")),
            "all text must be present: {}",
            &xml[..500.min(xml.len())]
        );

        // 순서 검증: "ABC" < fieldBegin < fieldEnd < "DE"
        let begin_pos = xml.find("fieldBegin").expect("fieldBegin");
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        // ABC는 fieldBegin 앞에
        let abc_pos = xml.find('A').expect("A");
        // DE는 fieldEnd 뒤에 (fieldEnd 태그 닫힘 이후)
        let field_end_close =
            xml.find("fieldEnd").unwrap() + xml[xml.find("fieldEnd").unwrap()..].find('>').unwrap();
        let de_pos = xml[field_end_close..]
            .find('D')
            .map(|p| p + field_end_close)
            .expect("D after fieldEnd");

        assert!(abc_pos < begin_pos, "ABC must precede fieldBegin");
        assert!(begin_pos < end_pos, "fieldBegin must precede fieldEnd");
        assert!(end_pos < de_pos, "fieldEnd must precede DE");
    }

    // ---------- #1321: 빈 문단(text == "")의 0-length field 순서 ----------

    #[test]
    fn task1321_zero_length_field_in_empty_paragraph() {
        // 빈 문단(text="")에 0-length 필드:
        // HWP stream: fieldBegin(8cu) + fieldEnd(8cu) + para_end(1cu) = 17cu
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 99;

        let mut para = Paragraph::default();
        para.text = "".to_string();
        para.char_count = 17;
        para.char_offsets = vec![];
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 0,
            control_idx: 0,
            ..Default::default()
        });

        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();

        assert!(
            xml.contains(r#"<hp:fieldBegin id="99""#),
            "fieldBegin must be emitted: {}",
            &xml[..400.min(xml.len())]
        );
        assert!(
            xml.contains(r#"<hp:fieldEnd beginIDRef="99"/>"#),
            "fieldEnd must be emitted: {}",
            &xml[..400.min(xml.len())]
        );

        let begin_pos = xml.find("fieldBegin").expect("fieldBegin");
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        assert!(
            begin_pos < end_pos,
            "빈 문단에서도 fieldBegin이 fieldEnd보다 앞에 와야 한다: {}",
            &xml[..400.min(xml.len())]
        );
    }

    // ---------- #1407: newNum(텍스트 끝 슬롯)이 fieldEnd 갭을 가로채지 않음 ----------

    #[test]
    fn task1407_field_end_not_stolen_by_newnum_slot() {
        // 143E 문단 0.14 모델: 하이퍼링크 필드가 "ABC"를 래핑하고 그 뒤 " DEF" 텍스트,
        // newNum 은 텍스트 끝. char_offsets 는 head(secPr) 16유닛 뒤로 시작:
        // fieldBegin(8) "ABC"(3) fieldEnd(8) " DEF"(4) newNum(8) end(1).
        // 핵심: fieldEnd(텍스트 중간 갭)가 후속 슬롯(newNum)에 가로채이면 " DEF"가
        // +8 밀린다. render_runs 방출 XML 의 컨트롤·텍스트 순서로 봉인.
        let mut f = Field::default();
        f.field_type = FieldType::Hyperlink;
        f.field_id = 42;

        let mut nn = NewNumber::default();
        nn.number = 2;
        nn.number_type = AutoNumberType::Page;

        let mut para = Paragraph::default();
        para.text = "ABC DEF".to_string();
        para.char_count = 8 + 3 + 8 + 4 + 8 + 1;
        para.char_offsets = vec![8, 9, 10, 19, 20, 21, 22];
        para.controls.push(Control::Field(f));
        para.controls.push(Control::NewNumber(nn));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 3, // "ABC" 래핑
            control_idx: 0,
            ..Default::default()
        });

        let xml = runs_of(&para);

        let begin_pos = xml.find("fieldBegin").expect("fieldBegin");
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        let newnum_pos = xml.find("newNum").expect("newNum");
        // " DEF" 텍스트(<hp:t> DEF</hp:t>) 위치 — fieldEnd 닫힘 뒤의 'DEF'.
        let after_end = end_pos + xml[end_pos..].find('>').unwrap();
        let def_pos = xml[after_end..]
            .find("DEF")
            .map(|p| p + after_end)
            .expect("DEF");

        assert!(begin_pos < end_pos, "fieldBegin이 fieldEnd보다 앞: {xml}");
        assert!(
            end_pos < def_pos,
            "fieldEnd 가 ' DEF' 텍스트보다 앞 (갭이 가로채이지 않음): {xml}"
        );
        assert!(
            def_pos < newnum_pos,
            "newNum 은 텍스트 끝 — ' DEF' 뒤에 와야 한다 (#1407 회귀 가드): {xml}"
        );
    }

    // ---------- #1378: char_shapes 경계 기준 다중 run 분할 ----------

    fn cs(start_pos: u32, char_shape_id: u32) -> CharShapeRef {
        CharShapeRef {
            start_pos,
            char_shape_id,
        }
    }

    fn runs_of(para: &Paragraph) -> String {
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        render_runs(para, &mut ctx).0
    }

    /// [#4902] 한 자리에서 이 문단의 `fieldBegin` 과 (앞 문단 필드를 닫는) 고아 `fieldEnd`
    /// 가 겹치면 **begin 이 먼저** 나가야 한다.
    ///
    /// 한컴 원본 PARA_TEXT 는 언제나 `begin(0x03) → end(0x04) → end(0x04)`(LIFO) 순이다
    /// (08368 실측). 고아를 앞세우면 한글은 짝 없는 `fieldEnd` 를 만나 그 지점에서 구역
    /// 파싱을 포기하고 이후 본문·개체를 통째로 버린다 — 실측 19쪽 35,205자 → 2쪽 7,838자,
    /// 개체 45→1. `beginIDRef` 값을 유효한 id 로 고쳐도 복원되지 않고, 순서를 바로잡으면
    /// 100% 복원된다.
    ///
    /// [#5252] 그 순서 계약은 **여는 짝이 있는** 고아에만 해당한다. `link_orphan_field_ends`
    /// 가 섹션을 훑고도 `begin_id_ref` 를 못 채웠다면 문서 어디에도 짝이 없다는 뜻이라
    /// 아예 방출하지 않는다 — 순서로는 막을 수 없는 경우다(07276 h2x 223→137쪽).
    /// 한 시험에서 두 계약을 함께 지킨다.
    #[test]
    fn issue4902_field_begin_precedes_orphan_field_end_at_same_slot() {
        use crate::model::control::{Field, FieldType};
        use crate::model::paragraph::OrphanFieldEnd;

        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let _ = &mut ctx;

        // 08368 문단 32 동형: 8유닛 슬롯 3개(begin·짝 end·고아 end) 뒤에 텍스트.
        let mut para = Paragraph::default();
        para.text = "해도".to_string();
        para.char_offsets = vec![24, 25];
        para.char_count = 24 + 2 + 1;
        para.controls = vec![Control::Field(Field {
            field_type: FieldType::ClickHere,
            field_id: 1_867_945_538,
            ctrl_id: crate::parser::tags::FIELD_CLICKHERE,
            ..Default::default()
        })];
        para.field_ranges = vec![FieldRange {
            start_char_idx: 0,
            end_char_idx: 0,
            control_idx: 0,
            end_field_id: 1_867_945_538,
            inner_slot_count: 0,
        }];
        // ① 여는 짝이 **있는** 고아 — 종전 계약대로 방출하되 begin 이 먼저다.
        para.orphan_field_ends = vec![OrphanFieldEnd {
            char_idx: 0,
            begin_id_ref: 1_867_945_539,
            field_id: 0,
            begin_ctrl_id: crate::parser::tags::FIELD_CLICKHERE,
            memo_index: 0,
        }];

        let runs = runs_of(&para);
        let begin = runs.find("<hp:fieldBegin").expect("fieldBegin 방출");
        let orphan = runs
            .find(r#"<hp:fieldEnd beginIDRef="1867945539""#)
            .expect("여는 짝이 있는 고아 fieldEnd 는 방출되어야 한다");
        assert!(
            begin < orphan,
            "고아 fieldEnd 가 짝 fieldBegin 보다 앞서면 한글이 본문을 버린다:\n{runs}"
        );

        // ② [#5252] 여는 짝을 **못 찾은** 고아는 방출하지 않는다. 한글은 열려 있지 않은
        //    필드를 닫는 fieldEnd 를 버리고, 그러면 문단 축만 8유닛 짧아져 원본
        //    linesegarray 가 축을 넘겨 그 문단부터 본문이 통째로 폐기된다.
        para.orphan_field_ends = vec![OrphanFieldEnd {
            char_idx: 0,
            begin_id_ref: 0,
            field_id: 0,
            begin_ctrl_id: 0,
            memo_index: 0,
        }];
        let runs = runs_of(&para);
        assert!(
            !runs.contains(r#"<hp:fieldEnd beginIDRef="0""#),
            "짝을 못 찾은 고아 fieldEnd 는 내보내면 안 된다:\n{runs}"
        );
        assert!(
            runs.contains("<hp:fieldBegin"),
            "짝 있는 필드는 그대로 방출되어야 한다:\n{runs}"
        );
    }

    /// [#1948] 반면 갭을 다투는 슬롯이 **표 등 다른 컨트롤**이면 종전대로 고아 fieldEnd 가
    /// 먼저다 — 그러지 않으면 말미 슬롯이 고아의 8유닛 갭을 가로채 `char_offsets` 가 밀린다.
    #[test]
    fn issue1948_orphan_field_end_still_precedes_non_field_slot() {
        use crate::model::paragraph::OrphanFieldEnd;

        let mut para = Paragraph::default();
        para.text = "가".to_string();
        para.char_offsets = vec![16];
        para.char_count = 16 + 1 + 1;
        para.controls = vec![Control::Table(Box::default())];
        para.orphan_field_ends = vec![OrphanFieldEnd {
            char_idx: 0,
            begin_id_ref: 2_031_845_287,
            field_id: 0,
            begin_ctrl_id: crate::parser::tags::FIELD_CLICKHERE,
            memo_index: 0,
        }];

        let runs = runs_of(&para);
        let orphan = runs.find("<hp:fieldEnd").expect("고아 fieldEnd 방출");
        let table = runs.find("<hp:tbl").expect("표 방출");
        assert!(
            orphan < table,
            "표 슬롯이 고아 fieldEnd 의 갭을 가로채면 char_offsets 가 밀린다:\n{runs}"
        );
    }

    /// [#4778] 위치 축이 무너진 문단(파서 미수용 8유닛 슬롯 — 차례표지 0x0008 등)의
    /// 저장 lineseg 는 방출하지 않는다. textpos 사다리와 어긋난 lineseg 를 한글 2022 가
    /// 만나면 그 문단부터 문서 끝까지 본문을 폐기한다(성년후견 h2x -112,075자 실측,
    /// lineseg 억제만으로 전량 회복).
    #[test]
    fn issue4778_broken_position_axis_suppresses_stored_linesegs() {
        use crate::model::control::{Bookmark, PageNumberPos};
        use crate::model::paragraph::LineSeg;
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);

        // 성년후견 #156 동형: 텍스트 앞에 8유닛 슬롯 갭(차례표지 자리)이 있는데
        // controls 는 비어 있다 — char_count/char_offsets 만 슬롯을 주장한다.
        let mut broken = Paragraph::default();
        broken.text = "다. 표제".to_string();
        broken.char_offsets = (0..broken.text.chars().count() as u32)
            .map(|i| 8 + i)
            .collect();
        broken.char_count = 8 + broken.text.chars().count() as u32 + 1;
        broken.line_segs = vec![LineSeg {
            line_height: 1100,
            ..Default::default()
        }];
        let (_, linesegs, _) = render_paragraph_parts(&broken, 0, &mut ctx);
        assert!(
            linesegs.is_empty(),
            "축 붕괴 문단은 저장 lineseg 를 방출하면 안 된다(한글 본문 폐기 트리거): {linesegs}"
        );

        // [#3518] HWP3 가 char_count 만 부풀린 문단: 본문은 0부터 연속이고
        // 컨트롤은 말미. mismatch 여도 글자 좌표가 안 밀리므로 저장 lineseg 유지.
        let mut hwp3_inflated = Paragraph::default();
        hwp3_inflated.text = "1.추진목적".to_string();
        hwp3_inflated.char_offsets = (0..52).collect();
        hwp3_inflated.char_count = 53;
        hwp3_inflated.controls.push(Control::Bookmark(Bookmark {
            name: "bm".to_string(),
        }));
        hwp3_inflated
            .controls
            .push(Control::PageNumberPos(PageNumberPos::default()));
        hwp3_inflated.line_segs = vec![LineSeg {
            line_height: 1600,
            line_spacing: 960,
            ..Default::default()
        }];
        let (_, linesegs, _) = render_paragraph_parts(&hwp3_inflated, 0, &mut ctx);
        assert!(
            linesegs.contains("<hp:lineseg"),
            "본문 좌표가 연속인 HWP3 문단은 mismatch 여도 저장 lineseg 를 유지해야 한다: {linesegs}"
        );

        // 대조군: 축이 온전한 문단은 종전대로 저장 lineseg 를 방출한다.
        let mut intact = Paragraph::default();
        intact.text = "본문".to_string();
        intact.char_offsets = (0..intact.text.chars().count() as u32).collect();
        intact.char_count = intact.text.chars().count() as u32 + 1;
        intact.line_segs = vec![LineSeg {
            line_height: 1100,
            ..Default::default()
        }];
        let (_, linesegs, _) = render_paragraph_parts(&intact, 0, &mut ctx);
        assert!(
            linesegs.contains("<hp:lineseg"),
            "온전한 문단의 저장 lineseg 보존이 깨졌다"
        );
    }

    #[test]
    fn task1378_two_run_split_mid_text() {
        // 경계가 텍스트 중간 — 텍스트 분할 (경계 케이스 2)
        let mut para = Paragraph::default();
        para.text = "abcdef".to_string();
        para.char_shapes = vec![cs(0, 1), cs(3, 2)];
        assert_eq!(
            runs_of(&para),
            r#"<hp:run charPrIDRef="1"><hp:t>abc</hp:t></hp:run><hp:run charPrIDRef="2"><hp:t>def</hp:t></hp:run>"#
        );
    }

    #[test]
    fn task1378_boundary_at_slot_position_slot_in_new_run() {
        // 경계와 컨트롤 슬롯이 같은 위치 — 경계 먼저 cut, 컨트롤은 새 run 소속 (경계 케이스 1)
        // 스트림: "ab"(0..2) + equation 슬롯(2..10) + "cd"(10..12), 경계 pos=2
        let mut para = Paragraph::default();
        para.text = "abcd".to_string();
        para.char_offsets = vec![0, 1, 10, 11];
        para.char_count = 13; // 4 + 8(슬롯) + 1
        para.controls.push(Control::Equation(Box::default()));
        para.char_shapes = vec![cs(0, 1), cs(2, 2)];
        let xml = runs_of(&para);
        assert!(
            xml.starts_with(r#"<hp:run charPrIDRef="1"><hp:t>ab</hp:t></hp:run><hp:run charPrIDRef="2"><hp:equation"#),
            "슬롯 위치의 경계는 슬롯보다 먼저 적용돼야 한다: {}",
            &xml[..200.min(xml.len())]
        );
        let run2 = xml.find(r#"<hp:run charPrIDRef="2">"#).unwrap();
        let cd = xml.find("<hp:t>cd</hp:t>").expect("cd 텍스트");
        assert!(run2 < cd, "cd 는 새 run 소속이어야 한다");
    }

    #[test]
    fn task1378_boundary_between_slot_and_text() {
        // 슬롯 이후 텍스트 중간 경계 — 슬롯은 이전 run, 분할은 텍스트에서
        // 스트림: equation 슬롯(0..8) + "ab"(8..10) + "cd"(10..12), 경계 pos=10
        let mut para = Paragraph::default();
        para.text = "abcd".to_string();
        para.char_offsets = vec![8, 9, 10, 11];
        para.char_count = 13;
        para.controls.push(Control::Equation(Box::default()));
        para.char_shapes = vec![cs(0, 1), cs(10, 2)];
        let xml = runs_of(&para);
        let run1_end = xml.find("</hp:run>").unwrap();
        let eq = xml.find("<hp:equation").expect("equation");
        let ab = xml.find("<hp:t>ab</hp:t>").expect("ab");
        assert!(
            eq < run1_end && ab < run1_end,
            "equation 과 ab 는 첫 run 소속"
        );
        assert!(
            xml.ends_with(r#"<hp:run charPrIDRef="2"><hp:t>cd</hp:t></hp:run>"#),
            "cd 만 새 run 으로 분할: {}",
            xml
        );
    }

    #[test]
    fn issue_3739_consecutive_same_id_boundary_preserved() {
        // 같은 ID여도 start_pos는 HWP PARA_CHAR_SHAPE 의 보존 대상이다.
        let mut para = Paragraph::default();
        para.text = "abcdef".to_string();
        para.char_shapes = vec![cs(0, 5), cs(2, 5), cs(4, 6)];
        let xml = runs_of(&para);
        assert_eq!(
            xml,
            r#"<hp:run charPrIDRef="5"><hp:t>ab</hp:t></hp:run><hp:run charPrIDRef="5"><hp:t>cd</hp:t></hp:run><hp:run charPrIDRef="6"><hp:t>ef</hp:t></hp:run>"#,
            "동일 id 경계 (2,5)도 별도 run으로 출력해야 한다"
        );
    }

    #[test]
    fn task1378_tab_and_linebreak_in_split_runs() {
        // 탭(8 유닛)/lineBreak 를 포함한 run 분할 (경계 케이스 4)
        // 위치: a=0, \t=1..9, b=9, \n=10, c=11 — 경계 pos=9
        let mut para = Paragraph::default();
        para.text = "a\tb\nc".to_string();
        para.char_shapes = vec![cs(0, 1), cs(9, 2)];
        let xml = runs_of(&para);
        assert_eq!(
            xml,
            concat!(
                r#"<hp:run charPrIDRef="1"><hp:t>a<hp:tab width="0" leader="0" type="1"/></hp:t></hp:run>"#,
                r#"<hp:run charPrIDRef="2"><hp:t>b<hp:lineBreak/>c</hp:t></hp:run>"#
            )
        );
    }

    #[test]
    fn task1378_empty_paragraph_single_run_id_zero() {
        // [#1592 갱신] 완전 빈 문단(text="", char_shapes=[], 컨트롤 없음)은 run 을 방출하지
        // 않는다. char_shapes=[] 는 "원본에 <hp:run> 없음"을 의미하므로(빈 run 이 있었다면
        // 파서가 [(0,0)] 을 산출), run 을 추가하면 재파싱 시 spurious (0,0) 가 생긴다(#1592).
        // 종전 #1378 은 빈 run(id 0)을 방출했으나, 이는 run 없던 빈 문단에 entry 를 가공했다.
        let para = Paragraph::default();
        assert_eq!(runs_of(&para), "");
    }

    #[test]
    fn task1378_field_end_stays_in_previous_run() {
        // 필드 begin/end 와 경계 교차 (경계 케이스 6)
        // 스트림: fieldBegin(0..8) + "abc"(8..11) + fieldEnd(11..19) + "de"(19..21)
        // 경계 pos=19 — fieldEnd 는 이전 run, "de" 는 새 run
        let mut f = Field::default();
        f.field_type = FieldType::ClickHere;
        f.field_id = 11;
        let mut para = Paragraph::default();
        para.text = "abcde".to_string();
        para.char_offsets = vec![8, 9, 10, 19, 20];
        para.char_count = 22;
        para.controls.push(Control::Field(f));
        para.field_ranges.push(FieldRange {
            start_char_idx: 0,
            end_char_idx: 3,
            control_idx: 0,
            ..Default::default()
        });
        para.char_shapes = vec![cs(0, 1), cs(19, 2)];
        let xml = runs_of(&para);
        let end_pos = xml.find("fieldEnd").expect("fieldEnd");
        let run2 = xml
            .find(r#"<hp:run charPrIDRef="2">"#)
            .expect("두 번째 run");
        assert!(
            end_pos < run2,
            "fieldEnd 는 이전 run 소속이어야 한다: {}",
            xml
        );
        assert!(
            xml.ends_with(r#"<hp:run charPrIDRef="2"><hp:t>de</hp:t></hp:run>"#),
            "de 는 새 run 소속이어야 한다: {}",
            xml
        );
    }

    #[test]
    fn task1378_trailing_boundary_emits_empty_run() {
        // 콘텐츠 끝 이후 경계 — 빈 run(<hp:t></hp:t>)으로 entry 보존 (규칙 5)
        let mut para = Paragraph::default();
        para.text = "abc".to_string();
        para.char_shapes = vec![cs(0, 1), cs(3, 2)];
        assert_eq!(
            runs_of(&para),
            r#"<hp:run charPrIDRef="1"><hp:t>abc</hp:t></hp:run><hp:run charPrIDRef="2"><hp:t></hp:t></hp:run>"#
        );
    }

    #[test]
    fn task1378_trailing_slot_in_new_run() {
        // 문단 끝 슬롯 위치의 경계 — trailing 슬롯도 새 run 소속 (규칙 1)
        // 스트림: "abc"(0..3) + equation 슬롯(3..11), 경계 pos=3
        let mut para = Paragraph::default();
        para.text = "abc".to_string();
        para.char_offsets = vec![0, 1, 2];
        para.char_count = 12; // 3 + 8(슬롯) + 1
        para.controls.push(Control::Equation(Box::default()));
        para.char_shapes = vec![cs(0, 1), cs(3, 2)];
        let xml = runs_of(&para);
        assert!(
            xml.starts_with(
                r#"<hp:run charPrIDRef="1"><hp:t>abc</hp:t></hp:run><hp:run charPrIDRef="2"><hp:equation"#
            ),
            "trailing 슬롯은 경계 적용 후 새 run 에 들어가야 한다: {}",
            &xml[..200.min(xml.len())]
        );
    }

    #[test]
    fn task1378_section_first_paragraph_secpr_run_id_follows_first_cs() {
        // 섹션 첫 문단 — secPr run id 와 텍스트 run id 의 dedup 상호작용 (경계 케이스 7)
        let mut para = Paragraph::default();
        para.text = "hi".to_string();
        para.char_shapes = vec![cs(0, 7)];
        let (doc, section) = make_doc_with_paragraph(para);
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let xml = String::from_utf8(write_section(&section, &doc, 0, &mut ctx).unwrap()).unwrap();
        assert!(
            xml.contains(r#"<hp:run charPrIDRef="7"><hp:secPr "#),
            "secPr run id 는 첫 텍스트 run id 와 일치해야 한다 (재파싱 시 (0,0) 오염 방지)"
        );
        assert!(
            xml.contains(r#"<hp:run charPrIDRef="7"><hp:t>hi</hp:t></hp:run>"#),
            "텍스트 run 은 완전한 run 시퀀스로 치환돼야 한다"
        );
        assert!(
            !xml.contains(r#"<hp:run charPrIDRef="0">"#),
            "템플릿의 charPrIDRef=0 run 이 남아있으면 안 된다: {}",
            xml
        );
    }

    #[test]
    fn task1378_serialize_parse_roundtrip_preserves_char_shapes() {
        // serialize → parse 왕복 후 본문 char_shapes 시퀀스 보존.
        // 파서 정합 IR 로 구성: 섹션 첫 문단은 secPr(8)+colPr(8) 가 위치 축을 16 만큼
        // 선점하므로 char_offsets 가 16 부터 시작하고, 첫 entry 는 secPr run 시작(0)에
        // 기록된다 (stage1 양상 ② 메커니즘).
        use crate::model::style::CharShape;

        // 첫 문단: "abcdef", 경계 1개 — 원본 파스 결과는 [(0,1),(19,2)]
        let mut p0 = Paragraph::default();
        p0.text = "abcdef".to_string();
        p0.char_offsets = vec![16, 17, 18, 19, 20, 21];
        p0.char_count = 23;
        p0.char_shapes = vec![cs(0, 1), cs(19, 2)];

        // 추가 문단: 위치 축이 0 부터 — [(0,1),(3,2)]
        let mut p1 = Paragraph::default();
        p1.text = "abcdef".to_string();
        p1.char_offsets = vec![0, 1, 2, 3, 4, 5];
        p1.char_count = 7;
        p1.char_shapes = vec![cs(0, 1), cs(3, 2)];

        let mut section = Section::default();
        section.paragraphs.push(p0);
        section.paragraphs.push(p1);
        let mut doc = Document::default();
        doc.doc_info.char_shapes = vec![
            CharShape::default(),
            CharShape::default(),
            CharShape::default(),
        ];
        doc.sections.push(section);

        let bytes = crate::serializer::hwpx::serialize_hwpx(&doc).expect("serialize");
        let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
        let shapes_of = |i: usize| -> Vec<(u32, u32)> {
            doc2.sections[0].paragraphs[i]
                .char_shapes
                .iter()
                .map(|r| (r.start_pos, r.char_shape_id))
                .collect()
        };
        assert_eq!(shapes_of(0), vec![(0, 1), (19, 2)], "섹션 첫 문단");
        assert_eq!(shapes_of(1), vec![(0, 1), (3, 2)], "추가 문단");
    }

    // ---------- #1584: 본문 인라인 ColumnDef 드롭 회귀 가드 ----------

    #[test]
    fn task1584_body_first_para_two_columndefs_roundtrip() {
        // 본문 첫 문단에 ColumnDef 2개(섹션 단 정의 + 인라인 단 정의).
        // 섹션 템플릿은 첫 ColumnDef 1개만 흡수하고, 2번째 인라인 ColumnDef 는
        // 본문 인라인 슬롯에서 제외되어 드롭된다(controls 6→5 양상).
        // 수정 전: reparse 후 ColumnDef 1개만 → RED. 수정 후: 2개 보존 → GREEN.
        let mut p0 = Paragraph::default();
        p0.controls.push(Control::ColumnDef(ColumnDef::default()));
        p0.controls.push(Control::ColumnDef(ColumnDef::default()));

        let mut section = Section::default();
        section.paragraphs.push(p0);
        let mut doc = Document::default();
        doc.sections.push(section);

        let bytes = crate::serializer::hwpx::serialize_hwpx(&doc).expect("serialize");
        let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
        let coldef_count = doc2.sections[0].paragraphs[0]
            .controls
            .iter()
            .filter(|c| matches!(c, Control::ColumnDef(_)))
            .count();
        assert_eq!(
            coldef_count, 2,
            "본문 첫 문단의 ColumnDef 2개가 roundtrip 후 모두 보존돼야 한다 (템플릿1 + 인라인1): {coldef_count}"
        );
    }

    #[test]
    fn page_starts_on_odd_survives_hwpx_roundtrip() {
        // pageStartsOn(홀수 시작)이 HWPX 왕복에서 보존돼야 한다. 종전엔 파서 미독 +
        // serializer 의 pageStartsOn="BOTH" 고정으로 page_num_type 이 0 으로 유실됐다.
        let mut section = Section::default();
        section.section_def.page_num_type = 1; // 홀수 시작
        section.section_def.page_num = 1;
        section.paragraphs.push(Paragraph::default());
        let mut doc = Document::default();
        doc.sections.push(section);

        let bytes = crate::serializer::hwpx::serialize_hwpx(&doc).expect("serialize");
        let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("parse");
        assert_eq!(
            doc2.sections[0].section_def.page_num_type, 1,
            "홀수 쪽 시작(pageStartsOn=ODD)이 왕복에서 보존돼야 함"
        );
    }

    // ---------- #1596: generic-shape 지오메트리 직렬화 ----------

    #[test]
    fn task1596_polygon_geometry_serialized() {
        // [#1596] polygon 의 꼭짓점(hc:pt)·테두리(lineShape)·그림자(shadow)가 방출돼야 한다.
        // render_common_shape_xml 이 종전 이들을 드롭 → 도형 형상 소실 → 페이지 붕괴(#1589 잔여).
        use crate::model::shape::PolygonShape;
        use crate::model::Point;
        let mut poly = PolygonShape::default();
        poly.points = vec![
            Point { x: 0, y: 0 },
            Point { x: 100, y: 0 },
            Point { x: 100, y: 100 },
        ];
        poly.drawing.border_line.width = 50;
        poly.drawing.shadow_type = 1;
        let mut ctx = SerializeContext::collect_from_document(&Document::default());
        let xml = render_shape(&ShapeObject::Polygon(poly), &mut ctx);
        assert!(xml.contains("<hc:pt "), "폴리곤 꼭짓점(hc:pt) 방출: {xml}");
        assert!(xml.contains("<hp:lineShape"), "lineShape 방출: {xml}");
        assert!(xml.contains("<hp:shadow"), "shadow 방출: {xml}");
    }
}