rhwp 0.9.1

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

use crate::document_core::DocumentCore;
use crate::error::HwpError;
use crate::model::control::{Control, Field, FieldType};
use crate::model::event::DocumentEvent;
use crate::model::paragraph::{FieldRange, Paragraph};
use crate::parser::tags;

/// 필드 위치 정보
#[derive(Debug, Clone)]
pub struct FieldLocation {
    pub section_index: usize,
    pub para_index: usize,
    /// 표/글상자 내 필드인 경우 중첩 경로
    pub nested_path: Vec<NestedEntry>,
}

/// 중첩 경로 항목 (표 셀 또는 글상자 내부)
#[derive(Debug, Clone)]
pub enum NestedEntry {
    /// 표 셀: (control_index, cell_index, para_index)
    TableCell {
        control_index: usize,
        cell_index: usize,
        para_index: usize,
    },
    /// 글상자: (control_index, para_index)
    TextBox {
        control_index: usize,
        para_index: usize,
    },
}

/// 필드 검색 결과
#[derive(Debug)]
pub struct FieldInfo {
    pub field: Field,
    pub location: FieldLocation,
    /// 필드 범위 내 텍스트 (빈 필드이면 빈 문자열)
    pub value: String,
    /// field_ranges에서의 인덱스
    pub field_range_index: usize,
    /// 필드가 속한 리스트 아이디 (한글 커서 좌표계 — [`ListEntry`] 참고)
    pub list_id: u32,
    /// 그 리스트 안에서의 문단 번호
    pub para_in_list: usize,
    /// 문단 안에서의 시작 위치 (코드 유닛). 셀 필드는 0.
    pub start_pos: usize,
    /// 문단 안에서의 끝 위치 (코드 유닛). 셀 필드는 0.
    pub end_pos: usize,
}

/// 본문(루트) 리스트의 아이디.
pub const ROOT_LIST_ID: u32 = 0;

/// 서브리스트(표 셀·글상자)가 받는 첫 아이디.
///
/// 1 번은 문서마다 하나 비어 있다 — 한글2022 실측으로 세 문서에서 모두 그랬고, 그 자리에
/// 무엇이 있는지는 아직 모른다(바탕쪽으로 짐작만 한다). 규명 전까지 상수로 둔다.
pub const FIRST_SUB_LIST_ID: u32 = 2;

/// 서브리스트 한 칸 — 한글 `GetPos`/`SetPos` 의 `list` 좌표계.
///
/// 번호는 **문서 순서 깊이 우선**으로 붙는다: 셀에 번호를 준 **뒤** 그 셀 안으로 내려간다
/// (한글2022 실측 — 3중 중첩 표에서 부모 셀 28 → 자식 표 → 부모 셀 29 순서를 확인).
#[derive(Debug, Clone)]
pub struct ListEntry {
    pub list_id: u32,
    /// 셀이면 true, 글상자면 false.
    pub is_cell: bool,
    /// 이 리스트를 담은 리스트의 아이디.
    pub host_list_id: u32,
    pub section_index: usize,
    /// 호스트 문단 번호. 본문 호스트는 구역 안 번호, 중첩 호스트는 리스트 안 번호.
    pub host_para_index: usize,
    /// 그 문단 안에서 컨트롤 번호 — 상위로 올라갈 때 위치는 `8 × control_index` 다.
    pub control_index: usize,
    pub cell_index: usize,
    pub para_count: usize,
    /// 표 안에서의 격자 자리 — 셀이 아니면 `None`. 표 셀 이동(`TableRightCell` 따위)이 딛는다.
    pub grid: Option<CellGrid>,
}

/// 표 셀 하나의 격자 자리와 병합 크기.
#[derive(Debug, Clone, Copy)]
pub struct CellGrid {
    pub row: u16,
    pub col: u16,
    pub row_span: u16,
    pub col_span: u16,
    /// 그 표가 담은 셀 수 — 표의 끝을 알아야 이동이 멈출 자리를 안다.
    pub cell_count: usize,
}

/// 리스트 번호를 매기며 걷는 상태.
struct ListWalk {
    next_id: u32,
    lists: Vec<ListEntry>,
}

impl ListWalk {
    fn new() -> Self {
        Self {
            next_id: FIRST_SUB_LIST_ID,
            lists: Vec::new(),
        }
    }

    fn alloc(&mut self) -> u32 {
        let id = self.next_id;
        self.next_id += 1;
        id
    }
}

impl DocumentCore {
    /// 문서 전체에서 모든 필드를 검색하여 목록으로 반환한다.
    pub fn collect_all_fields(&self) -> Vec<FieldInfo> {
        self.collect_fields_and_lists().0
    }

    /// 필드와 리스트 목록을 **한 번의 순회로** 함께 모은다.
    ///
    /// 둘을 따로 걸으면 리스트 번호가 서로 어긋난다 — 필드가 말하는 `listId` 와 리스트 표의
    /// 아이디가 같은 순회에서 나와야 커서 좌표가 성립한다.
    pub fn collect_fields_and_lists(&self) -> (Vec<FieldInfo>, Vec<ListEntry>) {
        let mut result = Vec::new();
        let mut walk = ListWalk::new();
        let mut para_base = 0;
        for (si, sec) in self.document.sections.iter().enumerate() {
            for (pi, para) in sec.paragraphs.iter().enumerate() {
                let loc = FieldLocation {
                    section_index: si,
                    para_index: pi,
                    nested_path: Vec::new(),
                };
                collect_fields_from_paragraph(
                    para,
                    &loc,
                    ROOT_LIST_ID,
                    para_base + pi,
                    &mut walk,
                    &mut result,
                );
            }
            para_base += sec.paragraphs.len();
        }
        (result, walk.lists)
    }

    /// 본문 문단의 현재 커서 위치에 빈 ClickHere 누름틀을 삽입한다.
    pub fn insert_click_here_field_at(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, HwpError> {
        let field_id = self.next_click_here_field_id();
        let inserted_offset = {
            let section = self
                .document
                .sections
                .get_mut(section_idx)
                .ok_or_else(|| HwpError::InvalidField("구역 인덱스 초과".into()))?;
            section.raw_stream = None;
            let para = section
                .paragraphs
                .get_mut(para_idx)
                .ok_or_else(|| HwpError::InvalidField("문단 인덱스 초과".into()))?;
            insert_click_here_field_in_para(
                para,
                char_offset,
                field_id,
                guide,
                memo,
                name,
                editable,
            )?
        };

        // [Task #2299] 리셋 판별용 — reflow 이전 저장 흐름 end 캡처.
        let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
            &self.document.sections[section_idx].paragraphs[para_idx],
        );
        self.reflow_paragraph(section_idx, para_idx);
        let doc_hwp3_layout = self.document.layout_profile().hwp3_layout();
        crate::renderer::composer::recalculate_section_vpos(
            &mut self.document.sections[section_idx].paragraphs,
            para_idx,
            None,
            stored_end_for_reset,
            &self.styles,
            self.dpi,
            doc_hwp3_layout,
        );
        self.recompose_paragraph(section_idx, para_idx);
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::TextInserted {
            section: section_idx,
            para: para_idx,
            offset: inserted_offset,
            len: 0,
        });

        Ok(format!(
            "{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
            field_id, inserted_offset
        ))
    }

    /// 셀/글상자 내 문단의 현재 커서 위치에 빈 ClickHere 누름틀을 삽입한다.
    pub fn insert_click_here_field_at_in_cell(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        _is_textbox: bool,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, HwpError> {
        let field_id = self.next_click_here_field_id();
        let inserted_offset = {
            let para = self.get_cell_paragraph_mut(
                section_idx,
                parent_para_idx,
                control_idx,
                cell_idx,
                cell_para_idx,
            )?;
            insert_click_here_field_in_para(
                para,
                char_offset,
                field_id,
                guide,
                memo,
                name,
                editable,
            )?
        };

        self.mark_cell_control_dirty(section_idx, parent_para_idx, control_idx);
        self.reflow_cell_paragraph(
            section_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        );
        if let Some(section) = self.document.sections.get_mut(section_idx) {
            section.raw_stream = None;
        }
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::CellTextChanged {
            section: section_idx,
            para: parent_para_idx,
            ctrl: control_idx,
            cell: cell_idx,
        });

        Ok(format!(
            "{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
            field_id, inserted_offset
        ))
    }

    /// path 기반 중첩 표 셀의 현재 커서 위치에 빈 ClickHere 누름틀을 삽입한다.
    pub fn insert_click_here_field_at_by_path(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        char_offset: usize,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, HwpError> {
        if path.is_empty() {
            return Err(HwpError::InvalidField("cellPath가 비어 있음".into()));
        }
        let field_id = self.next_click_here_field_id();
        let inserted_offset = {
            let para = self.get_cell_paragraph_mut_by_path(section_idx, parent_para_idx, path)?;
            insert_click_here_field_in_para(
                para,
                char_offset,
                field_id,
                guide,
                memo,
                name,
                editable,
            )?
        };

        let outer_ctrl = path[0].0;
        let inner_para = path.last().map(|entry| entry.2).unwrap_or(0);
        self.reflow_cell_paragraph_by_path(section_idx, parent_para_idx, path, inner_para);
        self.recalculate_cell_paragraph_vpos_by_path(
            section_idx,
            parent_para_idx,
            path,
            inner_para,
            None,
        );
        self.mark_cell_control_dirty(section_idx, parent_para_idx, outer_ctrl);
        if let Some(section) = self.document.sections.get_mut(section_idx) {
            section.raw_stream = None;
        }
        self.mark_section_dirty(section_idx);
        self.paginate_if_needed();
        self.invalidate_page_tree_cache();
        self.event_log.push(DocumentEvent::CellTextChanged {
            section: section_idx,
            para: parent_para_idx,
            ctrl: outer_ctrl,
            cell: path[0].1,
        });

        Ok(format!(
            "{{\"ok\":true,\"fieldId\":{},\"charOffset\":{}}}",
            field_id, inserted_offset
        ))
    }

    /// getFieldList: 모든 필드를 JSON 배열로 반환
    pub fn get_field_list_json(&self) -> String {
        let fields = self.collect_all_fields();
        let entries: Vec<String> = fields
            .iter()
            .map(|fi| {
                let name = fi.field.field_name().unwrap_or("");
                let guide = fi.field.guide_text().unwrap_or("");
                let location_json = field_location_json(&fi.location);
                let (start_char_idx, end_char_idx) = field_range_bounds(self, fi)
                    .unwrap_or((0, fi.value.chars().count()));
                format!(
                    "{{\"fieldId\":{},\"fieldType\":\"{}\",\"cellField\":{},\"name\":{},\"guide\":{},\"command\":{},\"value\":{},\"location\":{},\"startCharIdx\":{},\"endCharIdx\":{},\"editableInForm\":{},\"listId\":{},\"paraInList\":{},\"startPos\":{},\"endPos\":{}}}",
                    fi.field.field_id,
                    fi.field.field_type_str(),
                    // 셀 구역 이름(가상 필드)과 문단 안 누름틀은 다른 것이다. `fieldType` 은 둘 다
                    // ClickHere 라 가르지 못한다 — 소비자가 종류를 물을 유일한 자리다.
                    fi.field.ctrl_id == 0,
                    json_escape(name),
                    json_escape(guide),
                    json_escape(&fi.field.command),
                    json_escape(&fi.value),
                    location_json,
                    start_char_idx,
                    end_char_idx,
                    fi.field.is_editable_in_form(),
                    // 한글 커서 좌표(list/para/pos) — 웹한글컨트롤 GetPos·MoveToField 가 쓴다.
                    fi.list_id,
                    fi.para_in_list,
                    fi.start_pos,
                    fi.end_pos,
                )
            })
            .collect();
        format!("[{}]", entries.join(","))
    }

    /// 아무 내용도 없는 빈 문서인가 — 웹한글컨트롤 `IsEmpty`(§8.2.7).
    ///
    /// 구역·단 정의는 새 문서에도 늘 있으므로 "내용"으로 세지 않는다. 글자 하나, 표 하나라도
    /// 있으면 빈 문서가 아니다(오라클 실측: 새 문서 true, 영수증 서식 false).
    pub fn is_empty_document(&self) -> bool {
        self.document.sections.iter().all(|section| {
            section.paragraphs.iter().all(|para| {
                para.text.is_empty()
                    && para
                        .controls
                        .iter()
                        .all(|ctrl| matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)))
            })
        })
    }

    /// 한글 커서 좌표계(`GetPos`/`SetPos`/`MovePos`)를 쓰는 데 필요한 문서 사실을 모아 준다.
    ///
    /// ```json
    /// {"listCount":325,
    ///  "root":{"paraCount":3,"topPos":72,"endPara":2,"endPos":0},
    ///  "lists":[{"listId":2,"isCell":true,"hostListId":0,"hostPara":0,
    ///            "controlIndex":2,"cellIndex":0,"paraCount":1}, …]}
    /// ```
    ///
    /// `root.topPos` 는 "문서의 시작"(`MovePos(2)`)이 떨어지는 자리다. 한글은 문단 앞머리의
    /// **자리차지 컨트롤을 건너뛴다** — 영수증 서식(자리차지 표 7개)은 72, 보도자료 서식
    /// (인라인 표)은 16 이었다. 컨트롤 하나가 8 코드 유닛이다.
    pub fn get_cursor_model_json(&self) -> String {
        let (_, lists) = self.collect_fields_and_lists();
        let entries: Vec<String> = lists
            .iter()
            .map(|l| {
                let grid = match l.grid {
                    Some(g) => format!(
                        ",\"row\":{},\"col\":{},\"rowSpan\":{},\"colSpan\":{},\"cellCount\":{}",
                        g.row, g.col, g.row_span, g.col_span, g.cell_count,
                    ),
                    None => String::new(),
                };
                // `hostPara` 는 **구역 안 번호**다. 구역이 여럿이면 다른 구역의 같은 번호와
                // 겹치므로 `sectionIndex` 를 함께 줘야 표를 갈라 볼 수 있다.
                format!(
                    "{{\"listId\":{},\"isCell\":{},\"hostListId\":{},\"sectionIndex\":{},\"hostPara\":{},\"controlIndex\":{},\"cellIndex\":{},\"paraCount\":{}{}}}",
                    l.list_id,
                    l.is_cell,
                    l.host_list_id,
                    l.section_index,
                    l.host_para_index,
                    l.control_index,
                    l.cell_index,
                    l.para_count,
                    grid,
                )
            })
            .collect();

        // 본문은 **구역을 가로질러** 하나의 리스트다(한글 실측). 첫 구역만 세면 다구역 문서에서
        // 문단 번호가 통째로 어긋난다 — `root_para_location` 의 주석 참고.
        let para_count = root_para_count(self);
        let top_pos = self
            .document
            .sections
            .first()
            .and_then(|s| s.paragraphs.first())
            .map(leading_anchor_pos)
            .unwrap_or(0);
        let end_para = para_count.saturating_sub(1);
        let end_pos = root_para_location(self, end_para)
            .and_then(|(si, pi)| self.document.sections.get(si)?.paragraphs.get(pi))
            .map(|p| (p.char_count as usize).saturating_sub(1))
            .unwrap_or(0);

        format!(
            "{{\"listCount\":{},\"root\":{{\"paraCount\":{},\"topPos\":{},\"endPara\":{},\"endPos\":{}}},\"lists\":[{}]}}",
            FIRST_SUB_LIST_ID as usize + lists.len(),
            para_count,
            top_pos,
            end_para,
            end_pos,
            entries.join(","),
        )
    }

    /// getFieldValue: field_id로 필드 값 조회
    pub fn get_field_value_by_id(&self, field_id: u32) -> Result<String, HwpError> {
        let fields = self.collect_all_fields();
        for fi in &fields {
            if fi.field.field_id == field_id {
                return Ok(format!(
                    "{{\"ok\":true,\"value\":{}}}",
                    json_escape(&fi.value)
                ));
            }
        }
        Err(HwpError::InvalidField(format!("필드 ID {} 없음", field_id)))
    }

    /// getFieldValueByName: 필드 이름으로 값 조회
    pub fn get_field_value_by_name(&self, name: &str) -> Result<String, HwpError> {
        let fields = self.collect_all_fields();
        for fi in &fields {
            if let Some(field_name) = fi.field.field_name() {
                if field_name == name {
                    return Ok(format!(
                        "{{\"ok\":true,\"fieldId\":{},\"value\":{}}}",
                        fi.field.field_id,
                        json_escape(&fi.value),
                    ));
                }
            }
        }
        Err(HwpError::InvalidField(format!("필드 이름 '{}' 없음", name)))
    }

    /// setFieldValue: field_id로 필드 값 설정
    pub fn set_field_value_by_id(
        &mut self,
        field_id: u32,
        value: &str,
    ) -> Result<String, HwpError> {
        // 먼저 필드 위치 찾기
        let fields = self.collect_all_fields();
        let fi = fields
            .iter()
            .find(|f| f.field.field_id == field_id)
            .ok_or_else(|| HwpError::InvalidField(format!("필드 ID {} 없음", field_id)))?;

        let location = fi.location.clone();
        let fri = fi.field_range_index;
        let old_value = fi.value.clone();
        let is_cell_field = fi.field.ctrl_id == 0; // 가상 셀 필드

        let section_index = location.section_index;
        let stored_end_for_reset = self.field_body_flow_end(&location);
        self.validate_field_reflow_location(&location)?;
        if is_cell_field {
            self.set_cell_field_text(&location, value)?;
        } else {
            self.set_field_text_at(&location, fri, value)?;
        }
        self.reflow_field_location_after_edit(&location, stored_end_for_reset)?;
        if let Some(sec) = self.document.sections.get_mut(section_index) {
            sec.raw_stream = None;
        }
        self.recompose_section(section_index);

        Ok(format!(
            "{{\"ok\":true,\"fieldId\":{},\"oldValue\":{},\"newValue\":{}}}",
            field_id,
            json_escape(&old_value),
            json_escape(value),
        ))
    }

    /// setFieldValueByName: 필드 이름으로 값 설정
    pub fn set_field_value_by_name(&mut self, name: &str, value: &str) -> Result<String, HwpError> {
        self.set_field_value_by_name_at(name, 0, value)
    }

    /// [#3476] 같은 이름이 여러 번 나오는 서식에서 **N 번째**(0 기준) 필드에 값을 넣는다.
    ///
    /// 규제영향분석서 같은 실제 제출 서식은 같은 항목 묶음을 여러 번 요구한다
    /// (`피규제집단명` ×14 등). 이름만으로 찾으면 첫 매치만 바뀌어 나머지를 채울 수 없다.
    /// 순서는 `collect_all_fields()` 가 주는 문서 순서와 같으므로, 소비자는
    /// `fields --json` 목록의 순번을 그대로 쓰면 된다.
    pub fn set_field_value_by_name_at(
        &mut self,
        name: &str,
        occurrence: usize,
        value: &str,
    ) -> Result<String, HwpError> {
        let fields = self.collect_all_fields();
        let fi = fields
            .iter()
            .filter(|f| f.field.field_name().map(|n| n == name).unwrap_or(false))
            .nth(occurrence)
            .ok_or_else(|| {
                HwpError::InvalidField(format!("필드 이름 '{}'[{}] 없음", name, occurrence))
            })?;

        let field_id = fi.field.field_id;
        let location = fi.location.clone();
        let fri = fi.field_range_index;
        let old_value = fi.value.clone();
        let is_cell_field = fi.field.ctrl_id == 0; // 가상 셀 필드

        let section_index = location.section_index;
        let stored_end_for_reset = self.field_body_flow_end(&location);
        self.validate_field_reflow_location(&location)?;

        if is_cell_field {
            // 셀 필드: 셀의 첫 문단 텍스트를 직접 교체
            self.set_cell_field_text(&location, value)?;
        } else {
            // ClickHere 필드: field_ranges 기반 교체
            self.set_field_text_at(&location, fri, value)?;
        }

        self.reflow_field_location_after_edit(&location, stored_end_for_reset)?;

        // raw_stream 무효화
        if let Some(sec) = self.document.sections.get_mut(section_index) {
            sec.raw_stream = None;
        }
        self.recompose_section(section_index);

        Ok(format!(
            "{{\"ok\":true,\"fieldId\":{},\"oldValue\":{},\"newValue\":{}}}",
            field_id,
            json_escape(&old_value),
            json_escape(value),
        ))
    }

    /// 필드 텍스트 편집 전의 본문 흐름 끝을 보존한다.
    ///
    /// 본문 문단의 vpos 사다리를 다시 계산할 때만 쓰며, 셀·글상자는 각 컨테이너의
    /// 재계산 경로가 별도로 처리한다.
    fn field_body_flow_end(&self, location: &FieldLocation) -> Option<i32> {
        if !location.nested_path.is_empty() {
            return None;
        }
        self.document
            .sections
            .get(location.section_index)
            .and_then(|section| section.paragraphs.get(location.para_index))
            .and_then(crate::renderer::composer::paragraph_flow_end)
    }

    fn field_nested_reflow_path(
        location: &FieldLocation,
    ) -> Result<Vec<(usize, usize, usize)>, HwpError> {
        if location.nested_path.is_empty() {
            return Err(HwpError::InvalidField(
                "중첩 필드 위치에 소유자 경로 없음".into(),
            ));
        }
        Ok(location
            .nested_path
            .iter()
            .map(|entry| match entry {
                NestedEntry::TableCell {
                    control_index,
                    cell_index,
                    para_index,
                } => (*control_index, *cell_index, *para_index),
                NestedEntry::TextBox {
                    control_index,
                    para_index,
                } => (*control_index, 0, *para_index),
            })
            .collect())
    }

    /// mutation 전에 필드 소유 문단 경로를 검증한다.
    ///
    /// `reflow_cell_paragraph_by_path`는 일반 렌더 보조 경로라 실패 시 반환값이 없다.
    /// 공개 field setter에서는 그 동작을 그대로 노출하지 않고, 같은 path resolver로
    /// 대상 문단의 실재를 먼저 확인해 stale LineSeg를 정상 성공으로 보고하지 않는다.
    fn validate_field_reflow_location(&mut self, location: &FieldLocation) -> Result<(), HwpError> {
        if location.nested_path.is_empty() {
            self.document
                .sections
                .get(location.section_index)
                .and_then(|section| section.paragraphs.get(location.para_index))
                .ok_or_else(|| HwpError::InvalidField("필드 소유 본문 문단 범위 초과".into()))?;
            return Ok(());
        }

        let path = Self::field_nested_reflow_path(location)?;
        self.get_cell_paragraph_mut_by_path(location.section_index, location.para_index, &path)?;
        Ok(())
    }

    /// 필드 편집으로 무효가 된 LineSeg를 해당 문단 상자에서 즉시 다시 계산한다.
    ///
    /// 종전 `set_field_text_at`은 저장 LineSeg를 비운 뒤 section compose만 갱신했다.
    /// HWP5 저장기는 빈 배열을 기록하고 재적재기는 0높이 줄을 합성하므로, 같은 문서가
    /// 메모리에서는 0줄·재적재 뒤에는 1줄이 되어 `edit/batch fill --verify`가 항상
    /// 실패했다. 다른 텍스트 편집 관문과 같이 실제 소유자(본문 또는 셀/글상자)의 폭으로
    /// reflow하고 vpos를 잇는다. 저장 데이터의 차이는 그대로 비교되며, 검증기에서
    /// 차이를 숨기는 예외 규칙은 추가하지 않는다.
    fn reflow_field_location_after_edit(
        &mut self,
        location: &FieldLocation,
        stored_end_for_reset: Option<i32>,
    ) -> Result<(), HwpError> {
        if location.nested_path.is_empty() {
            self.reflow_paragraph(location.section_index, location.para_index);
            let hwp3_layout = self.document.layout_profile().hwp3_layout();
            crate::renderer::composer::recalculate_section_vpos(
                &mut self.document.sections[location.section_index].paragraphs,
                location.para_index,
                None,
                stored_end_for_reset,
                &self.styles,
                self.dpi,
                hwp3_layout,
            );
            let owner =
                &self.document.sections[location.section_index].paragraphs[location.para_index];
            if owner.line_segs.is_empty() {
                return Err(HwpError::InvalidField(
                    "필드 소유 본문 문단 재조판 결과가 비어 있음".into(),
                ));
            }
            return Ok(());
        }

        let path = Self::field_nested_reflow_path(location)?;
        let inner_para = path
            .last()
            .map(|entry| entry.2)
            .ok_or_else(|| HwpError::InvalidField("필드 소유 문단 경로 없음".into()))?;

        self.reflow_cell_paragraph_by_path(
            location.section_index,
            location.para_index,
            &path,
            inner_para,
        );
        self.recalculate_cell_paragraph_vpos_by_path(
            location.section_index,
            location.para_index,
            &path,
            inner_para,
            None,
        );
        if self
            .get_cell_paragraph_mut_by_path(location.section_index, location.para_index, &path)?
            .line_segs
            .is_empty()
        {
            return Err(HwpError::InvalidField(
                "필드 소유 중첩 문단 재조판 결과가 비어 있음".into(),
            ));
        }
        self.mark_cell_control_dirty(location.section_index, location.para_index, path[0].0);
        Ok(())
    }

    /// 한글 커서 좌표(list/para/pos)에 누름틀을 넣는다 — 웹한글컨트롤 `CreateField` 용.
    ///
    /// 좌표계가 두 개다. 한글의 `pos` 는 **코드 유닛**(확장 컨트롤 하나가 8칸)이고 rhwp 의
    /// 삽입 API 는 **글자 번호**를 받는다. 그 사이를 여기서 옮긴다 — 호출 측이 옮기면
    /// `char_offsets` 가 없는 곳에서 추측하게 된다.
    pub fn insert_click_here_field_at_cursor(
        &mut self,
        list_id: u32,
        para_in_list: usize,
        pos: usize,
        guide: &str,
        memo: &str,
        name: &str,
        editable: bool,
    ) -> Result<String, HwpError> {
        if list_id == ROOT_LIST_ID {
            let (section_index, para_index) = root_para_location(self, para_in_list)
                .ok_or_else(|| HwpError::InvalidField("본문 문단 인덱스 초과".into()))?;
            let char_offset = char_idx_at_code_unit(
                &self.document.sections[section_index].paragraphs[para_index],
                pos,
            );
            return self.insert_click_here_field_at(
                section_index,
                para_index,
                char_offset,
                guide,
                memo,
                name,
                editable,
            );
        }

        let (_, lists) = self.collect_fields_and_lists();
        let path = cell_path_to_list(&lists, list_id, para_in_list)
            .ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
        let entry = lists
            .iter()
            .find(|l| l.list_id == list_id)
            .ok_or_else(|| HwpError::InvalidField(format!("리스트 {} 없음", list_id)))?;
        let section_index = entry.section_index;
        let host_para = root_para_of(&lists, entry);
        let char_offset = self
            .cell_paragraph_at_path(section_index, host_para, &path)
            .map(|p| char_idx_at_code_unit(p, pos))
            .unwrap_or(0);
        self.insert_click_here_field_at_by_path(
            section_index,
            host_para,
            &path,
            char_offset,
            guide,
            memo,
            name,
            editable,
        )
    }

    /// 경로가 가리키는 셀 문단(읽기 전용). 좌표 변환에만 쓴다.
    fn cell_paragraph_at_path(
        &self,
        section_index: usize,
        host_para: usize,
        path: &[(usize, usize, usize)],
    ) -> Option<&Paragraph> {
        let mut para = self
            .document
            .sections
            .get(section_index)?
            .paragraphs
            .get(host_para)?;
        for (control_index, cell_index, para_index) in path {
            let ctrl = para.controls.get(*control_index)?;
            para = match ctrl {
                Control::Table(table) => {
                    table.cells.get(*cell_index)?.paragraphs.get(*para_index)?
                }
                // 그리기 개체는 글상자와 캡션을 연다 — 둘째 칸이 그중 몇 번째인지다.
                // 여기가 표만 알던 탓에 글상자·캡션 리스트는 **자리가 있어도 못 닿았다**
                // (한글은 그 리스트 끝을 18 로 답하는데 rhwp 는 0 이었다).
                Control::Shape(shape) => shape_lists(shape)
                    .into_iter()
                    .find(|(node, _)| node == cell_index)
                    .and_then(|(_, paragraphs)| paragraphs.get(*para_index))?,
                _ => return None,
            };
        }
        Some(para)
    }

    /// RenameField(웹한글컨트롤 §8.3.36) — 이름이 `oldname` 인 필드를 모두 `newname` 으로 바꾼다.
    ///
    /// 필드는 저장 경로가 두 갈래다. 누름틀은 문단의 CTRL_DATA 에, 셀 필드는 셀
    /// LIST_HEADER 의 추가 바이트에 이름을 싣는다. 누름틀 경로만 고치면 셀 필드는 **조용히
    /// 안 바뀐다** — `updateClickHereProps` 가 셀 필드에서 `{"ok":false}` 를 돌려주던 이유다.
    ///
    /// 같은 이름이 여러 번 나오면 **전부** 바꾼다(한글2022 실측: `pt_no` ×2 문서에서 한 번의
    /// 호출 뒤 `FieldExist("pt_no")` 가 false).
    ///
    /// 반환: `{"ok":true,"renamed":N}`. 없는 이름이면 `{"ok":false,"renamed":0}` —
    /// 오라클도 아무 일도 하지 않는다.
    pub fn rename_field_by_name(
        &mut self,
        oldname: &str,
        newname: &str,
    ) -> Result<String, HwpError> {
        if oldname.is_empty() {
            return Err(HwpError::InvalidField("바꿀 필드 이름이 비어 있음".into()));
        }
        // (위치, field_range 인덱스, 셀 필드 여부). ctrl_id == 0 은 collect_all_fields 가
        // 셀 이름으로 만들어 낸 가상 필드다.
        let targets: Vec<(FieldLocation, usize, bool)> = self
            .collect_all_fields()
            .iter()
            .filter(|fi| fi.field.field_name() == Some(oldname))
            .map(|fi| {
                (
                    fi.location.clone(),
                    fi.field_range_index,
                    fi.field.ctrl_id == 0,
                )
            })
            .collect();
        if targets.is_empty() {
            return Ok(r#"{"ok":false,"renamed":0}"#.to_string());
        }

        let mut renamed = 0usize;
        let mut touched_sections: Vec<usize> = Vec::new();
        for (location, field_range_index, is_cell) in targets {
            if is_cell {
                let cell = self.cell_at_location_mut(&location)?;
                cell.field_name = if newname.is_empty() {
                    None
                } else {
                    Some(newname.to_string())
                };
            } else {
                let para = self.get_para_mut_at_location(&location)?;
                let control_idx = para
                    .field_ranges
                    .get(field_range_index)
                    .ok_or_else(|| HwpError::InvalidField("field_range 인덱스 초과".into()))?
                    .control_idx;
                if let Some(Control::Field(field)) = para.controls.get_mut(control_idx) {
                    field.ctrl_data_name = if newname.is_empty() {
                        None
                    } else {
                        Some(newname.to_string())
                    };
                }
                write_ctrl_data_name(&mut para.ctrl_data_records, control_idx, newname);
            }
            renamed += 1;
            if !touched_sections.contains(&location.section_index) {
                touched_sections.push(location.section_index);
            }
        }

        // raw_stream 무효화: 없으면 저장이 원본 바이트를 재방출해 옛 이름이 되살아난다.
        // 이름은 조판에 영향이 없으므로 재조판은 하지 않는다.
        for section_index in touched_sections {
            if let Some(sec) = self.document.sections.get_mut(section_index) {
                sec.raw_stream = None;
            }
        }

        Ok(format!("{{\"ok\":true,\"renamed\":{}}}", renamed))
    }

    /// 필드 위치가 가리키는 **셀 자체**의 가변 참조. 경로의 마지막 항목이 셀이어야 한다.
    fn cell_at_location_mut(
        &mut self,
        location: &FieldLocation,
    ) -> Result<&mut crate::model::table::Cell, HwpError> {
        let (control_index, cell_index) = match location.nested_path.last() {
            Some(NestedEntry::TableCell {
                control_index,
                cell_index,
                ..
            }) => (*control_index, *cell_index),
            _ => return Err(HwpError::InvalidField("셀 필드가 아닌 위치".into())),
        };
        // 마지막 항목을 뗀 위치가 그 셀을 담은 표가 있는 문단이다.
        let mut host = location.clone();
        host.nested_path.pop();
        let para = self.get_para_mut_at_location(&host)?;
        let ctrl = para
            .controls
            .get_mut(control_index)
            .ok_or_else(|| HwpError::InvalidField("컨트롤 인덱스 초과".into()))?;
        match ctrl {
            Control::Table(table) => table
                .cells
                .get_mut(cell_index)
                .ok_or_else(|| HwpError::InvalidField("셀 인덱스 초과".into())),
            _ => Err(HwpError::InvalidField(
                "셀을 담은 컨트롤이 표가 아님".into(),
            )),
        }
    }

    /// 셀 필드의 텍스트를 교체한다 (셀의 첫 문단 텍스트를 value로 대체).
    /// 중첩 표를 재귀적으로 탐색하여 임의 깊이를 지원한다.
    fn set_cell_field_text(
        &mut self,
        location: &FieldLocation,
        value: &str,
    ) -> Result<(), HwpError> {
        if location.nested_path.is_empty() {
            return Err(HwpError::InvalidField(
                "셀 필드 위치에 중첩 경로 없음".into(),
            ));
        }
        let sec = self
            .document
            .sections
            .get_mut(location.section_index)
            .ok_or_else(|| HwpError::InvalidField("구역 초과".into()))?;
        let mut para: &mut Paragraph = sec
            .paragraphs
            .get_mut(location.para_index)
            .ok_or_else(|| HwpError::InvalidField("문단 초과".into()))?;

        // 마지막 항목 직전까지 중첩 탐색
        for (i, entry) in location.nested_path[..location.nested_path.len() - 1]
            .iter()
            .enumerate()
        {
            para = match entry {
                NestedEntry::TableCell {
                    control_index,
                    cell_index,
                    para_index,
                } => {
                    let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 컨트롤 인덱스 {} 초과",
                            i, control_index
                        ))
                    })?;
                    if let Control::Table(ref mut table) = ctrl {
                        let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 셀 인덱스 {} 초과",
                                i, cell_index
                            ))
                        })?;
                        cell.paragraphs.get_mut(*para_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 셀 문단 인덱스 {} 초과",
                                i, para_index
                            ))
                        })?
                    } else {
                        return Err(HwpError::InvalidField(format!(
                            "경로[{}]: controls[{}]가 Table이 아님",
                            i, control_index
                        )));
                    }
                }
                NestedEntry::TextBox {
                    control_index,
                    para_index,
                } => {
                    let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 컨트롤 인덱스 {} 초과",
                            i, control_index
                        ))
                    })?;
                    if let Control::Shape(ref mut shape) = ctrl {
                        let drawing = shape.drawing_mut().ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: Shape에 DrawingObjAttr 없음",
                                i
                            ))
                        })?;
                        let tb = drawing.text_box.as_mut().ok_or_else(|| {
                            HwpError::InvalidField(format!("경로[{}]: Shape에 TextBox 없음", i))
                        })?;
                        tb.paragraphs.get_mut(*para_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 글상자 문단 인덱스 {} 초과",
                                i, para_index
                            ))
                        })?
                    } else {
                        return Err(HwpError::InvalidField(format!(
                            "경로[{}]: controls[{}]가 Shape가 아님",
                            i, control_index
                        )));
                    }
                }
            };
        }

        // 마지막 항목: 셀의 첫 문단 텍스트를 교체
        let last_idx = location.nested_path.len() - 1;
        let last = location.nested_path.last().unwrap();
        match last {
            NestedEntry::TableCell {
                control_index,
                cell_index,
                ..
            } => {
                let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
                    HwpError::InvalidField(format!(
                        "경로[{}]: 컨트롤 인덱스 {} 초과",
                        last_idx, control_index
                    ))
                })?;
                if let Control::Table(ref mut table) = ctrl {
                    let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 셀 인덱스 {} 초과",
                            last_idx, cell_index
                        ))
                    })?;
                    let cell_para = cell.paragraphs.first_mut().ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 셀 필드에 편집할 문단 없음",
                            last_idx
                        ))
                    })?;
                    let old_len = cell_para.text.chars().count();
                    cell_para.replace_text_keeping_slots(0, old_len, value, None, false);
                    cell_para.replace_line_segs(Vec::new());
                    Ok(())
                } else {
                    Err(HwpError::InvalidField(format!(
                        "경로[{}]: controls[{}]가 Table이 아님",
                        last_idx, control_index
                    )))
                }
            }
            _ => Err(HwpError::InvalidField("셀 필드가 아닌 위치".into())),
        }
    }

    /// 필드 위치에서 텍스트를 교체한다.
    ///
    /// `replace_text_keeping_slots` 로 값만 바꿔 char_shapes, line_segs, range_tags,
    /// char_count 를 함께 옮기고 같은 문단의 다른 컨트롤 슬롯과 누름틀 경계를 지킨다.
    /// (직접 para.text 조작 시 메타데이터 불일치로 한컴 "파일 손상" 발생 — #838)
    fn set_field_text_at(
        &mut self,
        location: &FieldLocation,
        field_range_index: usize,
        value: &str,
    ) -> Result<(), HwpError> {
        // raw_stream 무효화: 직렬화 시 수정된 모델을 사용하도록 강제
        if let Some(sec) = self.document.sections.get_mut(location.section_index) {
            sec.raw_stream = None;
        }
        let para = self.get_para_mut_at_location(location)?;
        Self::replace_field_text_model(para, field_range_index, value)
    }

    /// Shared model-only operation for editor fields and detached template copies.
    pub(crate) fn replace_field_text_model(
        para: &mut Paragraph,
        field_range_index: usize,
        value: &str,
    ) -> Result<(), HwpError> {
        let fr = para
            .field_ranges
            .get(field_range_index)
            .ok_or_else(|| HwpError::InvalidField("field_range 인덱스 초과".into()))?
            .clone();

        let start_idx = fr.start_char_idx;
        let count = fr.end_char_idx.saturating_sub(start_idx);
        let control_idx = fr.control_idx;
        // 값은 이 필드가 품는다 — 빈 필드여도 같은 자리의 다른 필드보다 먼저다.
        para.replace_text_keeping_slots(start_idx, count, value, Some(control_idx), false);

        // [#3380] 값을 채운 필드는 더 이상 "초기 상태"가 아니다 — properties 비트 15를 세운다.
        //
        // 적재 시 `clear_initial_field_texts` 는 비트 15가 0 인 ClickHere 필드의 텍스트가
        // 안내문과 같으면 "한컴이 남긴 안내문 잔재"로 보고 지운다. 그래서 채운 값이 하필
        // 안내문과 같으면(행정 서식의 "주무관"·"공개"·"해당없음" 등 흔한 실값) 저장·재적재
        // 후 그 칸만 소리 없이 비었다. 쓰기 시점에 상태를 표시해 두면 정규화가 값을 잔재로
        // 오인하지 않는다. 비트 15 는 이 정규화와 Memo 직렬화에서만 쓰여 렌더에 영향이 없다.
        if !value.is_empty() {
            if let Some(Control::Field(field)) = para.controls.get_mut(control_idx) {
                field.properties |= 1 << 15;
            }
        }

        para.replace_line_segs(Vec::new());

        Ok(())
    }

    /// FieldLocation에 해당하는 Paragraph의 가변 참조를 반환한다.
    ///
    /// 중첩 표/글상자를 재귀적으로 탐색하여 임의 깊이를 지원한다.
    fn get_para_mut_at_location(
        &mut self,
        location: &FieldLocation,
    ) -> Result<&mut Paragraph, HwpError> {
        let sec = self
            .document
            .sections
            .get_mut(location.section_index)
            .ok_or_else(|| HwpError::InvalidField("구역 인덱스 초과".into()))?;
        let mut para = sec
            .paragraphs
            .get_mut(location.para_index)
            .ok_or_else(|| HwpError::InvalidField("문단 인덱스 초과".into()))?;

        for (i, entry) in location.nested_path.iter().enumerate() {
            para = match entry {
                NestedEntry::TableCell {
                    control_index,
                    cell_index,
                    para_index,
                } => {
                    let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 컨트롤 인덱스 {} 초과",
                            i, control_index
                        ))
                    })?;
                    if let Control::Table(ref mut table) = ctrl {
                        let cell = table.cells.get_mut(*cell_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 셀 인덱스 {} 초과",
                                i, cell_index
                            ))
                        })?;
                        cell.paragraphs.get_mut(*para_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 셀 문단 인덱스 {} 초과",
                                i, para_index
                            ))
                        })?
                    } else {
                        return Err(HwpError::InvalidField(format!(
                            "경로[{}]: controls[{}]가 Table이 아님",
                            i, control_index
                        )));
                    }
                }
                NestedEntry::TextBox {
                    control_index,
                    para_index,
                } => {
                    let ctrl = para.controls.get_mut(*control_index).ok_or_else(|| {
                        HwpError::InvalidField(format!(
                            "경로[{}]: 컨트롤 인덱스 {} 초과",
                            i, control_index
                        ))
                    })?;
                    if let Control::Shape(ref mut shape) = ctrl {
                        let drawing = shape.drawing_mut().ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: Shape에 DrawingObjAttr 없음",
                                i
                            ))
                        })?;
                        let tb = drawing.text_box.as_mut().ok_or_else(|| {
                            HwpError::InvalidField(format!("경로[{}]: Shape에 TextBox 없음", i))
                        })?;
                        tb.paragraphs.get_mut(*para_index).ok_or_else(|| {
                            HwpError::InvalidField(format!(
                                "경로[{}]: 글상자 문단 인덱스 {} 초과",
                                i, para_index
                            ))
                        })?
                    } else {
                        return Err(HwpError::InvalidField(format!(
                            "경로[{}]: controls[{}]가 Shape가 아님",
                            i, control_index
                        )));
                    }
                }
            };
        }

        Ok(para)
    }

    /// 본문 문단의 커서 위치에서 필드를 제거한다 (필드 내용과 컨트롤 삭제).
    ///
    /// 성공 시 `{"ok":true}`, 필드가 없으면 에러를 반환한다.
    pub fn remove_field_at(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> Result<String, HwpError> {
        let stored_end_for_reset = crate::renderer::composer::paragraph_flow_end(
            self.document
                .sections
                .get(section_idx)
                .and_then(|section| section.paragraphs.get(para_idx))
                .ok_or_else(|| HwpError::InvalidField("문단 위치 초과".into()))?,
        );
        let para = self
            .document
            .sections
            .get_mut(section_idx)
            .and_then(|s| s.paragraphs.get_mut(para_idx))
            .ok_or_else(|| HwpError::InvalidField("문단 위치 초과".into()))?;
        let removed = remove_field_in_para(para, char_offset)?;
        // 활성 주소의 para_idx는 셀에서도 본문 부모다. 같은 부모의 컨트롤 번호만
        // 비교해야 다른 표나 문단의 활성 누름틀을 해제하지 않는다.
        let mut clear_active = false;
        if let Some(active) = self.active_field.as_mut() {
            if active.section_idx == section_idx && active.para_idx == para_idx {
                match &active.cell_path {
                    None if active.para_idx == para_idx => {
                        clear_active = active.control_idx == removed;
                        if active.control_idx > removed {
                            active.control_idx -= 1;
                        }
                    }
                    Some(path) => {
                        clear_active = path.first().is_some_and(|&(table, _, _)| table > removed)
                    }
                    None => {}
                }
            }
        }
        if clear_active {
            self.clear_active_field();
        }
        // 필드 제거는 섹션 본문을 바꾸므로 raw_stream 을 무효화해야 저장에 반영된다
        // (삽입 짝 insert_click_here_field_at 과 동형). 누락 시 recompose 로 화면만
        // 갱신되고 저장은 원본 바이트를 재방출해 지운 필드가 되살아난다.
        if let Some(section) = self.document.sections.get_mut(section_idx) {
            section.raw_stream = None;
        }
        self.reflow_paragraph(section_idx, para_idx);
        let hwp3_layout = self.document.layout_profile().hwp3_layout();
        crate::renderer::composer::recalculate_section_vpos(
            &mut self.document.sections[section_idx].paragraphs,
            para_idx,
            None,
            stored_end_for_reset,
            &self.styles,
            self.dpi,
            hwp3_layout,
        );
        self.recompose_section(section_idx);
        self.paginate();
        Ok(r#"{"ok":true}"#.to_string())
    }

    /// 셀/글상자 내 문단의 커서 위치에서 필드를 제거한다.
    pub fn remove_field_at_in_cell(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        is_textbox: bool,
    ) -> Result<String, HwpError> {
        let para = {
            let host = self
                .document
                .sections
                .get_mut(section_idx)
                .and_then(|s| s.paragraphs.get_mut(parent_para_idx))
                .ok_or_else(|| HwpError::InvalidField("호스트 문단 위치 초과".into()))?;
            let ctrl = host
                .controls
                .get_mut(control_idx)
                .ok_or_else(|| HwpError::InvalidField("컨트롤 인덱스 초과".into()))?;
            if is_textbox {
                if let Control::Shape(shape) = ctrl {
                    let drawing = shape.drawing_mut().ok_or_else(|| {
                        HwpError::InvalidField("Shape에 DrawingObjAttr 없음".into())
                    })?;
                    let tb = drawing
                        .text_box
                        .as_mut()
                        .ok_or_else(|| HwpError::InvalidField("Shape에 TextBox 없음".into()))?;
                    tb.paragraphs
                        .get_mut(cell_para_idx)
                        .ok_or_else(|| HwpError::InvalidField("글상자 문단 인덱스 초과".into()))?
                } else {
                    return Err(HwpError::InvalidField("예상된 Shape 컨트롤이 아님".into()));
                }
            } else {
                if let Control::Table(table) = ctrl {
                    let cell = table
                        .cells
                        .get_mut(cell_idx)
                        .ok_or_else(|| HwpError::InvalidField("셀 인덱스 초과".into()))?;
                    cell.paragraphs
                        .get_mut(cell_para_idx)
                        .ok_or_else(|| HwpError::InvalidField("셀 문단 인덱스 초과".into()))?
                } else {
                    return Err(HwpError::InvalidField("예상된 Table 컨트롤이 아님".into()));
                }
            }
        };
        let removed = remove_field_in_para(para, char_offset)?;
        // 이 셀 문단의 활성 누름틀(또는 안쪽 표)이 지운 누름틀 자리나 그 뒤면 주소가 맞지 않는다.
        // 본문 부모까지 일치할 때만 로컬 셀 경로의 영향을 판단한다.
        if self.active_field.as_ref().is_some_and(|active| {
            active.section_idx == section_idx
                && active.para_idx == parent_para_idx
                && active.cell_path.as_deref().is_some_and(|path| {
                    path.first() == Some(&(control_idx, cell_idx, cell_para_idx))
                        && path
                            .get(1)
                            .map_or(active.control_idx, |&(table, _, _)| table)
                            >= removed
                })
        }) {
            self.clear_active_field();
        }
        // 셀/글상자 내 필드 제거도 섹션 본문 스트림을 바꾸므로 raw_stream 무효화 필요
        // (삽입 짝 insert_click_here_field_at_in_cell 과 동형).
        if let Some(section) = self.document.sections.get_mut(section_idx) {
            section.raw_stream = None;
        }
        self.reflow_cell_paragraph(
            section_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
        );
        self.recompose_section(section_idx);
        self.paginate();
        Ok(r#"{"ok":true}"#.to_string())
    }

    /// 커서가 진입한 활성 필드를 설정한다 (안내문 렌더링 스킵용).
    ///
    /// 본문 문단: `set_active_field(sec, para, char_offset)`
    /// 설정 후 해당 페이지의 렌더 트리 캐시를 무효화한다.
    /// 활성 필드를 설정한다. 변경이 발생하면 true를 반환한다.
    pub fn set_active_field(
        &mut self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> bool {
        use super::super::ActiveFieldInfo;
        let ctrl_idx = self.find_field_control_idx(section_idx, para_idx, char_offset, None);
        if let Some(ci) = ctrl_idx {
            let new_info = ActiveFieldInfo {
                section_idx,
                para_idx,
                control_idx: ci,
                cell_path: None,
            };
            if self.active_field.as_ref() != Some(&new_info) {
                self.active_field = Some(new_info);
                self.invalidate_page_tree_cache();
                return true;
            }
        }
        false
    }

    /// 셀/글상자 내 활성 필드를 설정한다. 변경이 발생하면 true를 반환한다.
    pub fn set_active_field_in_cell(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        is_textbox: bool,
    ) -> bool {
        use super::super::ActiveFieldInfo;
        let cell_path = Some(vec![(control_idx, cell_idx, cell_para_idx)]);
        let ctrl_idx = self.find_field_control_idx_in_cell(
            section_idx,
            parent_para_idx,
            control_idx,
            cell_idx,
            cell_para_idx,
            char_offset,
            is_textbox,
        );
        if let Some(ci) = ctrl_idx {
            let new_info = ActiveFieldInfo {
                section_idx,
                para_idx: parent_para_idx,
                control_idx: ci,
                cell_path,
            };
            if self.active_field.as_ref() != Some(&new_info) {
                self.active_field = Some(new_info);
                self.invalidate_page_tree_cache();
                return true;
            }
        }
        false
    }

    /// 활성 필드를 해제한다.
    pub fn clear_active_field(&mut self) {
        if self.active_field.is_some() {
            self.active_field = None;
            self.invalidate_page_tree_cache();
        }
    }

    /// 본문 문단의 커서 위치에서 필드 범위 정보를 조회한다.
    ///
    /// 커서가 필드 범위 내에 있으면 필드 정보를 JSON으로 반환하고,
    /// 필드 밖이면 `{"inField":false}`를 반환한다.
    pub fn get_field_info_at(
        &self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
    ) -> String {
        let para = match self
            .document
            .sections
            .get(section_idx)
            .and_then(|s| s.paragraphs.get(para_idx))
        {
            Some(p) => p,
            None => return r#"{"inField":false}"#.to_string(),
        };
        field_info_at_in_para(para, char_offset)
    }

    /// 셀/글상자 내 문단의 커서 위치에서 필드 범위 정보를 조회한다.
    pub fn get_field_info_at_in_cell(
        &self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        is_textbox: bool,
    ) -> String {
        let para = (|| {
            let host = self
                .document
                .sections
                .get(section_idx)?
                .paragraphs
                .get(parent_para_idx)?;
            let ctrl = host.controls.get(control_idx)?;
            if is_textbox {
                if let Control::Shape(shape) = ctrl {
                    let tb = shape.drawing()?.text_box.as_ref()?;
                    return tb.paragraphs.get(cell_para_idx);
                }
            } else {
                if let Control::Table(table) = ctrl {
                    let cell = table.cells.get(cell_idx)?;
                    return cell.paragraphs.get(cell_para_idx);
                }
            }
            None
        })();
        match para {
            Some(p) => field_info_at_in_para(p, char_offset),
            None => r#"{"inField":false}"#.to_string(),
        }
    }

    /// path 기반: 중첩 표 셀의 필드 범위 정보를 조회한다.
    pub fn get_field_info_at_by_path(
        &self,
        section_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        char_offset: usize,
    ) -> String {
        match self.resolve_paragraph_by_path(section_idx, parent_para_idx, path) {
            Ok(para) => field_info_at_in_para(para, char_offset),
            Err(_) => r#"{"inField":false}"#.to_string(),
        }
    }

    /// path 기반: 중첩 표 셀 내 활성 필드를 설정한다.
    pub fn set_active_field_by_path(
        &mut self,
        section_idx: usize,
        parent_para_idx: usize,
        path: &[(usize, usize, usize)],
        char_offset: usize,
    ) -> bool {
        use super::super::ActiveFieldInfo;
        let para = match self.resolve_paragraph_by_path(section_idx, parent_para_idx, path) {
            Ok(p) => p,
            Err(_) => return false,
        };
        let ctrl_idx = find_field_ctrl_idx_in_para(para, char_offset);
        if let Some(ci) = ctrl_idx {
            // cell_path: 전체 path를 저장 (중첩 표 구분용)
            let cell_path = Some(path.to_vec());
            let new_info = ActiveFieldInfo {
                section_idx,
                para_idx: parent_para_idx,
                control_idx: ci,
                cell_path,
            };
            if self.active_field.as_ref() != Some(&new_info) {
                self.active_field = Some(new_info);
                self.invalidate_page_tree_cache();
                return true;
            }
        }
        false
    }
}

/// 문단 내 커서 위치의 필드 범위 정보를 JSON으로 반환한다.
fn field_info_at_in_para(para: &Paragraph, char_offset: usize) -> String {
    for fr in &para.field_ranges {
        if fr.start_char_idx != fr.end_char_idx || char_offset != fr.start_char_idx {
            continue;
        }
        if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
            if field.field_type != FieldType::ClickHere {
                continue;
            }
            let guide = field.guide_text().unwrap_or("");
            return format!(
                "{{\"inField\":true,\"fieldId\":{},\"fieldType\":\"{}\",\"startCharIdx\":{},\"endCharIdx\":{},\"isGuide\":true,\"guideName\":{},\"editableInForm\":{}}}",
                field.field_id,
                field.field_type_str(),
                fr.start_char_idx,
                fr.end_char_idx,
                json_escape(guide),
                field.is_editable_in_form(),
            );
        }
    }

    for fr in &para.field_ranges {
        if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
            if field.field_type != FieldType::ClickHere {
                continue;
            }
            // 커서가 필드 범위 내에 있는지 확인 (start 이상, end 이하)
            // end가 exclusive이므로 커서가 end 위치에 있으면 필드 "끝"에 있는 것
            if char_offset >= fr.start_char_idx && char_offset <= fr.end_char_idx {
                let is_guide = fr.start_char_idx == fr.end_char_idx;
                let guide = field.guide_text().unwrap_or("");
                return format!(
                    "{{\"inField\":true,\"fieldId\":{},\"fieldType\":\"{}\",\"startCharIdx\":{},\"endCharIdx\":{},\"isGuide\":{},\"guideName\":{},\"editableInForm\":{}}}",
                    field.field_id,
                    field.field_type_str(),
                    fr.start_char_idx,
                    fr.end_char_idx,
                    is_guide,
                    json_escape(guide),
                    field.is_editable_in_form(),
                );
            }
        }
    }
    r#"{"inField":false}"#.to_string()
}

/// 문단에서 필드를 수집한다 (재귀: 표 셀, 글상자 내부 포함).
fn collect_fields_from_paragraph(
    para: &Paragraph,
    base_location: &FieldLocation,
    list_id: u32,
    para_in_list: usize,
    walk: &mut ListWalk,
    result: &mut Vec<FieldInfo>,
) {
    let host_para_index = if list_id == ROOT_LIST_ID {
        base_location.para_index
    } else {
        para_in_list
    };

    // 현재 문단의 field_ranges에서 필드 수집
    for (fri, fr) in para.field_ranges.iter().enumerate() {
        if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
            let value = if fr.start_char_idx < fr.end_char_idx {
                let chars: Vec<char> = para.text.chars().collect();
                if fr.end_char_idx <= chars.len() {
                    chars[fr.start_char_idx..fr.end_char_idx].iter().collect()
                } else {
                    String::new()
                }
            } else {
                String::new()
            };

            result.push(FieldInfo {
                field: field.clone(),
                location: base_location.clone(),
                value,
                field_range_index: fri,
                list_id,
                para_in_list,
                start_pos: field_content_start(para, fri),
                // 끝은 시작 + **내용 길이**다. 빈 누름틀의 내용은 한글이 채워 넣는 안내문이다.
                end_pos: field_content_start(para, fri)
                    + if fr.start_char_idx == fr.end_char_idx {
                        guide_units(para, fr.control_idx)
                    } else {
                        fr.end_char_idx - fr.start_char_idx
                    },
            });
        }
    }

    // 컨트롤 내부 재귀 탐색 (표 셀, 글상자)
    for (ci, ctrl) in para.controls.iter().enumerate() {
        match ctrl {
            Control::Table(table) => {
                for (cell_i, cell) in table.cells.iter().enumerate() {
                    // 셀에 먼저 번호를 주고 **그 다음** 셀 안으로 내려간다(깊이 우선).
                    let cell_list_id = walk.alloc();
                    walk.lists.push(ListEntry {
                        list_id: cell_list_id,
                        is_cell: true,
                        host_list_id: list_id,
                        section_index: base_location.section_index,
                        host_para_index,
                        control_index: ci,
                        cell_index: cell_i,
                        para_count: cell.paragraphs.len(),
                        grid: Some(CellGrid {
                            row: cell.row,
                            col: cell.col,
                            row_span: cell.row_span,
                            col_span: cell.col_span,
                            cell_count: table.cells.len(),
                        }),
                    });
                    // 셀 자체의 field_name이 있으면 가상 필드로 추가
                    if let Some(ref fname) = cell.field_name {
                        let mut loc = base_location.clone();
                        loc.nested_path.push(NestedEntry::TableCell {
                            control_index: ci,
                            cell_index: cell_i,
                            para_index: 0,
                        });
                        // 셀의 첫 문단 텍스트를 값으로 사용
                        let value = cell
                            .paragraphs
                            .first()
                            .map(|p| p.text.clone())
                            .unwrap_or_default();
                        result.push(FieldInfo {
                            field: Field {
                                ctrl_id: 0,
                                field_id: (ci as u32) << 16 | cell_i as u32,
                                field_type: FieldType::ClickHere,
                                command: String::new(),
                                properties: if cell.editable_in_form() { 1 } else { 0 },
                                extra_properties: 0,
                                ctrl_data_name: Some(fname.clone()),
                                instance_id: None,
                                raw_type: None,
                                memo_index: 0,
                                memo_paragraphs: Vec::new(),
                                memo_text_direction: None,
                                raw_parameters_xml: None,
                                parameters: Default::default(),
                                guide_residue: None,
                                hyperlink_format: None,
                            },
                            location: loc,
                            value,
                            field_range_index: 0,
                            // 셀 필드는 셀 리스트 그 자체를 가리킨다 — 커서는 첫 문단 0 위치다.
                            list_id: cell_list_id,
                            para_in_list: 0,
                            start_pos: 0,
                            end_pos: 0,
                        });
                    }
                    for (pi, cell_para) in cell.paragraphs.iter().enumerate() {
                        let mut loc = base_location.clone();
                        loc.nested_path.push(NestedEntry::TableCell {
                            control_index: ci,
                            cell_index: cell_i,
                            para_index: pi,
                        });
                        collect_fields_from_paragraph(
                            cell_para,
                            &loc,
                            cell_list_id,
                            pi,
                            walk,
                            result,
                        );
                    }
                }
            }
            Control::Shape(shape) => {
                // 글상자도 리스트 하나를 차지한다(한글2022 실측: 표 12칸 다음 글상자가
                // 그 자리에서 아이디를 받고, 그 뒤 표가 이어받는다). **캡션도 마찬가지다** —
                // 안 세면 그 뒤 리스트 번호가 전부 밀린다.
                for (node, paragraphs) in shape_lists(shape) {
                    let box_list_id = walk.alloc();
                    walk.lists.push(ListEntry {
                        list_id: box_list_id,
                        is_cell: false,
                        host_list_id: list_id,
                        section_index: base_location.section_index,
                        host_para_index,
                        control_index: ci,
                        // 묶음 안에서 몇 번째 마디인지 — 사슬 쪽과 같은 번호를 쓴다.
                        cell_index: node,
                        para_count: paragraphs.len(),
                        grid: None,
                    });
                    for (pi, tb_para) in paragraphs.iter().enumerate() {
                        let mut loc = base_location.clone();
                        loc.nested_path.push(NestedEntry::TextBox {
                            control_index: ci,
                            para_index: pi,
                        });
                        collect_fields_from_paragraph(tb_para, &loc, box_list_id, pi, walk, result);
                    }
                }
            }
            _ => {}
        }
    }
}

/// 리스트까지 내려가는 셀 경로 `(control, cell, para)` 를 리스트 표에서 되짚는다.
///
/// 마지막 칸의 문단 번호만 호출 측이 정한다(그 리스트 안에서 캐럿이 있는 문단).
pub(crate) fn cell_path_to_list(
    lists: &[ListEntry],
    list_id: u32,
    para_in_list: usize,
) -> Option<Vec<(usize, usize, usize)>> {
    let mut path = Vec::new();
    let mut current = lists.iter().find(|l| l.list_id == list_id)?;
    let mut para_index = para_in_list;
    loop {
        // 셀만 풀던 자리다. 글상자·캡션도 같은 꼴의 경로를 쓴다 — 둘째 칸이 셀 번호가 아니라
        // 그 개체가 연 리스트 중 몇 번째냐일 뿐이고, 푸는 쪽(`cell_paragraph_at_path`)이
        // 컨트롤 갈래를 보고 가른다. 여기서 막고 있어서 캡션 리스트는 끝이 0 으로 나왔다.
        path.push((current.control_index, current.cell_index, para_index));
        if current.host_list_id == ROOT_LIST_ID {
            break;
        }
        para_index = current.host_para_index;
        current = lists.iter().find(|l| l.list_id == current.host_list_id)?;
    }
    path.reverse();
    Some(path)
}

/// 리스트가 딛고 선 **본문 문단** 번호.
pub(crate) fn root_para_of(lists: &[ListEntry], entry: &ListEntry) -> usize {
    let mut current = entry;
    while current.host_list_id != ROOT_LIST_ID {
        match lists.iter().find(|l| l.list_id == current.host_list_id) {
            Some(host) => current = host,
            None => break,
        }
    }
    current.host_para_index
}

/// 커서 좌표(리스트 아이디 + 그 안의 문단 번호)가 가리키는 문단.
///
/// 리스트 표를 이미 만들어 둔 쪽에서 쓴다 — 표를 다시 만드는 비용을 부르는 쪽이 정한다.
pub(crate) fn cursor_paragraph<'a>(
    core: &'a DocumentCore,
    lists: &[ListEntry],
    list_id: u32,
    para_in_list: usize,
) -> Option<&'a Paragraph> {
    if list_id == ROOT_LIST_ID {
        let (si, pi) = root_para_location(core, para_in_list)?;
        return core.document.sections.get(si)?.paragraphs.get(pi);
    }
    let entry = lists.iter().find(|l| l.list_id == list_id)?;
    let path = cell_path_to_list(lists, list_id, para_in_list)?;
    core.cell_paragraph_at_path(entry.section_index, root_para_of(lists, entry), &path)
}

/// 본문 문단 번호를 `(구역, 그 구역 안 문단)` 으로 푼다.
///
/// **한글의 본문 리스트는 구역을 가로질러 하나로 이어진다.** rhwp 는 구역별로 나눠 들고 있어서
/// 첫 구역만 보면 다구역 문서에서 문단 번호가 통째로 어긋난다(실측: `2026_oss_rst.hwp` 는
/// 두 구역이고 한글은 본문 문단을 0‥14 로 세는데 첫 구역만 보면 0‥7 이다).
pub(crate) fn root_para_location(
    core: &DocumentCore,
    para_in_list: usize,
) -> Option<(usize, usize)> {
    let mut rest = para_in_list;
    for (si, sec) in core.document.sections.iter().enumerate() {
        if rest < sec.paragraphs.len() {
            return Some((si, rest));
        }
        rest -= sec.paragraphs.len();
    }
    None
}

/// 본문이 담은 문단 수 — 구역을 모두 합친다.
pub(crate) fn root_para_count(core: &DocumentCore) -> usize {
    core.document
        .sections
        .iter()
        .map(|s| s.paragraphs.len())
        .sum()
}

/// 코드 유닛 위치를 글자 번호로 되돌린다 — `code_unit_pos` 의 짝.
pub(crate) fn char_idx_at_code_unit(para: &Paragraph, pos: usize) -> usize {
    match para
        .char_offsets
        .iter()
        .position(|offset| *offset as usize >= pos)
    {
        Some(idx) => idx,
        None => para.char_offsets.len(),
    }
}

/// 문단 앞머리의 **자리차지(비 인라인) 컨트롤**이 차지하는 코드 유닛 수.
///
/// 한글의 "문서의 시작"은 이 자리다 — 자리차지 개체의 컨트롤 문자는 건너뛰고, 처음 만나는
/// 인라인 컨트롤이나 글자 앞에서 멈춘다. 컨트롤 하나는 8 코드 유닛이다.
pub(crate) fn leading_anchor_pos(para: &Paragraph) -> usize {
    let mut skipped = 0usize;
    let mut anchored_count = 0usize;
    for ctrl in &para.controls {
        let anchored = match ctrl {
            Control::Table(t) => !t.common.treat_as_char,
            Control::Shape(s) => !s.common().treat_as_char,
            // 누름틀은 **건너뛰면 안 된다** — 그 시작 자리가 캐럿이 서는 곳이다.
            Control::Field(_) => false,
            // 자동 번호는 글자 사이에 놓이는 **인라인**이다. 문단 앞머리에 오더라도 캐럿을
            // 밀지 않는다(실측: 쪽 번호를 셋 끼운 문단에서 `SetPos(…, 3)` 이 3 그대로다).
            Control::AutoNumber(_) | Control::NewNumber(_) => false,
            // 구역·단 정의 같은 표식은 자리를 차지하되 캐럿이 설 곳이 아니다.
            _ => true,
        };
        if !anchored {
            break;
        }
        skipped += 8;
        anchored_count += 1;
    }
    // 컨트롤 개수 × 8 은 **개체들이 스트림에서 맞붙어 있을 때만** 맞는다. 자리차지 개체가
    // 여럿인 문단은 개체 사이에 **공백 글자가 한 칸씩** 있어(한글 실측: 앵커가 16·25·34 로
    // 8 이 아니라 9 씩 벌어진다) 개수 셈이 그만큼 앞질러 간다. `mix-shape-01` 에서 이 함수는
    // 40 을 줬고 한글은 24 였다 — 캐럿이 문단 끝으로 밀려 `SelectCtrlFront` 가 아무 개체도
    // 못 골랐다.
    //
    // 스트림에 글자가 있으면 그 **첫 글자 자리**가 답이다. 개수 셈이 그보다 앞서 나갈 때만
    // 갈아끼운다 — 맞붙어 있는 문단에서는 두 값이 같아 아무것도 안 바뀐다.
    //
    // **0 은 안 믿는다.** 앞머리에 컨트롤이 있는데 첫 글자가 스트림 0 이라는 것은 대응표가
    // 컨트롤을 안 담았다는 뜻이다 — 구역 나누기로 **새로 생긴 문단**이 그렇다(`char_offsets`
    // 가 0 부터 다시 매겨진다). 그 문단에서는 개수 셈이 맞는 답이라 그대로 둔다.
    if anchored_count > 0 {
        if let Some(first_char) = para.char_offsets.first() {
            let first_char = *first_char as usize;
            if first_char > 0 && first_char < skipped {
                skipped = first_char;
            }
        }
    }
    skipped.min((para.char_count as usize).saturating_sub(1))
}

/// 확장 컨트롤 하나가 스트림에서 차지하는 코드 유닛 수.
pub(crate) const EXTENDED_CTRL_UNITS: usize = 8;

/// **블록**이 시작할 수 있는 첫 자리. 캐럿이 설 수 있는 자리([`leading_anchor_pos`])와 다르다.
///
/// 캐럿은 앞머리 자리차지 개체를 전부 건너뛰지만 블록은 그 개체들을 **담을 수 있어야** 한다 —
/// 표를 통째로 잡는 것이 그런 경우다. 한글이 건너뛰는 것은 구역·단 정의처럼 자리만 차지하는
/// 표식뿐이다(본문 첫 문단 `SelectAll` 실측: 캐럿 시작은 72, 블록 시작은 16 = 표식 둘).
pub(crate) fn select_start_pos(para: &Paragraph) -> usize {
    para.controls
        .iter()
        .take_while(|ctrl| matches!(ctrl, Control::SectionDef(_) | Control::ColumnDef(_)))
        .count()
        * EXTENDED_CTRL_UNITS
}

/// rhwp 의 글자 번호를 **한글이 보는 스트림 위치**(코드 유닛)로 옮긴다.
///
/// `char_offsets` 를 쓰지 않는다. 그 배열은 적재 때 안내문을 지우면서 추정으로 다시 쓰여
/// 문단마다 다르게 세고(계획서 §4.6.1), 무엇보다 **rhwp 모델과 한글 스트림이 다른 문서**가
/// 됐다는 사실을 담지 못한다.
///
/// 원본 바이트로 확인한 세 규칙(영수증 서식 6개 필드 전수 일치):
///
/// 1. 글자 하나는 1칸.
/// 2. 확장 컨트롤(표·개체·누름틀 시작/끝)은 8칸. 누름틀 하나가 시작·끝 **두 개**를 낸다.
/// 3. **빈 누름틀은 안내문 글자를 스트림에 담는다.** rhwp 는 적재 때 그것을 지우지만
///    한글은 파일을 열며 다시 채운다 — 그래서 그 뒤 위치가 안내문 길이만큼 밀린다.
pub(crate) fn stream_pos(para: &Paragraph, char_idx: usize) -> usize {
    let control_positions = para.control_text_positions();
    let mut units = char_idx + tab_padding(para, char_idx);

    // 필드가 아닌 확장 컨트롤 — 자기 자리에서 8칸.
    //
    // (컨트롤의 **앵커 자리**를 구할 때는 이 셈을 쓰면 안 된다. 문단마다 자리표 글자를
    // 남기는 것과 안 남기는 것이 섞여 있어서 여기서 갈라 주지 못한다 — 앵커는
    // `controls_json` 이 컨트롤을 차례로 걸으며 따로 센다.)
    for (ci, ctrl) in para.controls.iter().enumerate() {
        if matches!(ctrl, Control::Field(_)) {
            continue;
        }
        if control_positions
            .get(ci)
            .is_some_and(|pos| *pos <= char_idx)
        {
            units += ctrl_stream_units(ctrl);
        }
    }

    // 누름틀 — 시작 코드, 끝 코드, 그리고 빈 필드면 안내문 글자.
    for fr in &para.field_ranges {
        if fr.start_char_idx <= char_idx {
            units += EXTENDED_CTRL_UNITS;
        }
        if fr.end_char_idx <= char_idx {
            units += EXTENDED_CTRL_UNITS;
            if fr.start_char_idx == fr.end_char_idx {
                units += guide_units(para, fr.control_idx);
            }
        }
    }
    units
}

/// 그리기 개체 하나가 여는 **글 리스트들** — 글상자와 **캡션**이다.
///
/// 첫 값은 그 개체 안에서 몇 번째 리스트인지다. 리스트 표(`cell_index` 자리)와 컨트롤 사슬이
/// 이 번호를 같이 써서 둘이 **같은 마디를 같은 이름으로** 가리킨다.
///
/// 캡션을 안 세던 것이 리스트 번호가 밀리던 뿌리였다(실측: `samples/draw-group.hwp` 의 묶음은
/// 글상자가 없는데도 한글이 list 2 를 주고, 그 부모가 바로 그 묶음이며, 안에 `atno` 가 든
/// 가운데 정렬 한 문단이다 — 캡션이다).
///
/// 글상자와 캡션을 **둘 다** 가진 개체의 앞뒤 순서는 아직 못 쟀다. 그런 표본을 만나면 그때
/// 실측해서 고칠 것 — 지금 순서는 기존에 검증된 글상자 자리를 지키려고 글상자를 앞에 둔 것뿐이다.
pub(crate) fn shape_lists(shape: &crate::model::shape::ShapeObject) -> Vec<(usize, &[Paragraph])> {
    let mut out: Vec<(usize, &[Paragraph])> = Vec::new();
    if let Some(tb) = shape.drawing().and_then(|d| d.text_box.as_ref()) {
        out.push((0, tb.paragraphs.as_slice()));
    }
    let caption = match shape {
        crate::model::shape::ShapeObject::Group(g) => g.caption.as_ref(),
        other => other.drawing().and_then(|d| d.caption.as_ref()),
    };
    if let Some(cap) = caption {
        if !cap.paragraphs.is_empty() {
            out.push((1, cap.paragraphs.as_slice()));
        }
    }
    out
}

/// 컨트롤 하나가 **글자 몫을 빼고** 스트림에서 더 차지하는 칸 수.
///
/// 확장 컨트롤은 8칸인데, 그중 자동 번호 계열은 파서가 **자리표 글자 한 칸**을 텍스트에 남긴다
/// (`parse_para_text` 의 `0x0012` 가지가 공백을 넣는다). 그 한 칸은 이미 글자로 세어졌으므로
/// 여기서 8을 더하면 아홉이 된다 — 오라클은 여덟이다(실측: `InsertPageNum` 뒤 문단 끝 7 → 15).
fn ctrl_stream_units(ctrl: &Control) -> usize {
    match ctrl {
        Control::AutoNumber(_) | Control::NewNumber(_) => EXTENDED_CTRL_UNITS - 1,
        _ => EXTENDED_CTRL_UNITS,
    }
}

/// 탭이 스트림에서 더 차지하는 칸 수.
///
/// 파서는 탭(`0x0009`)을 **글자 하나** `'\t'` 로 담는데 한글 스트림에서 탭은 **8칸**이다
/// (`parse_para_text` 의 탭 가지가 `pos += 16` 으로 넘어간다 — 16바이트 = 8 코드 유닛).
/// 그래서 탭이 든 문단은 그 뒤 자리가 탭 하나당 7칸씩 앞당겨져 보였다. 누름틀 좌표가
/// 어긋나는 결함이라, 오라클 실측(`InsertTab` 뒤 캐럿 3 → 11)으로 확인하고 여기서 메운다.
fn tab_padding(para: &Paragraph, char_idx: usize) -> usize {
    para.text
        .chars()
        .take(char_idx)
        .filter(|c| *c == '\t')
        .count()
        * (EXTENDED_CTRL_UNITS - 1)
}

/// 빈 누름틀이 스트림에 담는 안내문 길이(글자 수). 안내문이 없으면 0.
fn guide_units(para: &Paragraph, control_idx: usize) -> usize {
    match para.controls.get(control_idx) {
        Some(Control::Field(field)) => field.guide_text().map(|g| g.chars().count()).unwrap_or(0),
        _ => 0,
    }
}

/// 문단이 스트림에서 차지하는 코드 유닛 수 — 끝 문단 부호는 빼고 센다.
///
/// 앞머리 자리차지 자리를 **바닥으로 깐다.** 컨트롤 중에는 문단 텍스트에 자리표 글자를 남기지
/// 않는 것이 있어서([`Paragraph::control_text_positions`] 가 자리를 못 주는 것들 — 구역·단
/// 정의 같은 표식) 텍스트만 세면 문단이 실제보다 짧게 나온다. 본문 첫 문단이 그런 꼴인데,
/// 그러면 시작(72)이 끝(24)보다 커지는 있을 수 없는 상태가 된다. 한글은 그 문단의 시작도 끝도
/// 72 로 답한다(`MoveDocBegin`·`MoveSelParaEnd` 실측).
pub(crate) fn stream_len(para: &Paragraph) -> usize {
    stream_pos(para, para.text.chars().count()).max(leading_anchor_pos(para))
}

/// 누름틀 **내용이 시작하는** 스트림 위치.
///
/// [`stream_pos`] 를 그대로 쓰면 안 된다 — 그 함수는 "그 자리의 글자"를 기준으로 세기 때문에
/// 빈 누름틀에서는 **자기 FIELD_END 와 자기 안내문까지** 앞선 것으로 친다. 내용의 시작은
/// 자기 FIELD_BEGIN **바로 뒤**다.
pub(crate) fn field_content_start(para: &Paragraph, field_range_index: usize) -> usize {
    let Some(own) = para.field_ranges.get(field_range_index) else {
        return 0;
    };
    let control_positions = para.control_text_positions();
    let mut units = own.start_char_idx + tab_padding(para, own.start_char_idx);

    for (ci, ctrl) in para.controls.iter().enumerate() {
        if matches!(ctrl, Control::Field(_)) {
            continue;
        }
        if control_positions
            .get(ci)
            .is_some_and(|pos| *pos <= own.start_char_idx)
        {
            units += ctrl_stream_units(ctrl);
        }
    }

    for (i, fr) in para.field_ranges.iter().enumerate() {
        if i == field_range_index {
            continue; // 자기 것은 아래에서 시작 코드만 더한다
        }
        if fr.start_char_idx <= own.start_char_idx {
            units += EXTENDED_CTRL_UNITS;
        }
        if fr.end_char_idx <= own.start_char_idx {
            units += EXTENDED_CTRL_UNITS;
            if fr.start_char_idx == fr.end_char_idx {
                units += guide_units(para, fr.control_idx);
            }
        }
    }

    units + EXTENDED_CTRL_UNITS // 자기 FIELD_BEGIN
}

/// 캐럿이 설 수 있는 자리들 — 한 글자 이동(`MoveNextChar` 류)이 딛는 눈금.
///
/// 한글 실측(영수증 서식 list 9): `0 · 8 · 22 · 23 · 24 · 25 · 33 · 47 · 48 · 49`.
/// 규칙은 세 가지다.
///
/// - 글자마다 한 자리.
/// - 누름틀은 **시작 코드 앞**과 **내용 시작**에 자리가 있다. 끝 코드 앞에는 없다 —
///   빈 누름틀에서 한 칸 가면 안내문과 끝 코드를 **한꺼번에 건너뛴다**(8 → 22).
/// - 문단 끝에 한 자리.
pub(crate) fn caret_stops(para: &Paragraph) -> Vec<usize> {
    let mut stops = Vec::new();
    for (fri, _) in para.field_ranges.iter().enumerate() {
        let content = field_content_start(para, fri);
        stops.push(content.saturating_sub(EXTENDED_CTRL_UNITS)); // 시작 코드 앞
        stops.push(content);
    }
    let len = para.text.chars().count();
    for i in 0..len {
        stops.push(stream_pos(para, i));
    }
    stops.push(stream_len(para));
    stops.sort_unstable();
    stops.dedup();
    stops
}

/// 단어가 시작하는 자리들 — `MoveNextWord`·`MovePrevWord` 가 딛는 눈금.
///
/// 한글2022 실측(두 셀 · 두 방향 자기정합). 단어는 **공백으로 나뉜 덩어리**이고, 누름틀은
/// 그 자체가 경계를 만든다.
///
/// | 자리 | 왜 |
/// |---|---|
/// | 문단 시작·끝 | 언제나 |
/// | 앞이 공백인 글자 | 평문 규칙 — 문장부호는 단어를 안 가른다(`!@` 는 한 덩어리) |
/// | 누름틀 시작 코드 자리 | 필드가 시작하면 새 단어 |
/// | 누름틀 내용 시작 | 안내문/내용이 새 단어 |
///
/// 끝 코드(FIELD_END)는 경계가 **아니다** — 필드 바로 뒤 글자는 앞 단어에 붙는다
/// (list 9 에서 22 번 '부' 가 단어 시작이 아니다).
pub(crate) fn word_starts(para: &Paragraph) -> Vec<usize> {
    let mut starts = vec![leading_anchor_pos(para)];

    for (fri, _) in para.field_ranges.iter().enumerate() {
        let content = field_content_start(para, fri);
        starts.push(content.saturating_sub(EXTENDED_CTRL_UNITS));
        starts.push(content);
    }

    // 공백 다음 글자가 단어 시작이다. 단 **스트림에서 바로 이웃**이어야 한다 — 사이에 누름틀이
    // 끼면(공백 … 필드 … 글자) 그 글자는 앞 단어에 붙는다(list 9 의 47 번 '까').
    let chars: Vec<char> = para.text.chars().collect();
    for i in 1..chars.len() {
        if chars[i - 1].is_whitespace()
            && !chars[i].is_whitespace()
            && stream_pos(para, i) == stream_pos(para, i - 1) + 1
        {
            starts.push(stream_pos(para, i));
        }
    }

    starts.push(stream_len(para));
    starts.sort_unstable();
    starts.dedup();
    starts
}

/// 지금 단어의 끝 — `MoveWordEnd` 가 가는 자리.
///
/// **다음 공백 글자의 자리**다(실측: `가나 다라마` 에서 4 → 6, 1 → 2). 마지막 단어면 문단 끝.
pub(crate) fn word_end_from(para: &Paragraph, pos: usize) -> usize {
    let chars: Vec<char> = para.text.chars().collect();
    for (i, ch) in chars.iter().enumerate() {
        let at = stream_pos(para, i);
        if at >= pos && ch.is_whitespace() {
            return at;
        }
    }
    stream_len(para)
}

/// [`stream_pos`] 의 역 — 한글이 준 스트림 위치를 rhwp 의 글자 번호로 되돌린다.
///
/// 문단은 짧아서 훑어도 된다. 대응표를 따로 두면 편집 때마다 둘이 어긋난다.
pub(crate) fn char_idx_at_stream_pos(para: &Paragraph, pos: usize) -> usize {
    let len = para.text.chars().count();
    (0..=len)
        .find(|&i| stream_pos(para, i) >= pos)
        .unwrap_or(len)
}

/// 글자 번호를 문단 안의 **코드 유닛 위치**로 옮긴다 (옛 경로).
///
/// 한글의 `pos` 는 글자 수가 아니라 코드 유닛이다 — 확장 컨트롤(표·누름틀 시작/끝)이 8칸을
/// 차지한다. `char_offsets` 가 그 대응표다.
#[allow(dead_code)]
fn code_unit_pos(para: &Paragraph, char_idx: usize, control_idx: usize) -> usize {
    if let Some(offset) = para.char_offsets.get(char_idx) {
        return *offset as usize;
    }
    if para.char_offsets.is_empty() {
        // 글자가 없는 문단(개체만 늘어선 본문 문단 등)에는 대응표가 없다. 앞선 컨트롤을
        // 세어 자리를 짚는다 — 확장 컨트롤은 8칸, 필드는 시작·끝 두 개라 16칸이다.
        let before: usize = para
            .controls
            .iter()
            .take(control_idx)
            .map(|c| {
                if matches!(c, Control::Field(_)) {
                    16
                } else {
                    8
                }
            })
            .sum();
        return before + 8; // 자기 FIELD_BEGIN 뒤가 텍스트 자리다
    }
    // 글자 끝을 넘어선 자리 — 문단 길이(끝 문단 부호 제외)로 잡는다.
    para.char_offsets
        .last()
        .map(|last| *last as usize + 1)
        .unwrap_or_else(|| (para.char_count as usize).saturating_sub(1))
}

/// 문단 CTRL_DATA 레코드의 필드 이름 부분을 새 이름으로 다시 쓴다.
///
/// 레이아웃은 파서 대칭이다(`parser::body_text::parse_ctrl_data_field_name`):
/// 헤더 10바이트 + 이름 길이(u16 LE, 글자 수) + UTF-16LE 이름.
/// 인코더가 둘이 되면 한쪽만 고쳐져 조용히 어긋나므로 여기 하나만 둔다.
pub(crate) fn write_ctrl_data_name(
    records: &mut Vec<Option<Vec<u8>>>,
    control_idx: usize,
    new_name: &str,
) {
    while records.len() <= control_idx {
        records.push(None);
    }
    let name_chars: Vec<u16> = new_name.encode_utf16().collect();
    let mut data = match &records[control_idx] {
        // 원본이 있으면 헤더(10바이트)를 보존한다 — 한컴이 남긴 paramset 값이 들어 있다.
        Some(existing) if existing.len() >= 12 => existing[..10].to_vec(),
        Some(_) => return, // 12바이트 미만은 이름 자리가 없는 레코드다. 건드리지 않는다.
        None => vec![0x1Bu8, 0x02, 0x01, 0x00, 0x00, 0x00, 0x00, 0x40, 0x01, 0x00],
    };
    data.extend_from_slice(&(name_chars.len() as u16).to_le_bytes());
    for ch in &name_chars {
        data.extend_from_slice(&ch.to_le_bytes());
    }
    records[control_idx] = Some(data);
}

/// FieldLocation을 JSON으로 변환
fn field_location_json(loc: &FieldLocation) -> String {
    if loc.nested_path.is_empty() {
        format!(
            "{{\"sectionIndex\":{},\"paraIndex\":{}}}",
            loc.section_index, loc.para_index,
        )
    } else {
        let path_entries: Vec<String> = loc.nested_path.iter().map(|e| match e {
            NestedEntry::TableCell { control_index, cell_index, para_index } => {
                format!("{{\"type\":\"cell\",\"controlIndex\":{},\"cellIndex\":{},\"paraIndex\":{}}}",
                    control_index, cell_index, para_index)
            }
            NestedEntry::TextBox { control_index, para_index } => {
                format!("{{\"type\":\"textbox\",\"controlIndex\":{},\"paraIndex\":{}}}",
                    control_index, para_index)
            }
        }).collect();
        format!(
            "{{\"sectionIndex\":{},\"paraIndex\":{},\"path\":[{}]}}",
            loc.section_index,
            loc.para_index,
            path_entries.join(","),
        )
    }
}

fn para_at_location<'a>(core: &'a DocumentCore, location: &FieldLocation) -> Option<&'a Paragraph> {
    let mut para = core
        .document
        .sections
        .get(location.section_index)?
        .paragraphs
        .get(location.para_index)?;

    for entry in &location.nested_path {
        para = match entry {
            NestedEntry::TableCell {
                control_index,
                cell_index,
                para_index,
            } => {
                let ctrl = para.controls.get(*control_index)?;
                if let Control::Table(table) = ctrl {
                    table.cells.get(*cell_index)?.paragraphs.get(*para_index)?
                } else {
                    return None;
                }
            }
            NestedEntry::TextBox {
                control_index,
                para_index,
            } => {
                let ctrl = para.controls.get(*control_index)?;
                if let Control::Shape(shape) = ctrl {
                    shape
                        .drawing()?
                        .text_box
                        .as_ref()?
                        .paragraphs
                        .get(*para_index)?
                } else {
                    return None;
                }
            }
        };
    }

    Some(para)
}

fn field_range_bounds(core: &DocumentCore, fi: &FieldInfo) -> Option<(usize, usize)> {
    let para = para_at_location(core, &fi.location)?;
    let range = para.field_ranges.get(fi.field_range_index)?;
    Some((range.start_char_idx, range.end_char_idx))
}

impl DocumentCore {
    /// 본문 문단에서 커서 위치의 필드 컨트롤 인덱스를 찾는다.
    fn find_field_control_idx(
        &self,
        section_idx: usize,
        para_idx: usize,
        char_offset: usize,
        _cell_path: Option<(usize, usize, usize)>,
    ) -> Option<usize> {
        let para = self
            .document
            .sections
            .get(section_idx)?
            .paragraphs
            .get(para_idx)?;
        find_field_ctrl_idx_in_para(para, char_offset)
    }

    /// 셀/글상자 내 문단에서 커서 위치의 필드 컨트롤 인덱스를 찾는다.
    fn find_field_control_idx_in_cell(
        &self,
        section_idx: usize,
        parent_para_idx: usize,
        control_idx: usize,
        cell_idx: usize,
        cell_para_idx: usize,
        char_offset: usize,
        is_textbox: bool,
    ) -> Option<usize> {
        let host = self
            .document
            .sections
            .get(section_idx)?
            .paragraphs
            .get(parent_para_idx)?;
        let ctrl = host.controls.get(control_idx)?;
        let para = if is_textbox {
            if let Control::Shape(shape) = ctrl {
                let tb = shape.drawing()?.text_box.as_ref()?;
                tb.paragraphs.get(cell_para_idx)?
            } else {
                return None;
            }
        } else {
            if let Control::Table(table) = ctrl {
                table.cells.get(cell_idx)?.paragraphs.get(cell_para_idx)?
            } else {
                return None;
            }
        };
        find_field_ctrl_idx_in_para(para, char_offset)
    }

    pub(crate) fn next_click_here_field_id(&self) -> u32 {
        let mut max_id = 0u32;
        for section in &self.document.sections {
            for para in &section.paragraphs {
                collect_max_field_id(para, &mut max_id);
            }
        }
        max_id.saturating_add(1).max(1)
    }
}

pub(crate) fn collect_max_field_id(para: &Paragraph, max_id: &mut u32) {
    for end in &para.orphan_field_ends {
        *max_id = (*max_id).max(end.begin_id_ref).max(end.field_id);
    }
    for range in &para.field_ranges {
        *max_id = (*max_id).max(range.end_field_id);
    }
    for ctrl in &para.controls {
        match ctrl {
            Control::Field(field) => {
                *max_id = (*max_id)
                    .max(field.field_id)
                    .max(field.instance_id.unwrap_or(0));
                for p in &field.memo_paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::Header(h) => {
                for p in &h.paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::Footer(h) => {
                for p in &h.paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::Footnote(h) => {
                for p in &h.paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::Endnote(h) => {
                for p in &h.paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::HiddenComment(h) => {
                for p in &h.paragraphs {
                    collect_max_field_id(p, max_id);
                }
            }
            Control::SectionDef(s) => {
                for m in &s.master_pages {
                    for p in &m.paragraphs {
                        collect_max_field_id(p, max_id);
                    }
                }
            }
            Control::Table(table) => {
                for cell in &table.cells {
                    for cell_para in &cell.paragraphs {
                        collect_max_field_id(cell_para, max_id);
                    }
                }
                if let Some(caption) = &table.caption {
                    for cap_para in &caption.paragraphs {
                        collect_max_field_id(cap_para, max_id);
                    }
                }
            }
            Control::Shape(shape) => collect_shape_field_ids(shape, max_id),
            Control::Picture(pic) => {
                if let Some(caption) = &pic.caption {
                    for cap_para in &caption.paragraphs {
                        collect_max_field_id(cap_para, max_id);
                    }
                }
            }
            _ => {}
        }
    }
}

// 필드 ID는 본문뿐 아니라 그룹 도형·캡션·글상자에서도 문서 전체에 걸쳐 고유하다.
fn collect_shape_field_ids(shape: &crate::model::shape::ShapeObject, max_id: &mut u32) {
    use crate::model::shape::ShapeObject;
    if let Some(drawing) = shape.drawing() {
        if let Some(text_box) = &drawing.text_box {
            for p in &text_box.paragraphs {
                collect_max_field_id(p, max_id);
            }
        }
        if let Some(caption) = &drawing.caption {
            for p in &caption.paragraphs {
                collect_max_field_id(p, max_id);
            }
        }
    }
    let caption = match shape {
        ShapeObject::Group(g) => {
            for child in &g.children {
                collect_shape_field_ids(child, max_id);
            }
            g.caption.as_ref()
        }
        ShapeObject::Picture(p) => p.caption.as_ref(),
        ShapeObject::Chart(c) => c.caption.as_ref(),
        ShapeObject::Ole(o) => o.caption.as_ref(),
        _ => None,
    };
    if let Some(caption) = caption {
        for p in &caption.paragraphs {
            collect_max_field_id(p, max_id);
        }
    }
}

fn insert_click_here_field_in_para(
    para: &mut Paragraph,
    char_offset: usize,
    field_id: u32,
    guide: &str,
    memo: &str,
    name: &str,
    editable: bool,
) -> Result<usize, HwpError> {
    let field = Field {
        field_type: FieldType::ClickHere,
        // [#1434] 이름은 ctrl_data_name(CTRL_DATA 0x57)으로 별도 저장하므로 command 에
        // 넣지 않는다 (Name 키가 끼면 한컴이 안내문 바인딩 실패).
        command: Field::build_clickhere_command(guide, memo),
        properties: if editable { 1 } else { 0 },
        extra_properties: 0x09,
        field_id,
        ctrl_id: tags::FIELD_CLICKHERE,
        instance_id: None,
        raw_type: None,
        ctrl_data_name: if name.is_empty() {
            None
        } else {
            Some(name.to_string())
        },
        memo_index: 0,
        memo_paragraphs: Vec::new(),
        memo_text_direction: None,
        raw_parameters_xml: None,
        parameters: Default::default(),
        guide_residue: None,
        hyperlink_format: None,
    };

    insert_field_in_para(para, char_offset, field).map(|(start, _)| start)
}

/// 문단의 글자 자리에 빈 필드를 넣고 (시작 글자, 필드 컨트롤 번호)를 돌려준다.
pub(crate) fn insert_field_in_para(
    para: &mut Paragraph,
    char_offset: usize,
    field: Field,
) -> Result<(usize, usize), HwpError> {
    let text_len = para.text.chars().count();
    let start = char_offset.min(text_len);
    let gaps = raw_slot_gaps(para)?;
    // 새 BEGIN·END는 시작 글자 바로 앞, 그 갭의 끝에 놓인다. 거기까지의 슬롯에서
    // 거기까지 끝난 누름틀의 END를 빼면 앞에 남는 컨트롤 수다.
    let insert_pos = gaps[start].1;
    let insert_idx = gaps[..=start]
        .iter()
        .map(|&(gap_start, gap_end)| ((gap_end - gap_start) / 8) as usize)
        .sum::<usize>()
        - para
            .field_ranges
            .iter()
            .filter(|range| range.end_char_idx <= start)
            .count();

    for range in &mut para.field_ranges {
        if range.control_idx >= insert_idx {
            range.control_idx += 1;
        }
    }

    para.controls.insert(insert_idx, Control::Field(field));
    if para.ctrl_data_records.len() < insert_idx {
        para.ctrl_data_records.resize(insert_idx, None);
    }
    para.ctrl_data_records.insert(insert_idx, None);

    let new_range = FieldRange {
        start_char_idx: start,
        end_char_idx: start,
        control_idx: insert_idx,
        ..Default::default()
    };
    let range_idx = para
        .field_ranges
        .iter()
        .position(|range| {
            range.start_char_idx > start
                || (range.start_char_idx == start && range.control_idx > insert_idx)
        })
        .unwrap_or(para.field_ranges.len());
    para.field_ranges.insert(range_idx, new_range);
    for offset in &mut para.char_offsets[start..] {
        *offset += 16;
    }
    para.shift_position_metadata_for_stream_insertion(insert_pos, 16);
    // 문단 끝 표시 앞까지의 슬롯과 글자에 새 슬롯 16유닛, 끝 표시 1유닛을 더한다.
    para.char_count = gaps[text_len].1 + 16 + 1;
    para.invalidate_layout_inputs();

    Ok((start, insert_idx))
}

/// 문단에서 커서 위치의 ClickHere 필드 컨트롤 인덱스를 반환한다.
fn find_field_ctrl_idx_in_para(para: &Paragraph, char_offset: usize) -> Option<usize> {
    // 인접 누름틀 경계에서는 앞 누름틀의 끝과 다음 빈 누름틀의 시작이
    // 같은 charOffset을 공유한다. 새 빈 누름틀을 먼저 잡아야 첫 입력이
    // 앞 누름틀 값으로 붙지 않는다.
    for fr in &para.field_ranges {
        if fr.start_char_idx == fr.end_char_idx && char_offset == fr.start_char_idx {
            if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
                if field.field_type == FieldType::ClickHere {
                    return Some(fr.control_idx);
                }
            }
        }
    }

    for fr in &para.field_ranges {
        if let Some(Control::Field(field)) = para.controls.get(fr.control_idx) {
            if field.field_type != FieldType::ClickHere {
                continue;
            }
            if char_offset >= fr.start_char_idx && char_offset <= fr.end_char_idx {
                return Some(fr.control_idx);
            }
        }
    }
    None
}

/// 문단 내 커서 위치의 누름틀 필드를 제거하고 지운 컨트롤 번호를 돌려준다.
///
/// 대상은 `getFieldInfoAt` 과 같은 규칙으로 고른다. 누름틀의 BEGIN·END 슬롯과 내용 글자만
/// 지우고 다른 컨트롤의 슬롯은 제자리에 둔다.
fn remove_field_in_para(para: &mut Paragraph, char_offset: usize) -> Result<usize, HwpError> {
    let control_idx = find_field_ctrl_idx_in_para(para, char_offset)
        .ok_or_else(|| HwpError::InvalidField("커서 위치에 누름틀 필드 없음".into()))?;
    remove_field_control_in_para(para, control_idx)
}

/// 문단의 필드 컨트롤 하나를 BEGIN·END 슬롯과 내용 글자째 지운다.
pub(crate) fn remove_field_control_in_para(
    para: &mut Paragraph,
    control_idx: usize,
) -> Result<usize, HwpError> {
    let gaps = raw_slot_gaps(para)?;
    let range_idx = para
        .field_ranges
        .iter()
        .position(|range| range.control_idx == control_idx)
        .ok_or_else(invalid_raw_slots)?;
    let (start, end) = (
        para.field_ranges[range_idx].start_char_idx,
        para.field_ranges[range_idx].end_char_idx,
    );
    // 내용 글자를 지우면 BEGIN이 있는 시작 갭과 END가 있는 끝 갭이 하나로 합쳐진다. 갭 안의
    // 순서는 원본이 남기지 않으므로 삽입과 같이 합친 갭의 끝에서 두 슬롯을 뺀다.
    let content: u32 = para
        .text
        .chars()
        .skip(start)
        .take(end - start)
        .map(|ch| if ch == '\t' { 8 } else { ch.len_utf16() as u32 })
        .sum();
    let merged = gaps[end].1 - gaps[start].0 - content;
    let para_end = gaps[gaps.len() - 1].1 - content - 16;

    para.field_ranges.remove(range_idx);
    if end > start {
        para.delete_text_at(start, end - start);
    }
    let slots = gaps[start].0 + merged - 16;
    let shift = |position: &mut u32| {
        if *position > slots {
            *position = position.saturating_sub(16).max(slots);
        }
    };
    for position in &mut para.char_offsets {
        shift(position);
    }
    for shape in &mut para.char_shapes {
        shift(&mut shape.start_pos);
    }
    for range in &mut para.range_tags {
        shift(&mut range.start);
        shift(&mut range.end);
    }
    for mark in &mut para.markpen_marks {
        if let Some(position) = &mut mark.utf16_pos {
            shift(position);
        }
    }
    para.char_count = para_end + 1;
    // 슬롯 자리에서 시작하던 글자모양이 뒤 글자 경계와 겹치면 뒤 글자에 쓰이던 것을 남긴다.
    let shapes = std::mem::take(&mut para.char_shapes);
    for shape in shapes {
        if para
            .char_shapes
            .last()
            .is_some_and(|last| last.start_pos == shape.start_pos)
        {
            para.char_shapes.pop();
        }
        para.char_shapes.push(shape);
    }
    para.invalidate_layout_inputs();

    para.controls.remove(control_idx);
    if control_idx < para.ctrl_data_records.len() {
        para.ctrl_data_records.remove(control_idx);
    }
    for range in &mut para.field_ranges {
        if range.control_idx > control_idx {
            range.control_idx -= 1;
        }
    }
    para.forget_para_text_if_emptied();
    Ok(control_idx)
}

fn invalid_raw_slots() -> HwpError {
    HwpError::InvalidField("누름틀의 원시 슬롯 위치를 확인할 수 없습니다.".into())
}

/// 글자 앞 갭마다 원시 `(시작, 끝)` 위치를 돌려준다. 마지막 갭은 문단 끝 표시 앞이다.
///
/// 갭은 8유닛 슬롯(컨트롤과 FIELD_END)으로만 채워지고, 누름틀 BEGIN은 시작 갭에, END는 끝
/// 갭에 있어야 한다. 숨은 슬롯이 있거나 갭마다 거기까지의 슬롯 수가 이 배치와 맞지 않으면
/// 위치를 추정하지 않고 오류를 낸다.
pub(crate) fn raw_slot_gaps(para: &Paragraph) -> Result<Vec<(u32, u32)>, HwpError> {
    if !para.title_marks.is_empty()
        || !para.orphan_field_ends.is_empty()
        || para.text.contains('\u{fffc}')
        || para.char_offsets.len() != para.text.chars().count()
        || para.controls.iter().any(|control| {
            matches!(
                control,
                Control::Hyperlink(_)
                    | Control::AutoNumber(_)
                    | Control::NewNumber(_)
                    | Control::Ruby(_)
                    | Control::CharOverlap(_)
                    | Control::Unknown(_)
            )
        })
    {
        return Err(invalid_raw_slots());
    }
    let mut gaps = Vec::with_capacity(para.char_offsets.len() + 1);
    let mut end = 0u32;
    let mut inner = 0;
    for (&offset, ch) in para.char_offsets.iter().zip(para.text.chars()) {
        let units = offset
            .checked_sub(end)
            .filter(|units| units % 8 == 0)
            .ok_or_else(invalid_raw_slots)?;
        inner += (units / 8) as usize;
        gaps.push((end, offset));
        end = offset + if ch == '\t' { 8 } else { ch.len_utf16() as u32 };
    }
    // 문단 끝 갭에는 남은 슬롯이 온다. 합성 문단은 char_count가 어긋나 있기도 해서 쓰지 않는다.
    let ranges = &para.field_ranges;
    let tail = (para.controls.len() + ranges.len())
        .checked_sub(inner)
        .ok_or_else(invalid_raw_slots)?;
    gaps.push((end, end + 8 * tail as u32));
    let mut slots = 0;
    let mut placed = 0;
    for (gap, &(start, end)) in gaps.iter().enumerate() {
        slots += ((end - start) / 8) as usize;
        // 여기까지 온 슬롯에서 끝난 누름틀의 END를 뺀 컨트롤 수는 줄지 않고, 시작한 누름틀의
        // BEGIN을 모두 포함하며, 아직 시작하지 않은 누름틀의 BEGIN은 포함하지 않아야 한다.
        let ends = ranges
            .iter()
            .filter(|range| range.end_char_idx <= gap)
            .count();
        let begun = ranges
            .iter()
            .filter(|range| range.start_char_idx <= gap)
            .map(|range| range.control_idx + 1)
            .max()
            .unwrap_or(0);
        let before_next = ranges
            .iter()
            .filter(|range| range.start_char_idx > gap)
            .map(|range| range.control_idx)
            .min()
            .unwrap_or(para.controls.len());
        placed = slots
            .checked_sub(ends)
            .filter(|&controls| controls >= placed && (begun..=before_next).contains(&controls))
            .ok_or_else(invalid_raw_slots)?;
    }
    Ok(gaps)
}

/// 문자열을 JSON 이스케이프한다.
pub(crate) fn json_escape(s: &str) -> String {
    let mut result = String::with_capacity(s.len() + 2);
    result.push('"');
    for c in s.chars() {
        match c {
            '"' => result.push_str("\\\""),
            '\\' => result.push_str("\\\\"),
            '\n' => result.push_str("\\n"),
            '\r' => result.push_str("\\r"),
            '\t' => result.push_str("\\t"),
            c if (c as u32) < 0x20 => {
                result.push_str(&format!("\\u{:04x}", c as u32));
            }
            _ => result.push(c),
        }
    }
    result.push('"');
    result
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::control::{Control, Field, FieldType};
    use crate::model::document::Section;
    use crate::model::paragraph::{FieldRange, LineSeg, Paragraph};
    use crate::model::table::{Cell, Table};

    fn make_field_control(ctrl_id: u32) -> Control {
        Control::Field(Field {
            field_type: FieldType::ClickHere,
            command: String::new(),
            properties: 0,
            extra_properties: 0,
            field_id: ctrl_id,
            ctrl_id,
            instance_id: None,
            raw_type: None,
            ctrl_data_name: None,
            memo_index: 0,
            memo_paragraphs: Vec::new(),
            memo_text_direction: None,
            raw_parameters_xml: None,
            parameters: Default::default(),
            guide_residue: None,
            hyperlink_format: None,
        })
    }

    fn para_with_click_here_field() -> Paragraph {
        // 스트림: [ColumnDef 8B] A B C [FIELD_BEGIN] X Y [FIELD_END], 필드는 [3,5]
        Paragraph {
            text: "ABCXY".into(),
            controls: vec![
                Control::ColumnDef(Default::default()),
                make_field_control(100),
            ],
            field_ranges: vec![FieldRange {
                start_char_idx: 3,
                end_char_idx: 5,
                control_idx: 1,
                ..Default::default()
            }],
            char_count: 21,
            char_offsets: vec![8, 9, 10, 19, 20],
            ..Default::default()
        }
    }

    #[test]
    fn tab_occupies_eight_stream_units() {
        // 한글 스트림에서 탭은 8칸인데 파서는 글자 하나로 담는다. 그 차이를 `stream_pos` 가
        // 메우지 않으면 탭 뒤의 모든 자리가 탭 하나당 7칸씩 앞당겨진다 — 누름틀 좌표가
        // 어긋나는 결함이다(오라클 실측: `InsertTab` 뒤 캐럿 3 → 11).
        let para = Paragraph {
            text: "AB\tCD".into(),
            char_count: 13, // 글자 4 + 탭 8 + 문단끝 1
            ..Default::default()
        };
        assert_eq!(stream_pos(&para, 0), 0);
        assert_eq!(stream_pos(&para, 2), 2, "탭 앞은 그대로다");
        assert_eq!(stream_pos(&para, 3), 10, "탭 하나를 지나면 8칸");
        assert_eq!(stream_pos(&para, 5), 12);
        assert_eq!(stream_len(&para), 12);
        // 되짚기도 같은 자를 써야 한다.
        assert_eq!(char_idx_at_stream_pos(&para, 10), 3);
        assert_eq!(char_idx_at_stream_pos(&para, 12), 5);
    }

    #[test]
    fn remove_field_at_invalidates_raw_stream() {
        // 본문 필드 제거는 섹션 본문을 바꾸므로 raw_stream 이 무효화돼야 저장에 반영된다.
        // 무효화 라인을 제거하면 이 테스트가 실패한다(RED): 저장이 원본 바이트를 재방출해
        // 지운 필드가 되살아난다.
        let mut core = DocumentCore::new_empty();
        core.document.sections.push(Section {
            paragraphs: vec![para_with_click_here_field()],
            raw_stream: Some(vec![0xAB; 64]),
            ..Default::default()
        });
        core.composed = vec![Vec::new()];
        core.dirty_sections = vec![true];
        core.dirty_paragraphs = vec![None];

        core.remove_field_at(0, 0, 4).unwrap();

        assert!(
            core.document.sections[0].raw_stream.is_none(),
            "remove_field_at 후 raw_stream 이 무효화돼야 한다"
        );
        let bytes = crate::serializer::body_text::serialize_section(&core.document.sections[0]);
        assert_ne!(
            bytes,
            vec![0xAB; 64],
            "serialize_section 이 여전히 원본 바이트를 반환"
        );
        // 필드 컨트롤이 실제로 제거돼 ColumnDef 만 남는다
        assert_eq!(core.document.sections[0].paragraphs[0].controls.len(), 1);
    }

    #[test]
    fn remove_field_at_in_cell_invalidates_raw_stream() {
        // 표 셀 내 필드 제거도 섹션 본문 스트림을 바꾸므로 raw_stream 무효화가 필요하다.
        let table = Table {
            cells: vec![Cell {
                paragraphs: vec![para_with_click_here_field()],
                ..Default::default()
            }],
            ..Default::default()
        };
        let parent_para = Paragraph {
            controls: vec![Control::Table(Box::new(table))],
            ..Default::default()
        };
        let mut core = DocumentCore::new_empty();
        core.document.sections.push(Section {
            paragraphs: vec![parent_para],
            raw_stream: Some(vec![0xAB; 64]),
            ..Default::default()
        });
        core.composed = vec![Vec::new()];
        core.dirty_sections = vec![true];
        core.dirty_paragraphs = vec![None];

        core.remove_field_at_in_cell(0, 0, 0, 0, 0, 4, false)
            .unwrap();

        assert!(
            core.document.sections[0].raw_stream.is_none(),
            "remove_field_at_in_cell 후 raw_stream 이 무효화돼야 한다"
        );
        let bytes = crate::serializer::body_text::serialize_section(&core.document.sections[0]);
        assert_ne!(bytes, vec![0xAB; 64]);
    }

    /// 이름이 `name` 인 셀 하나를 담은 표 문단.
    fn para_with_named_cells(names: &[&str]) -> Paragraph {
        let table = Table {
            cells: names
                .iter()
                .map(|name| Cell {
                    field_name: Some((*name).to_string()),
                    paragraphs: vec![Paragraph::default()],
                    ..Default::default()
                })
                .collect(),
            ..Default::default()
        };
        Paragraph {
            controls: vec![Control::Table(Box::new(table))],
            ..Default::default()
        }
    }

    fn core_with(paragraphs: Vec<Paragraph>) -> DocumentCore {
        let mut core = DocumentCore::new_empty();
        core.document.sections.push(Section {
            paragraphs,
            raw_stream: Some(vec![0xAB; 64]),
            ..Default::default()
        });
        core.composed = vec![Vec::new()];
        core.dirty_sections = vec![true];
        core.dirty_paragraphs = vec![None];
        core
    }

    fn field_names(core: &DocumentCore) -> Vec<String> {
        core.collect_all_fields()
            .iter()
            .filter_map(|fi| fi.field.field_name().map(str::to_string))
            .collect()
    }

    /// 셀 하나짜리 표를 담은 문단. 셀 안에 다른 컨트롤을 넣을 수 있다.
    fn para_with_cells(cells: Vec<Cell>) -> Paragraph {
        Paragraph {
            controls: vec![Control::Table(Box::new(Table {
                cells,
                ..Default::default()
            }))],
            ..Default::default()
        }
    }

    fn named_cell(name: &str, paragraphs: Vec<Paragraph>) -> Cell {
        Cell {
            field_name: Some(name.to_string()),
            paragraphs,
            ..Default::default()
        }
    }

    #[test]
    fn list_ids_run_depth_first_from_two() {
        // 한글2022 실측 규칙: 셀에 번호를 준 **뒤** 그 셀 안으로 내려간다. 바깥 셀을 모두
        // 세고 나서 안으로 들어가면 중첩 표에서 번호가 어긋난다(3중 중첩 문서로 확인).
        let inner = para_with_cells(vec![
            named_cell("inner0", vec![Paragraph::default()]),
            named_cell("inner1", vec![Paragraph::default()]),
        ]);
        let outer = para_with_cells(vec![
            named_cell("outer0", vec![Paragraph::default()]),
            named_cell("outer1", vec![inner]),
            named_cell("outer2", vec![Paragraph::default()]),
        ]);
        let core = core_with(vec![outer]);

        let (fields, lists) = core.collect_fields_and_lists();
        let ids: Vec<(String, u32)> = fields
            .iter()
            .map(|fi| (fi.field.field_name().unwrap_or("").to_string(), fi.list_id))
            .collect();

        assert_eq!(
            ids,
            vec![
                ("outer0".to_string(), 2),
                ("outer1".to_string(), 3),
                ("inner0".to_string(), 4),
                ("inner1".to_string(), 5),
                ("outer2".to_string(), 6),
            ],
            "셀 3 다음에 그 안의 표가 오고, 그 뒤에 셀 6 이 이어져야 한다"
        );
        assert_eq!(lists.len(), 5);
        // 안쪽 리스트는 바깥 셀(리스트 3)에 매달린다 — 상위 이동이 이 값을 딛는다.
        assert_eq!(lists[2].host_list_id, 3);
        assert_eq!(lists[0].host_list_id, ROOT_LIST_ID);
    }

    #[test]
    fn cursor_model_top_pos_skips_anchored_controls() {
        // "문서의 시작"은 자리차지 개체를 건너뛴 자리다. 인라인 표를 만나면 그 앞에서 멈춘다.
        let mut anchored = para_with_cells(vec![named_cell("a", vec![Paragraph::default()])]);
        anchored.char_count = 9;
        let mut core = core_with(vec![anchored]);
        let model = core.get_cursor_model_json();
        assert!(
            model.contains("\"topPos\":8"),
            "자리차지 표 하나를 건너뛰어 8이어야 한다: {model}"
        );

        if let Control::Table(t) = &mut core.document.sections[0].paragraphs[0].controls[0] {
            t.common.treat_as_char = true;
        }
        let model = core.get_cursor_model_json();
        assert!(
            model.contains("\"topPos\":0"),
            "인라인 표 앞에서 멈춰 0이어야 한다: {model}"
        );
    }

    #[test]
    fn para_bounds_never_start_past_end() {
        // 자리표 글자를 안 남기는 컨트롤이 있으면 텍스트만 세는 길이가 앞머리 자리차지보다
        // 짧아져 시작 > 끝이라는 있을 수 없는 상태가 된다. 한글은 그런 문단의 시작도 끝도
        // 같은 자리로 답한다.
        let mut anchored = para_with_cells(vec![named_cell("a", vec![Paragraph::default()])]);
        anchored.char_count = 9;
        let core = core_with(vec![anchored]);

        let bounds = core.para_bounds_json(0, 0);

        assert_eq!(
            bounds, r#"{"start":8,"end":8,"selectStart":0}"#,
            "시작이 끝을 넘으면 안 된다: {bounds}"
        );
    }

    #[test]
    fn rename_field_renames_cell_field() {
        // 셀 필드는 누름틀과 저장 경로가 다르다. `updateClickHereProps` 로는 못 바꾼 자리다.
        let mut core = core_with(vec![para_with_named_cells(&["pt_nm"])]);

        let json = core.rename_field_by_name("pt_nm", "환자명").unwrap();

        assert_eq!(json, r#"{"ok":true,"renamed":1}"#);
        assert_eq!(field_names(&core), vec!["환자명".to_string()]);
        assert!(
            core.document.sections[0].raw_stream.is_none(),
            "raw_stream 이 남으면 저장이 옛 이름을 재방출한다"
        );
    }

    #[test]
    fn rename_field_renames_every_occurrence() {
        // 오라클 실측: 같은 이름이 두 번 나오는 문서에서 한 번의 호출로 둘 다 바뀐다.
        let mut core = core_with(vec![
            para_with_named_cells(&["pt_no", "other"]),
            para_with_named_cells(&["pt_no"]),
        ]);

        let json = core.rename_field_by_name("pt_no", "접수번호").unwrap();

        assert_eq!(json, r#"{"ok":true,"renamed":2}"#);
        assert_eq!(
            field_names(&core),
            vec![
                "접수번호".to_string(),
                "other".to_string(),
                "접수번호".to_string()
            ]
        );
    }

    #[test]
    fn rename_field_rewrites_click_here_ctrl_data() {
        // 누름틀 이름은 CTRL_DATA 바이트에도 실려 있다. 모델만 바꾸면 저장에서 되돌아간다.
        let mut para = para_with_click_here_field();
        if let Control::Field(f) = &mut para.controls[1] {
            f.ctrl_data_name = Some("old_name".into());
        }
        let mut core = core_with(vec![para]);

        let json = core.rename_field_by_name("old_name", "새이름").unwrap();

        assert_eq!(json, r#"{"ok":true,"renamed":1}"#);
        assert_eq!(field_names(&core), vec!["새이름".to_string()]);
        let record = core.document.sections[0].paragraphs[0].ctrl_data_records[1]
            .as_ref()
            .expect("CTRL_DATA 레코드가 만들어져야 한다");
        let name_len = u16::from_le_bytes([record[10], record[11]]) as usize;
        let chars: Vec<u16> = record[12..12 + name_len * 2]
            .chunks_exact(2)
            .map(|c| u16::from_le_bytes([c[0], c[1]]))
            .collect();
        assert_eq!(String::from_utf16_lossy(&chars), "새이름");
    }

    #[test]
    fn rename_field_missing_name_changes_nothing() {
        // 없는 이름이면 오라클도 아무 일도 하지 않는다(FieldExist 가 계속 false).
        let mut core = core_with(vec![para_with_named_cells(&["pt_nm"])]);

        let json = core.rename_field_by_name("없는필드", "아무개").unwrap();

        assert_eq!(json, r#"{"ok":false,"renamed":0}"#);
        assert_eq!(field_names(&core), vec!["pt_nm".to_string()]);
        assert!(
            core.document.sections[0].raw_stream.is_some(),
            "바꾼 게 없으면 원본 스트림을 버리지 않는다"
        );
    }

    #[test]
    fn set_cell_field_text_updates_text_metadata() {
        modest_cell_field_fill_reaches_frame_consumers_before_serialization();
        let cell_para = Paragraph {
            text: "기존값".into(),
            char_count: 4,
            char_offsets: vec![0, 1, 2],
            ..Default::default()
        };
        let table = Table {
            cells: vec![Cell {
                field_name: Some("셀필드".into()),
                paragraphs: vec![cell_para],
                ..Default::default()
            }],
            ..Default::default()
        };
        let parent_para = Paragraph {
            controls: vec![Control::Table(Box::new(table))],
            ..Default::default()
        };

        let mut core = DocumentCore::new_empty();
        core.document.sections.push(Section {
            paragraphs: vec![parent_para],
            ..Default::default()
        });

        let location = FieldLocation {
            section_index: 0,
            para_index: 0,
            nested_path: vec![NestedEntry::TableCell {
                control_index: 0,
                cell_index: 0,
                para_index: 0,
            }],
        };

        core.set_cell_field_text(&location, "새값").unwrap();

        let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
            panic!("expected table control");
        };
        let updated = &table.cells[0].paragraphs[0];
        assert_eq!(updated.text, "새값");
        assert_eq!(updated.char_count, 3);
        assert_eq!(updated.char_offsets, vec![0, 1]);
    }

    fn modest_cell_field_fill_reaches_frame_consumers_before_serialization() {
        let initial = "old";
        let cell_para = Paragraph {
            text: initial.into(),
            char_count: 4,
            char_offsets: vec![0, 1, 2],
            line_segs: vec![LineSeg {
                text_start: 0,
                line_height: 1_000,
                text_height: 900,
                baseline_distance: 800,
                segment_width: 1,
                tag: LineSeg::TAG_SINGLE_SEGMENT_LINE,
                ..Default::default()
            }],
            ..Default::default()
        };
        let mut core = DocumentCore::new_empty();
        core.document.sections.push(Section {
            paragraphs: vec![Paragraph {
                controls: vec![Control::Table(Box::new(Table {
                    cells: vec![Cell {
                        field_name: Some("셀필드".into()),
                        paragraphs: vec![cell_para],
                        ..Default::default()
                    }],
                    ..Default::default()
                }))],
                ..Default::default()
            }],
            ..Default::default()
        });
        let location = FieldLocation {
            section_index: 0,
            para_index: 0,
            nested_path: vec![NestedEntry::TableCell {
                control_index: 0,
                cell_index: 0,
                para_index: 0,
            }],
        };

        core.set_cell_field_text(&location, "moderately wider field value")
            .unwrap();

        let styles = crate::renderer::style_resolver::ResolvedStyleSet::default();
        let dpi = 96.0;
        let measured = {
            let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
                panic!("expected table control");
            };
            let para = &table.cells[0].paragraphs[0];
            assert!(para.line_segs.is_empty());
            let composed = crate::renderer::composer::compose_paragraph(para);
            crate::renderer::composer::estimate_composed_line_width(&composed.lines[0], &styles)
        };
        let width_hwp = crate::renderer::px_to_hwpunit(measured / 1.2, dpi);
        let inner_width = crate::renderer::hwpunit_to_px(width_hwp, dpi);
        assert!(measured > inner_width && measured < inner_width * 1.8);

        let Control::Table(table) = &core.document.sections[0].paragraphs[0].controls[0] else {
            panic!("expected table control");
        };
        let para = &table.cells[0].paragraphs[0];
        let mut composed = crate::renderer::composer::compose_paragraph(para);
        crate::renderer::composer::recompose_cell_lines_in_frame(
            &mut composed,
            para,
            crate::renderer::composer::ParagraphBox::content(0..width_hwp),
            &styles,
            dpi,
            false,
        );

        assert!(
            composed.lines.len() > 1,
            "the shared cell consumer must see a fresh boundary before save/reload"
        );
        assert!(composed.lines[1].char_start > 0);
    }
}