rhwp 0.9.0

HWP/HWPX document engine for Rust applications, WebAssembly, and CLI automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
//! `<hp:tbl>` 표 직렬화.
//!
//! Stage 3 (#182): `Control::Table` IR → `<hp:tbl>` + `<hp:tr>` + `<hp:tc>` + `<hp:subList>` + 문단 재귀.
//!
//! 속성·자식 순서는 한컴 OWPML 공식 (hancom-io/hwpx-owpml-model, Apache 2.0)
//! `Class/Para/TableType.cpp` 의 `WriteElement()`, `InitMap()` 기준:
//!
//! ### `<hp:tbl>` 속성 순서 (부모 AbstractShapeObjectType + 자신)
//! id, zOrder, numberingType, textWrap, textFlow, lock, dropcapstyle,
//! pageBreak, repeatHeader, rowCnt, colCnt, cellSpacing, borderFillIDRef, noAdjust
//!
//! ### `<hp:tbl>` 자식 순서
//! sz, pos, outMargin, (caption, shapeComment, parameterset, metaTag — 옵셔널),
//! inMargin, (cellzoneList — 옵셔널), tr (루프), (label — 옵셔널)
//!
//! ### `<hp:tc>` 속성 순서
//! name, header, hasMargin, protect, editable, dirty, borderFillIDRef
//!
//! ### `<hp:tc>` 자식 순서
//! subList, cellAddr, cellSpan, cellSz, cellMargin
//!
//! ## 중요: table.attr 비트 연산 금지
//!
//! HWPX에서 `table.attr` 는 0인 경우가 많으므로 비트 연산으로 `textWrap/textFlow/pageBreak` 등을
//! 추출하면 안 된다. 반드시 `table.common.text_wrap`, `table.page_break` 등 파싱된 IR 필드를 사용.

use super::section::{
    build_secpr_run_with_storage, render_hp_p_open_with_storage,
    render_paragraph_parts_with_storage,
};
use super::shape::color_to_hex_with_storage;
use super::utils::{
    empty_tag_with_storage, end_tag_with_storage, start_tag_attrs_with_storage,
    start_tag_with_storage, text_with_storage, write_xml_decl_with_storage, xml_error,
    xml_escape_with_storage, xml_value,
};
use std::io::Write;

use quick_xml::Writer;

use crate::model::shape::{
    CommonObjAttr, HorzAlign, HorzRelTo, SizeCriterion, TextFlow, TextWrap, VertAlign, VertRelTo,
};
use crate::model::table::{Cell, Table, TablePageBreak, VerticalAlign};

use super::context::SerializeContext;
use super::section::{
    build_secpr_run, first_run_char_shape_id, render_hp_p_open, render_paragraph_parts,
};
use super::shape::numbering_type_str;
use super::utils::{empty_tag, end_tag, start_tag, start_tag_attrs};
use super::SerializeError;

/// `<hp:tbl>` 직렬화.
pub fn write_table<W: Write>(
    w: &mut Writer<W>,
    table: &Table,
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_table_with_storage(w, table, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_table_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    table: &Table,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    // Keep the editable IR grid; HWPX rows must each contain a cell origin.
    let projected = ctx
        .table_row_grids
        .table_with_reserved_ids_and_storage(table, &ctx.table_instance_ids.registered, storage)
        .map_err(SerializeError::UnsupportedInput)?;
    let table = projected.as_ref();
    // borderFillIDRef 참조 등록 (assert_all_refs_resolved 검증 대상)
    ctx.border_fill_ids.reference(table.border_fill_id);
    for zone in &table.zones {
        ctx.border_fill_ids.reference(zone.border_fill_id);
    }
    for cell in &table.cells {
        ctx.border_fill_ids.reference(cell.border_fill_id);
    }

    // --- <hp:tbl> 시작 태그 + 속성 ---
    let id_str = xml_value(storage, table.common.instance_id)?;
    let z_order = xml_value(storage, table.common.z_order)?;
    let text_wrap = text_wrap_str(table.common.text_wrap);
    let text_flow = text_flow_str(table.common.text_flow);
    // [#2840] lock(개체 잠금) — IR 보존 값 방출 (종전 false 하드코딩).
    let lock = bool01(table.common.locked);
    let page_break = table_page_break_str(table.page_break);
    let repeat_header = bool01(table.repeat_header);
    let row_cnt = xml_value(storage, table.row_count)?;
    let col_cnt = xml_value(storage, table.col_count)?;
    let cell_spacing = xml_value(storage, table.cell_spacing)?;
    let border_fill_id_ref = xml_value(storage, table.border_fill_id)?;
    let no_adjust = bool01((table.attr | table.raw_table_record_attr) & 0x08 != 0);

    start_tag_attrs_with_storage(
        w,
        "hp:tbl",
        &[
            ("id", &id_str),
            ("zOrder", &z_order),
            // [#2697] numberingType 은 IR(common.numbering_type)을 보존한다. 종전 "TABLE"
            // 하드코딩은 표에 그림 번호 캡션을 붙인 문서(numberingType="PICTURE")에서
            // 저장 시 번호 범주를 되돌려 문서 전체 캡션 번호를 재배치시켰다. 도형 계열은
            // 이미 #1379 에서 IR 보존으로 정리됐다(shape.rs:70,172,291,367).
            (
                "numberingType",
                numbering_type_str(table.common.numbering_type),
            ),
            ("textWrap", text_wrap),
            ("textFlow", text_flow),
            ("lock", lock),
            (
                "dropcapstyle",
                super::shape::drop_cap_style_str(table.common.drop_cap_style),
            ),
            ("pageBreak", page_break),
            ("repeatHeader", repeat_header),
            ("rowCnt", &row_cnt),
            ("colCnt", &col_cnt),
            ("cellSpacing", &cell_spacing),
            ("borderFillIDRef", &border_fill_id_ref),
            ("noAdjust", no_adjust),
        ],
        storage,
    )?;

    // --- 자식: sz, pos, outMargin, (caption — 옵셔널), inMargin, tr[] ---
    write_sz_with_storage(w, &table.common, storage)?;
    write_pos_with_storage(w, &table.common, storage)?;
    write_out_margin_with_storage(w, table, storage)?;
    if let Some(caption) = &table.caption {
        write_caption_with_storage(w, caption, ctx, storage)?;
    }
    write_in_margin_with_storage(w, table, storage)?;
    // cellzoneList: inMargin 다음, tr 앞 (OWPML 자식 순서). 셀 영역 테두리/배경
    // 오버레이를 정의한다. 파서가 table.zones 로 보존하므로 그대로 되살린다.
    write_cellzone_list_with_storage(w, table, storage)?;

    // tr[]: 행 단위 반복. 각 행에 속한 셀 (cell.row == r) 을 col 오름차순으로 출력.
    for row_idx in 0..table.row_count {
        start_tag_with_storage(w, "hp:tr", storage)?;
        let mut row_cells: Vec<&Cell> = storage
            .collect(table.cells.iter().filter(|c| c.row == row_idx))
            .map_err(xml_error)?;
        storage
            .bytes(std::mem::size_of_val(row_cells.as_slice()))
            .map_err(xml_error)?;
        row_cells.sort_by_key(|c| c.col);
        for cell in row_cells {
            write_cell_with_storage(w, cell, ctx, storage)?;
        }
        end_tag_with_storage(w, "hp:tr", storage)?;
    }

    end_tag_with_storage(w, "hp:tbl", storage)?;
    Ok(())
}

fn write_sz<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
    write_sz_with_storage(w, c, &crate::storage::Unbounded)
}

pub(super) fn write_sz_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    c: &CommonObjAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let width = xml_value(storage, c.width)?;
    let height = xml_value(storage, c.height)?;
    // [#2697] widthRelTo/heightRelTo/protect 는 IR 을 보존한다. 종전 "ABSOLUTE"/"0"
    // 하드코딩은 파서가 이미 읽어 둔 값(section.rs:1689/1693)을 저장 때 버려, 단/쪽/문단에
    // 맞춘 표가 절대값으로 바뀌고 크기 보호가 풀렸다. 이웃 write_pos 는 이미 모든 필드를
    // enum 헬퍼로 통과시킨다. 같은 hp:sz 를 다루는 form.rs:178-188 도 3속성 모두 보존한다.
    empty_tag_with_storage(
        w,
        "hp:sz",
        &[
            ("width", &width),
            ("widthRelTo", size_criterion_str(c.width_criterion)),
            ("height", &height),
            ("heightRelTo", height_criterion_str(c.height_criterion)),
            ("protect", bool01(c.size_protect)),
        ],
        storage,
    )
}

/// 너비 기준 → HWPX `widthRelTo`. 파서 `parse_size_criterion(_, true)` 의 정확한 역.
fn size_criterion_str(c: SizeCriterion) -> &'static str {
    match c {
        SizeCriterion::Paper => "PAPER",
        SizeCriterion::Page => "PAGE",
        SizeCriterion::Column => "COLUMN",
        SizeCriterion::Para => "PARA",
        SizeCriterion::Absolute => "ABSOLUTE",
    }
}

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

fn write_pos<W: Write>(w: &mut Writer<W>, c: &CommonObjAttr) -> Result<(), SerializeError> {
    write_pos_with_storage(w, c, &crate::storage::Unbounded)
}

pub(super) fn write_pos_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    c: &CommonObjAttr,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let treat = bool01(c.treat_as_char);
    let vert_offset = xml_value(storage, c.vertical_offset)?;
    let horz_offset = xml_value(storage, c.horizontal_offset)?;
    // [#1594] holdAnchorAndSO 는 IR(prevent_page_break)을 보존한다. 종전 "0" 하드코딩은
    // 페이지 하단 앵커 개체(발신명의 footer 등)의 1→0 드롭으로 한글 페이지 붕괴를 유발했다.
    let hold = bool01(c.prevent_page_break != 0);
    empty_tag_with_storage(
        w,
        "hp:pos",
        &[
            ("treatAsChar", treat),
            // [#2784] affectLSpacing 은 IR(affect_line_spacing)을 보존한다. 종전 "0"
            // 하드코딩은 "줄 간격에 영향" 켜진 표가 저장 시 1→0 으로 드롭됐다.
            ("affectLSpacing", bool01(c.affect_line_spacing)),
            // [#1637] flowWithText 는 IR(flow_with_text)을 보존한다. 종전 "1" 하드코딩은
            // treatAsChar 표의 1→0 케이스에서 0→1 드롭으로 표 partial-split 임계를 흔들어
            // 페이지네이션이 달라졌다(IR-invisible). #1594 holdAnchorAndSO 와 동형.
            ("flowWithText", bool01(c.flow_with_text)),
            // allowOverlap 는 IR(allow_overlap)을 보존한다. 이웃 flowWithText(#1637)·
            // holdAnchorAndSO(#1594)는 이미 IR 보존으로 고쳐졌는데 그 사이 allowOverlap 만
            // "0" 하드코딩으로 남아, "개체 겹침 허용"이 켜진 플로팅 표가 저장 시 1→0 으로
            // 드롭됐다(IR-invisible). shape.rs·picture.rs 의 write_pos 와 동형으로 방출.
            ("allowOverlap", bool01(c.allow_overlap)),
            ("holdAnchorAndSO", hold),
            ("vertRelTo", vert_rel_to_str(c.vert_rel_to)),
            ("horzRelTo", horz_rel_to_str(c.horz_rel_to)),
            ("vertAlign", vert_align_str(c.vert_align)),
            ("horzAlign", horz_align_str(c.horz_align)),
            ("vertOffset", &vert_offset),
            ("horzOffset", &horz_offset),
        ],
        storage,
    )
}

fn write_out_margin<W: Write>(w: &mut Writer<W>, t: &Table) -> Result<(), SerializeError> {
    write_out_margin_with_storage(w, t, &crate::storage::Unbounded)
}

pub(super) fn write_out_margin_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    t: &Table,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let left = xml_value(storage, t.outer_margin_left)?;
    let right = xml_value(storage, t.outer_margin_right)?;
    let top = xml_value(storage, t.outer_margin_top)?;
    let bottom = xml_value(storage, t.outer_margin_bottom)?;
    empty_tag_with_storage(
        w,
        "hp:outMargin",
        &[
            ("left", &left),
            ("right", &right),
            ("top", &top),
            ("bottom", &bottom),
        ],
        storage,
    )
}

fn write_in_margin<W: Write>(w: &mut Writer<W>, t: &Table) -> Result<(), SerializeError> {
    write_in_margin_with_storage(w, t, &crate::storage::Unbounded)
}

pub(super) fn write_in_margin_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    t: &Table,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let left = xml_value(storage, t.padding.left)?;
    let right = xml_value(storage, t.padding.right)?;
    let top = xml_value(storage, t.padding.top)?;
    let bottom = xml_value(storage, t.padding.bottom)?;
    empty_tag_with_storage(
        w,
        "hp:inMargin",
        &[
            ("left", &left),
            ("right", &right),
            ("top", &top),
            ("bottom", &bottom),
        ],
        storage,
    )
}

/// `<hp:cellzoneList>` + `<hp:cellzone>` 자식들. 셀 영역(범위) 단위 테두리/배경
/// 오버레이. `table.zones` 가 비어 있으면 원본에 없었던 것이므로 미방출.
/// 속성 순서는 OWPML 관찰 순서: startRowAddr, startColAddr, endRowAddr,
/// endColAddr, borderFillIDRef. borderFillIDRef 는 셀과 동일하게 raw 값(오프셋
/// 없음)으로 쓴다 (parser `parse_u16`, 헤더 borderFill id 와 1:1).
fn write_cellzone_list<W: Write>(w: &mut Writer<W>, t: &Table) -> Result<(), SerializeError> {
    write_cellzone_list_with_storage(w, t, &crate::storage::Unbounded)
}

pub(super) fn write_cellzone_list_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    t: &Table,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    if t.zones.is_empty() {
        return Ok(());
    }
    start_tag_with_storage(w, "hp:cellzoneList", storage)?;
    for zone in &t.zones {
        let start_row = xml_value(storage, zone.start_row)?;
        let start_col = xml_value(storage, zone.start_col)?;
        let end_row = xml_value(storage, zone.end_row)?;
        let end_col = xml_value(storage, zone.end_col)?;
        let border_fill = xml_value(storage, zone.border_fill_id)?;
        empty_tag_with_storage(
            w,
            "hp:cellzone",
            &[
                ("startRowAddr", &start_row),
                ("startColAddr", &start_col),
                ("endRowAddr", &end_row),
                ("endColAddr", &end_col),
                ("borderFillIDRef", &border_fill),
            ],
            storage,
        )?;
    }
    end_tag_with_storage(w, "hp:cellzoneList", storage)
}

fn write_cell<W: Write>(
    w: &mut Writer<W>,
    cell: &Cell,
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_cell_with_storage(w, cell, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_cell_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let name = cell.field_name.as_deref().unwrap_or("");
    let header = bool01(cell.is_header);
    let has_margin = bool01(cell.apply_inner_margin);
    let protect = bool01(cell.cell_protect());
    let editable = bool01(cell.editable_in_form());
    let dirty = bool01(cell.dirty_flag);
    let border_ref = xml_value(storage, cell.border_fill_id)?;

    start_tag_attrs_with_storage(
        w,
        "hp:tc",
        &[
            ("name", name),
            ("header", header),
            ("hasMargin", has_margin),
            ("protect", protect),
            ("editable", editable),
            ("dirty", dirty),
            ("borderFillIDRef", &border_ref),
        ],
        storage,
    )?;

    // 자식 순서: subList, cellAddr, cellSpan, cellSz, cellMargin
    write_sub_list_with_storage(w, cell, ctx, storage)?;
    write_cell_addr_with_storage(w, cell, storage)?;
    write_cell_span_with_storage(w, cell, storage)?;
    write_cell_sz_with_storage(w, cell, storage)?;
    write_cell_margin_with_storage(w, cell, storage)?;

    end_tag_with_storage(w, "hp:tc", storage)?;
    Ok(())
}

fn write_sub_list<W: Write>(
    w: &mut Writer<W>,
    cell: &Cell,
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_sub_list_with_storage(w, cell, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_sub_list_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    start_tag_attrs_with_storage(
        w,
        "hp:subList",
        &[
            ("id", ""),
            (
                "textDirection",
                // [#8334] HWP5 셀 방향 값 2 는 세로 영문 세움(`VERTICALALL`)이다.
                match cell.text_direction {
                    1 => "VERTICAL",
                    2 => "VERTICALALL",
                    _ => "HORIZONTAL",
                },
            ),
            // [#4898] 종전엔 상수 "BREAK" 였다 — 원본이 SQUEEZE 인 셀도 BREAK 로 굳어
            // x2x 왕복에서 조용히 소실됐다(코퍼스 표본 3,019회). IR 값을 그대로 되돌린다.
            ("lineWrap", cell_line_wrap_str(cell.line_wrap)),
            ("vertAlign", cell_vert_align_str(cell.vertical_align)),
            ("linkListIDRef", "0"),
            ("linkListNextIDRef", "0"),
            ("textWidth", "0"),
            ("textHeight", "0"),
            ("hasTextRef", "0"),
            ("hasNumRef", "0"),
        ],
        storage,
    )?;

    write_sub_list_paragraphs_with_storage(w, &cell.paragraphs, ctx, storage)?;

    end_tag_with_storage(w, "hp:subList", storage)?;
    Ok(())
}

/// subList 내부 문단 시퀀스 방출 — 셀(#1379)과 표 캡션(#1387)이 공유.
///
/// 본문과 동일한 공유 직렬화 경로(render_paragraph_parts)로 컨트롤 슬롯(표 재귀
/// 포함) 방출 + run 분할 + lineseg IR 보존/fallback (#1379 2단계).
/// sub_list_depth: subList 경로 한정 colPr 인라인 방출 스코프 (#1379 3단계).
///
/// [#5873] 셀 안 문단이 구역 나누기(`SectionDef`)를 들고 있으면 `hp:secPr` 도 낸다.
/// `render_runs` 는 `SectionDef` 슬롯을 hidden 처리해 XML 을 내지 않고, 본문 최상위
/// 문단만 #4056 이 `write_section` 루프에서 보완해 왔다. subList 에는 그 보완이 없어
/// 셀 안 구역이 통째로 사라졌다 — 뒤따르는 `hp:colPr` 만 남는다.
///
/// 코퍼스 HWP5 6,491문서 전수(레코드 단위): BodyText 스트림 수보다 `secd` 가 많은 문서
/// 3건이고 그 **17개 전부 표 셀 안(level 3)** 이다. 그중 06874 는 `secd` 15개를 잃어
/// 한글이 `부록 4-④` 문단부터 문서 끝까지 폐기했다(204→159쪽, −57,525자).
/// 한글 2022 오라클 주입 검정: 그 자리 **한 곳에만** `secPr` 를 되살리면 쪽수·글자수가
/// 원본과 정확히 같아지고 컨트롤 인구조사(`atno:6`·`fn:6`·`tbl:113`·`gso:41`)도 일치한다.
fn write_sub_list_paragraphs<W: Write>(
    w: &mut Writer<W>,
    paragraphs: &[crate::model::paragraph::Paragraph],
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_sub_list_paragraphs_with_storage(w, paragraphs, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_sub_list_paragraphs_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    paragraphs: &[crate::model::paragraph::Paragraph],
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let depth = ctx.sub_list_depth;
    let result = (|| -> Result<(), SerializeError> {
        ctx.sub_list_depth += 1;
        let mut vert_cursor: u32 = 0;
        for para in paragraphs {
            ctx.para_shape_ids.reference(para.para_shape_id);
            let sid = ctx.effective_style_id(para.style_id);
            ctx.style_ids.reference(sid as u16);

            let (runs, linesegs, advance) =
                render_paragraph_parts_with_storage(para, vert_cursor, ctx, storage)?;
            vert_cursor = advance;
            let pid = ctx.next_para_id();
            let mut p_xml = render_hp_p_open_with_storage(para, pid, sid, storage)?;
            // [#5873] 셀 안 구역 나누기 — #4056 의 본문 경로와 같은 보완.
            if let Some(crate::model::control::Control::SectionDef(sd)) = para
                .controls
                .iter()
                .find(|c| matches!(c, crate::model::control::Control::SectionDef(_)))
            {
                storage
                    .push_str(
                        &mut p_xml,
                        &build_secpr_run_with_storage(sd, first_run_char_shape_id(para), storage)?,
                    )
                    .map_err(xml_error)?;
            }
            storage.push_str(&mut p_xml, &runs).map_err(xml_error)?;
            storage.push_str(&mut p_xml, &linesegs).map_err(xml_error)?;
            storage.push_str(&mut p_xml, "</hp:p>").map_err(xml_error)?;
            w.get_mut()
                .write_all(p_xml.as_bytes())
                .map_err(|e| SerializeError::XmlError(e.to_string()))?;
        }
        ctx.sub_list_depth -= 1;
        Ok(())
    })();
    ctx.sub_list_depth = depth;
    result
}

/// `<hp:caption>` 직렬화 (#1387) — 자식 순서상 outMargin 과 inMargin 사이 (모듈 doc).
///
/// 속성 순서는 한컴 실물(ta-pic-001-r) 기준: side, fullSz, width, gap, lastWidth.
/// 캡션 subList 의 lineWrap/textDirection 은 파서가 적재하지 않으며 samples/hwpx 전수
/// 17건 동일(lineWrap=BREAK textDirection=HORIZONTAL — 1단계 측정) — 실물 고정값 방출.
/// vertAlign 은 IR(`caption.vert_align`, table_ops.rs 편집 경로 존재)을 실제로 반영한다(#3035).
/// 그림/도형/묶음 캡션(#1403)도 동일 경로를 공유한다 (pub(super)).
pub(super) fn write_caption<W: Write>(
    w: &mut Writer<W>,
    caption: &crate::model::shape::Caption,
    ctx: &mut SerializeContext,
) -> Result<(), SerializeError> {
    write_caption_with_storage(w, caption, ctx, &crate::storage::Unbounded)
}

pub(super) fn write_caption_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    caption: &crate::model::shape::Caption,
    ctx: &mut SerializeContext,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    use crate::model::shape::{CaptionDirection, CaptionVertAlign};

    let side = match caption.direction {
        CaptionDirection::Left => "LEFT",
        CaptionDirection::Right => "RIGHT",
        CaptionDirection::Top => "TOP",
        CaptionDirection::Bottom => "BOTTOM",
    };
    let vert_align = match caption.vert_align {
        CaptionVertAlign::Top => "TOP",
        CaptionVertAlign::Center => "CENTER",
        CaptionVertAlign::Bottom => "BOTTOM",
    };
    let full_sz = bool01(caption.include_margin);
    let width = xml_value(storage, caption.width)?;
    let gap = xml_value(storage, caption.spacing)?;
    let last_width = xml_value(storage, caption.max_width)?;
    start_tag_attrs_with_storage(
        w,
        "hp:caption",
        &[
            ("side", side),
            ("fullSz", full_sz),
            ("width", &width),
            ("gap", &gap),
            ("lastWidth", &last_width),
        ],
        storage,
    )?;
    start_tag_attrs_with_storage(
        w,
        "hp:subList",
        &[
            ("id", ""),
            ("textDirection", "HORIZONTAL"),
            ("lineWrap", "BREAK"),
            ("vertAlign", vert_align),
            ("linkListIDRef", "0"),
            ("linkListNextIDRef", "0"),
            ("textWidth", "0"),
            ("textHeight", "0"),
            ("hasTextRef", "0"),
            ("hasNumRef", "0"),
        ],
        storage,
    )?;
    write_sub_list_paragraphs_with_storage(w, &caption.paragraphs, ctx, storage)?;
    end_tag_with_storage(w, "hp:subList", storage)?;
    end_tag_with_storage(w, "hp:caption", storage)?;
    Ok(())
}

fn write_cell_addr<W: Write>(w: &mut Writer<W>, cell: &Cell) -> Result<(), SerializeError> {
    write_cell_addr_with_storage(w, cell, &crate::storage::Unbounded)
}

pub(super) fn write_cell_addr_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let col = xml_value(storage, cell.col)?;
    let row = xml_value(storage, cell.row)?;
    empty_tag_with_storage(
        w,
        "hp:cellAddr",
        &[("colAddr", &col), ("rowAddr", &row)],
        storage,
    )
}

fn write_cell_span<W: Write>(w: &mut Writer<W>, cell: &Cell) -> Result<(), SerializeError> {
    write_cell_span_with_storage(w, cell, &crate::storage::Unbounded)
}

pub(super) fn write_cell_span_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let cs = xml_value(storage, cell.col_span.max(1))?;
    let rs = xml_value(storage, cell.row_span.max(1))?;
    empty_tag_with_storage(
        w,
        "hp:cellSpan",
        &[("colSpan", &cs), ("rowSpan", &rs)],
        storage,
    )
}

fn write_cell_sz<W: Write>(w: &mut Writer<W>, cell: &Cell) -> Result<(), SerializeError> {
    write_cell_sz_with_storage(w, cell, &crate::storage::Unbounded)
}

pub(super) fn write_cell_sz_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let w_s = xml_value(storage, cell.width)?;
    let h_s = xml_value(storage, cell.height)?;
    empty_tag_with_storage(
        w,
        "hp:cellSz",
        &[("width", &w_s), ("height", &h_s)],
        storage,
    )
}

fn write_cell_margin<W: Write>(w: &mut Writer<W>, cell: &Cell) -> Result<(), SerializeError> {
    write_cell_margin_with_storage(w, cell, &crate::storage::Unbounded)
}

pub(super) fn write_cell_margin_with_storage<W: Write, S: crate::storage::Storage>(
    w: &mut Writer<W>,
    cell: &Cell,
    storage: &S,
) -> Result<(), SerializeError>
where
    S::Error: std::fmt::Display,
{
    let l = xml_value(storage, cell.padding.left)?;
    let r = xml_value(storage, cell.padding.right)?;
    let t = xml_value(storage, cell.padding.top)?;
    let b = xml_value(storage, cell.padding.bottom)?;
    empty_tag_with_storage(
        w,
        "hp:cellMargin",
        &[("left", &l), ("right", &r), ("top", &t), ("bottom", &b)],
        storage,
    )
}

// ---------- enum 변환 헬퍼 ----------

fn bool01(b: bool) -> &'static str {
    if b {
        "1"
    } else {
        "0"
    }
}

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

fn text_flow_str(f: TextFlow) -> &'static str {
    match f {
        TextFlow::BothSides => "BOTH_SIDES",
        TextFlow::LeftOnly => "LEFT_ONLY",
        TextFlow::RightOnly => "RIGHT_ONLY",
        TextFlow::LargestOnly => "LARGEST_ONLY",
    }
}

fn table_page_break_str(pb: TablePageBreak) -> &'static str {
    use TablePageBreak::*;
    // HWPX 문자열 매핑은 파서(parser/hwpx/section.rs `pageBreak`)의 정확한 역이어야
    // HWPX→HWPX 왕복이 충실하다. 파서는 한컴 관찰 기준으로
    // `"TABLE"→CellBreak`, `"CELL"/"ROW"→RowBreak` 로 매핑하므로 (한컴 HWPX
    // "CELL" = HWP5 row-break bit 1 = RowBreak), 직렬화도 그 역으로 방출한다.
    // (이전 구현은 CellBreak→"CELL", RowBreak→"TABLE" 로 파서와 불일치해 왕복 시
    //  CELL↔TABLE 이 뒤바뀌었다.) enum→HWP5 bit 매핑(hwpx_to_hwp.rs)은 enum 을
    // 직접 쓰므로 이 변경의 영향을 받지 않는다.
    match pb {
        None => "NONE",
        CellBreak => "TABLE",
        RowBreak => "CELL",
    }
}

fn vert_rel_to_str(v: VertRelTo) -> &'static str {
    use VertRelTo::*;
    match v {
        Paper => "PAPER",
        Page => "PAGE",
        Para => "PARA",
    }
}

fn horz_rel_to_str(h: HorzRelTo) -> &'static str {
    use HorzRelTo::*;
    match h {
        Paper => "PAPER",
        Page => "PAGE",
        Column => "COLUMN",
        Para => "PARA",
    }
}

fn vert_align_str(v: VertAlign) -> &'static str {
    use VertAlign::*;
    match v {
        Top => "TOP",
        Center => "CENTER",
        Bottom => "BOTTOM",
        Inside => "INSIDE",
        Outside => "OUTSIDE",
    }
}

fn horz_align_str(h: HorzAlign) -> &'static str {
    use HorzAlign::*;
    match h {
        Left => "LEFT",
        Center => "CENTER",
        Right => "RIGHT",
        Inside => "INSIDE",
        Outside => "OUTSIDE",
    }
}

fn cell_vert_align_str(v: VerticalAlign) -> &'static str {
    use VerticalAlign::*;
    match v {
        Top => "TOP",
        Center => "CENTER",
        Bottom => "BOTTOM",
    }
}

/// [#4898] 셀 줄바꿈 방식(LIST_HEADER bit 19~20) → OWPML `lineWrap`.
///
/// 한글 2022 실측으로 확정한 대응이다 — SQUEEZE 만 쓰는 문서를 한글이 HWP5 로 저장하면
/// LIST_HEADER 가 전부 bit19=1, BREAK 위주 문서는 SQUEEZE 인 셀 하나만 1 이었다.
/// `KEEP`(=2)은 스키마 열거 순서를 따른다(코퍼스 표본에는 나타나지 않았다).
fn cell_line_wrap_str(line_wrap: u8) -> &'static str {
    match line_wrap {
        1 => "SQUEEZE",
        2 => "KEEP",
        _ => "BREAK",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::document::Document;
    use crate::model::paragraph::Paragraph;
    use crate::model::table::{Cell, Table};
    use crate::serializer::hwpx::context::SerializeContext;

    fn empty_table(rows: u16, cols: u16) -> Table {
        let mut t = Table::default();
        t.row_count = rows;
        t.col_count = cols;
        for r in 0..rows {
            for c in 0..cols {
                let mut cell = Cell::default();
                cell.col = c;
                cell.row = r;
                cell.col_span = 1;
                cell.row_span = 1;
                cell.width = 1000;
                cell.height = 300;
                cell.paragraphs.push(Paragraph::default());
                t.cells.push(cell);
            }
        }
        t.rebuild_grid();
        t
    }

    /// [#4898] 셀 줄바꿈 방식(`lineWrap`)이 HWPX 왕복에서 보존돼야 한다.
    ///
    /// 종전엔 파서가 이 속성을 읽지 않고 직렬화기가 상수 `"BREAK"` 를 방출해, 원본이
    /// `SQUEEZE`(자간 조절로 한 줄 유지)인 셀이 조용히 `BREAK` 로 굳었다 — 한글은 그 셀의
    /// 줄을 다시 나누므로 셀·표 높이가 달라진다. 코퍼스 표본(hwpx 648건)에 SQUEEZE 가
    /// 3,019회 나온다. HWP5 축 대응(LIST_HEADER bit 19~20)은 한글 2022 SaveAs 실측이다.
    #[test]
    fn cell_line_wrap_survives_hwpx_roundtrip() {
        use crate::model::control::Control;

        let bytes0 = std::fs::read("samples/hwpx/basic-table-01.hwpx").expect("샘플 읽기");
        let mut doc = crate::parser::hwpx::parse_hwpx(&bytes0).expect("샘플 파싱");
        for section in &mut doc.sections {
            for para in &mut section.paragraphs {
                for control in &mut para.controls {
                    if let Control::Table(table) = control {
                        table.cells[0].line_wrap = 1; // SQUEEZE
                    }
                }
            }
        }

        let bytes = crate::serializer::hwpx::serialize_hwpx(&doc).expect("직렬화");
        let xml = String::from_utf8_lossy(&bytes).to_string();
        let _ = xml; // zip 바이트라 XML 직접 검사 대신 재파싱으로 확인한다
        let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("재파싱");
        let wrapped = doc2
            .sections
            .iter()
            .flat_map(|s| &s.paragraphs)
            .flat_map(|p| &p.controls)
            .filter_map(|c| match c {
                Control::Table(t) => Some(t),
                _ => None,
            })
            .any(|t| t.cells.first().is_some_and(|c| c.line_wrap == 1));
        assert!(wrapped, "SQUEEZE 셀이 왕복에서 BREAK 로 굳으면 안 된다");
    }

    /// [#4898] 매핑은 한글 2022 실측이다 — SQUEEZE 만 쓰는 문서를 SaveAs 하면 LIST_HEADER
    /// 19개가 전부 bit19=1, BREAK 위주 문서는 SQUEEZE 셀 하나만 1 이었다.
    #[test]
    fn cell_line_wrap_str_matches_owpml_enum() {
        assert_eq!(cell_line_wrap_str(0), "BREAK");
        assert_eq!(cell_line_wrap_str(1), "SQUEEZE");
        assert_eq!(cell_line_wrap_str(2), "KEEP");
        assert_eq!(
            cell_line_wrap_str(9),
            "BREAK",
            "미지 값은 기본값으로 관용 처리"
        );
    }

    #[test]
    fn cell_text_direction_survives_hwpx_roundtrip() {
        use crate::model::control::Control;
        // 세로쓰기 셀(text_direction=1)이 HWPX 왕복에서 보존돼야 한다. serializer 는
        // 셀 <hp:subList> 에 textDirection 을 방출하지만, 종전엔 파서가 subList 에서
        // vertAlign 만 읽어 세로쓰기가 유실됐다. (유효한 DocInfo 를 위해 표 샘플 사용.)
        let find_first_table = |doc: &Document| -> usize {
            doc.sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .flat_map(|p| &p.controls)
                .filter(|c| matches!(c, Control::Table(_)))
                .count()
        };

        let bytes0 = std::fs::read("samples/hwpx/basic-table-01.hwpx").expect("샘플 읽기");
        let mut doc = crate::parser::hwpx::parse_hwpx(&bytes0).expect("샘플 파싱");
        assert!(find_first_table(&doc) >= 1, "샘플에 표가 있어야 함");

        // 첫 표의 첫 셀을 세로쓰기로 설정
        for section in &mut doc.sections {
            for para in &mut section.paragraphs {
                for control in &mut para.controls {
                    if let Control::Table(table) = control {
                        table.cells[0].text_direction = 1;
                    }
                }
            }
        }

        let bytes = crate::serializer::hwpx::serialize_hwpx(&doc).expect("직렬화");
        let doc2 = crate::parser::hwpx::parse_hwpx(&bytes).expect("재파싱");
        let table2 = doc2
            .sections
            .iter()
            .flat_map(|s| &s.paragraphs)
            .flat_map(|p| &p.controls)
            .find_map(|c| match c {
                Control::Table(t) => Some(t),
                _ => None,
            })
            .expect("표");
        assert_eq!(
            table2.cells[0].text_direction, 1,
            "세로쓰기 셀 방향(textDirection)이 HWPX 왕복에서 보존돼야 함"
        );
    }

    fn serialize(table: &Table) -> String {
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, table, &mut ctx).expect("write_table");
        String::from_utf8(w.into_inner()).unwrap()
    }

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

    // ---------- #1594: holdAnchorAndSO 보존 ----------

    #[test]
    fn task1594_hold_anchor_preserved() {
        // [#1594] holdAnchorAndSO 는 IR(common.prevent_page_break)을 보존해야 한다.
        // 현재 직렬화가 "0" 하드코딩 → 1→0 드롭(페이지 하단 앵커 개체에서 페이지 붕괴 원인). RED.
        let mut t = empty_table(1, 1);
        t.common.prevent_page_break = 1;
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"holdAnchorAndSO="1""#),
            "holdAnchorAndSO 가 IR 값(1)으로 방출돼야 한다(현재 0 하드코딩): {}",
            &xml[..xml.len().min(500)]
        );
    }

    #[test]
    fn task1594_hold_anchor_zero_when_unset() {
        // prevent_page_break=0 이면 holdAnchorAndSO="0" (기존 동작 보존).
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"holdAnchorAndSO="0""#),
            "기본 0: {}",
            &xml[..xml.len().min(300)]
        );
    }

    // ---------- allowOverlap 보존 ----------

    #[test]
    fn allow_overlap_preserved() {
        // allowOverlap 는 IR(common.allow_overlap)을 보존해야 한다. 종전 "0" 하드코딩은
        // 개체 겹침 허용이 켜진 플로팅 표에서 1→0 드롭으로 저장 시 설정을 유실시켰다. RED.
        let mut t = empty_table(1, 1);
        t.common.allow_overlap = true;
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"allowOverlap="1""#),
            "allowOverlap 가 IR 값(1)으로 방출돼야 한다(종전 0 하드코딩): {}",
            &xml[..xml.len().min(500)]
        );
    }

    #[test]
    fn allow_overlap_zero_when_unset() {
        // allow_overlap=false 이면 allowOverlap="0" (기존 동작 보존).
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"allowOverlap="0""#),
            "기본 0: {}",
            &xml[..xml.len().min(300)]
        );
    }

    // ---------- tc dirty 속성 라운드트립 ----------

    #[test]
    fn tc_dirty_flag_preserved_when_set() {
        // <hp:tc dirty> 는 파싱은 되지만 직렬화 시 "0"으로 하드코딩되어 있었다.
        // dirty_flag=true 인 셀은 dirty="1" 로 방출돼야 한다. RED(수정 전에는 실패).
        let mut t = empty_table(1, 1);
        t.cells[0].dirty_flag = true;
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"dirty="1""#),
            "dirty_flag=true 인 셀은 dirty=\"1\" 로 방출돼야 한다: {}",
            &xml[..xml.len().min(500)]
        );
    }

    #[test]
    fn tc_dirty_flag_zero_when_unset() {
        // dirty_flag=false(기본) 이면 기존 동작대로 dirty="0" 유지.
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"dirty="0""#),
            "기본 0: {}",
            &xml[..xml.len().min(300)]
        );
    }

    // ---------- #1387: write_caption — 표 캡션 직렬화 ----------

    fn caption_with_text(text: &str) -> crate::model::shape::Caption {
        let mut para = Paragraph::default();
        para.text = text.to_string();
        let mut caption = crate::model::shape::Caption::default();
        caption.width = 8504;
        caption.spacing = 850;
        caption.max_width = 47624;
        caption.paragraphs.push(para);
        caption
    }

    #[test]
    fn task1387_caption_attrs_reflect_ir() {
        // 속성 5종 역매핑 + 한컴 실물 순서(side, fullSz, width, gap, lastWidth).
        let mut t = empty_table(1, 1);
        t.caption = Some(caption_with_text("캡션"));
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:caption side="BOTTOM" fullSz="0" width="8504" gap="850" lastWidth="47624">"#
            ),
            "caption 속성이 IR 값·실물 순서로 방출되어야 함: {}",
            xml
        );
        assert!(
            xml.contains("<hp:t>캡션</hp:t>"),
            "캡션 subList 문단 텍스트가 방출되어야 함"
        );
        // 자식 순서: outMargin → caption → inMargin (모듈 doc).
        let om = xml.find("<hp:outMargin").unwrap();
        let cp = xml.find("<hp:caption").unwrap();
        let im = xml.find("<hp:inMargin").unwrap();
        assert!(om < cp && cp < im, "caption 은 outMargin 과 inMargin 사이");
    }

    #[test]
    fn task3035_caption_vert_align_reflects_ir() {
        // vertAlign 이 caption.vert_align IR 값을 실제로 반영해야 함(고정 TOP 방출 금지).
        use crate::model::shape::CaptionVertAlign;
        let mut t = empty_table(1, 1);
        let mut c = caption_with_text("c");
        c.vert_align = CaptionVertAlign::Bottom;
        t.caption = Some(c);
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"vertAlign="BOTTOM""#),
            "vertAlign 이 IR 값(BOTTOM)으로 방출되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1387_caption_side_reflects_direction() {
        use crate::model::shape::CaptionDirection;
        for (dir, expected) in [
            (CaptionDirection::Left, r#"side="LEFT""#),
            (CaptionDirection::Right, r#"side="RIGHT""#),
            (CaptionDirection::Top, r#"side="TOP""#),
            (CaptionDirection::Bottom, r#"side="BOTTOM""#),
        ] {
            let mut t = empty_table(1, 1);
            let mut c = caption_with_text("c");
            c.direction = dir;
            t.caption = Some(c);
            let xml = serialize(&t);
            assert!(xml.contains(expected), "{:?} → {}", dir, expected);
        }
    }

    #[test]
    fn task1387_caption_paragraph_controls_emitted() {
        // 캡션 문단 내 인라인 컨트롤(autoNum — ta-pic-001-r 실물 패턴)이 공유 경로로 방출.
        let mut para = Paragraph::default();
        para.text = "\u{0}그림".to_string(); // 확장 컨트롤 문자 위치 0 + 텍스트
        para.char_offsets = vec![0, 1, 2];
        let auto_num = crate::model::control::AutoNumber {
            number_type: crate::model::control::AutoNumberType::Picture,
            ..Default::default()
        };
        para.controls
            .push(crate::model::control::Control::AutoNumber(auto_num));
        let mut caption = crate::model::shape::Caption::default();
        caption.paragraphs.push(para);
        let mut t = empty_table(1, 1);
        t.caption = Some(caption);
        let xml = serialize(&t);
        assert!(
            xml.contains("<hp:autoNum"),
            "캡션 내 autoNum 컨트롤이 방출되어야 함: {}",
            xml
        );
        assert!(
            xml.contains(r#"numType="PICTURE""#),
            "그림 번호는 한컴 실물 표기 PICTURE 로 방출 — FIGURE 는 한컴 미인식(#1387 판정): {}",
            xml
        );
    }

    #[test]
    fn task1387_no_caption_no_emission() {
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(
            !xml.contains("<hp:caption"),
            "caption 없는 표는 hp:caption 미방출 (기존 동작 무변화)"
        );
    }

    #[test]
    fn tbl_root_attrs_in_canonical_order() {
        let t = empty_table(2, 3);
        let xml = serialize(&t);
        assert!(xml.contains("<hp:tbl "), "should emit <hp:tbl>: {}", xml);
        // id → zOrder → numberingType → textWrap → textFlow → lock → dropcapstyle →
        // pageBreak → repeatHeader → rowCnt → colCnt → cellSpacing → borderFillIDRef → noAdjust
        let ip = xml.find("id=").unwrap();
        let zp = xml.find("zOrder=").unwrap();
        let nt = xml.find("numberingType=").unwrap();
        let tw = xml.find("textWrap=").unwrap();
        let tf = xml.find("textFlow=").unwrap();
        let rc = xml.find("rowCnt=").unwrap();
        let cc = xml.find("colCnt=").unwrap();
        let bf = xml.find("borderFillIDRef=").unwrap();
        let na = xml.find("noAdjust=").unwrap();
        assert!(
            ip < zp && zp < nt && nt < tw && tw < tf && tf < rc && rc < cc && cc < bf && bf < na
        );
    }

    #[test]
    fn tr_count_matches_row_count() {
        let t = empty_table(4, 2);
        let xml = serialize(&t);
        assert_eq!(xml.matches("<hp:tr>").count(), 4);
    }

    #[test]
    fn cellzone_list_omitted_when_no_zones() {
        // 셀 영역이 없으면(원본에 cellzoneList 부재) 출력하지 않는다.
        let t = empty_table(2, 2);
        assert!(t.zones.is_empty());
        let xml = serialize(&t);
        assert!(
            !xml.contains("cellzone"),
            "zones 없음 → cellzoneList 미출력: {xml}"
        );
    }

    #[test]
    fn cellzone_list_serialized_between_inmargin_and_tr() {
        // [Finding 13] 셀 영역 테두리/배경(cellzone)이 inMargin 다음, 첫 tr 앞에
        // 정확한 속성 순서로 복원되어야 한다(종전엔 IR 에만 있고 직렬화 누락).
        use crate::model::table::TableZone;
        let mut t = empty_table(15, 12);
        t.zones.push(TableZone {
            start_row: 2,
            start_col: 0,
            end_row: 14,
            end_col: 11,
            border_fill_id: 5,
        });
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:cellzoneList><hp:cellzone startRowAddr="2" startColAddr="0" endRowAddr="14" endColAddr="11" borderFillIDRef="5"/></hp:cellzoneList>"#
            ),
            "cellzone 정확 복원 실패: {xml}"
        );
        // 자식 순서: inMargin < cellzoneList < 첫 tr
        let im = xml.find("<hp:inMargin").expect("inMargin");
        let cz = xml.find("<hp:cellzoneList>").expect("cellzoneList");
        let tr = xml.find("<hp:tr>").expect("tr");
        assert!(
            im < cz && cz < tr,
            "순서 inMargin<cellzoneList<tr 위반: {xml}"
        );
    }

    #[test]
    fn tc_count_matches_cell_count() {
        let t = empty_table(2, 3);
        let xml = serialize(&t);
        assert_eq!(xml.matches("<hp:tc ").count(), 6);
    }

    #[test]
    fn cells_have_canonical_child_order() {
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        // subList → cellAddr → cellSpan → cellSz → cellMargin
        let sl = xml.find("<hp:subList ").unwrap();
        let ca = xml.find("<hp:cellAddr ").unwrap();
        let cs = xml.find("<hp:cellSpan ").unwrap();
        let cz = xml.find("<hp:cellSz ").unwrap();
        let cm = xml.find("<hp:cellMargin ").unwrap();
        assert!(sl < ca && ca < cs && cs < cz && cz < cm);
    }

    #[test]
    fn cell_addr_reflects_coordinates() {
        let t = empty_table(2, 2);
        let xml = serialize(&t);
        assert!(xml.contains(r#"<hp:cellAddr colAddr="0" rowAddr="0"/>"#));
        assert!(xml.contains(r#"<hp:cellAddr colAddr="1" rowAddr="0"/>"#));
        assert!(xml.contains(r#"<hp:cellAddr colAddr="0" rowAddr="1"/>"#));
        assert!(xml.contains(r#"<hp:cellAddr colAddr="1" rowAddr="1"/>"#));
    }

    #[test]
    fn cell_span_defaults_to_one() {
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(xml.contains(r#"<hp:cellSpan colSpan="1" rowSpan="1"/>"#));
    }

    #[test]
    fn border_fill_id_ref_registered_in_ctx() {
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut t = empty_table(1, 1);
        t.border_fill_id = 99;
        t.cells[0].border_fill_id = 99;
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, &t, &mut ctx).unwrap();
        // 99 는 등록되지 않은 borderFill → unresolved
        assert!(ctx.border_fill_ids.unresolved().contains(&99u16));
    }

    #[test]
    fn text_flow_default_is_both_sides() {
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(xml.contains(r#"textFlow="BOTH_SIDES""#), "{}", xml);
    }

    #[test]
    fn text_flow_left_only_serialized() {
        let mut t = empty_table(1, 1);
        t.common.text_flow = TextFlow::LeftOnly;
        let xml = serialize(&t);
        assert!(xml.contains(r#"textFlow="LEFT_ONLY""#), "{}", xml);
    }

    #[test]
    fn text_flow_right_only_serialized() {
        let mut t = empty_table(1, 1);
        t.common.text_flow = TextFlow::RightOnly;
        let xml = serialize(&t);
        assert!(xml.contains(r#"textFlow="RIGHT_ONLY""#), "{}", xml);
    }

    #[test]
    fn text_flow_largest_only_serialized() {
        let mut t = empty_table(1, 1);
        t.common.text_flow = TextFlow::LargestOnly;
        let xml = serialize(&t);
        assert!(xml.contains(r#"textFlow="LARGEST_ONLY""#), "{}", xml);
    }

    #[test]
    fn cell_paragraph_ids_are_globally_unique() {
        // 2×2 표 = 셀 4개, 각 셀에 문단 1개 → id="0", id="1", id="2", id="3"
        let t = empty_table(2, 2);
        let xml = serialize(&t);
        assert_eq!(
            xml.matches(r#"<hp:p id="0""#).count(),
            1,
            "셀 문단 id=0 이 중복됨: {}",
            &xml[..xml.len().min(400)]
        );
        for expected_id in 0..4u32 {
            assert!(
                xml.contains(&format!(r#"<hp:p id="{}""#, expected_id)),
                "id={} 가 없음",
                expected_id
            );
        }
    }

    #[test]
    fn cell_para_ids_continue_from_context_counter() {
        // 컨텍스트 카운터를 5 앞당긴 뒤 직렬화하면 셀 문단 id가 5부터 시작해야 함.
        // 본문 문단이 먼저 id 0~4를 소비한 상황을 모사한다.
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        for _ in 0..5 {
            ctx.next_para_id();
        }
        let t = empty_table(1, 2); // 셀 2개 × 문단 1개 → id=5, id=6 이어야 함
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, &t, &mut ctx).unwrap();
        let xml = String::from_utf8(w.into_inner()).unwrap();
        assert!(
            xml.contains(r#"<hp:p id="5""#),
            "첫 셀 문단은 id=5 여야 함 (카운터 오프셋 5): {}",
            &xml[..xml.len().min(600)]
        );
        assert!(
            xml.contains(r#"<hp:p id="6""#),
            "두 번째 셀 문단은 id=6 여야 함"
        );
    }

    #[test]
    fn two_sequential_tables_have_no_para_id_collision() {
        // 같은 ctx로 표 두 개를 연달아 직렬화 — 두 번째 표가 카운터를 초기화하면
        // id=0 이 2번 나타나므로 회귀를 탐지할 수 있다.
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, &empty_table(2, 2), &mut ctx).unwrap(); // id 0-3
        write_table(&mut w, &empty_table(2, 2), &mut ctx).unwrap(); // id 4-7
        let xml = String::from_utf8(w.into_inner()).unwrap();

        assert_eq!(
            xml.matches(r#"<hp:p id="0""#).count(),
            1,
            "id=0 이 중복 — 두 번째 표가 카운터를 재사용했을 가능성"
        );
        for expected_id in 0..8u32 {
            assert!(
                xml.contains(&format!(r#"<hp:p id="{}""#, expected_id)),
                "id={} 가 없음 (총 8개 문단이어야 함)",
                expected_id
            );
        }
    }

    #[test]
    fn multi_para_cells_all_get_unique_ids() {
        // 셀당 문단 3개, 2×2 표 → 총 12개 문단, id=0..11 전부 1회씩
        let doc = Document::default();
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut t = empty_table(2, 2);
        for cell in &mut t.cells {
            cell.paragraphs.push(Paragraph::default());
            cell.paragraphs.push(Paragraph::default());
        }
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, &t, &mut ctx).unwrap();
        let xml = String::from_utf8(w.into_inner()).unwrap();

        let p_count = xml.matches("<hp:p ").count();
        assert_eq!(p_count, 12, "문단 수가 12여야 함: {}", p_count);

        for expected_id in 0..12u32 {
            assert_eq!(
                xml.matches(&format!(r#"<hp:p id="{}""#, expected_id))
                    .count(),
                1,
                "id={} 가 없거나 중복됨",
                expected_id
            );
        }
    }

    #[test]
    fn cell_text_serializes_tab_and_line_break_as_hwpx_inline_elements() {
        let mut t = empty_table(1, 1);
        let para = &mut t.cells[0].paragraphs[0];
        para.text = "A\tB\nC".to_string();
        para.tab_extended = vec![[2000, 0, 0x0100, 0, 0, 0, 0]];

        let xml = serialize(&t);

        assert!(
            xml.contains(
                r#"<hp:t>A<hp:tab width="2000" leader="0" type="1"/>B<hp:lineBreak/>C</hp:t>"#
            ),
            "cell text must emit hp:tab/hp:lineBreak instead of raw control chars: {}",
            xml
        );
    }

    #[test]
    fn task1378_cell_paragraph_multi_run_split() {
        // 셀 문단 다중 char_shapes → 경계 기준 다중 run 분할 (#1378 3단계).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "abcd".to_string();
            para.char_offsets = vec![0, 1, 2, 3];
            para.char_count = 5;
            para.char_shapes = vec![cs(0, 1), cs(2, 2)];
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:run charPrIDRef="1"><hp:t>ab</hp:t></hp:run><hp:run charPrIDRef="2"><hp:t>cd</hp:t></hp:run>"#
            ),
            "셀 문단이 경계에서 2 run 으로 분할되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1378_cell_boundary_with_control_gap_offsets() {
        // IR 내 컨트롤(8 유닛 갭)이 있어도 char_offsets 매핑으로 경계 위치가
        // 어긋나지 않는다 (컨트롤 자체의 출력은 #1379 범위).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "abcd".to_string();
            para.char_offsets = vec![0, 1, 10, 11];
            para.char_count = 13;
            para.char_shapes = vec![cs(0, 1), cs(10, 2)];
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:run charPrIDRef="1"><hp:t>ab</hp:t></hp:run><hp:run charPrIDRef="2"><hp:t>cd</hp:t></hp:run>"#
            ),
            "경계(pos=10)가 컨트롤 갭 뒤 'c' 앞에 떨어져야 함: {}",
            xml
        );
    }

    /// bin_data_id=1 을 참조하는 Picture 컨트롤 — `serialize_with_bin` 과 함께 사용.
    fn picture_control() -> crate::model::control::Control {
        let mut pic = crate::model::image::Picture::default();
        pic.image_attr.bin_data_id = 1;
        crate::model::control::Control::Picture(Box::new(pic))
    }

    /// BinDataContent(id=1) 등록 문서 기준으로 직렬화 — hp:pic 방출 테스트용.
    fn serialize_with_bin(table: &Table) -> String {
        let mut doc = Document::default();
        doc.bin_data_content
            .push(crate::model::bin_data::BinDataContent {
                id: 1,
                data: vec![0u8; 4].into(),
                extension: "png".to_string(),
            });
        let mut ctx = SerializeContext::collect_from_document(&doc);
        let mut w: Writer<Vec<u8>> = Writer::new(Vec::new());
        write_table(&mut w, table, &mut ctx).expect("write_table");
        String::from_utf8(w.into_inner()).unwrap()
    }

    #[test]
    fn task1379_cell_paragraph_emits_picture_control() {
        // 셀 문단의 Picture 컨트롤이 hp:pic 으로 방출되어야 함 (#1379 2단계).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.char_count = 9; // 슬롯 1개(8 유닛) + 종단 1
            para.controls.push(picture_control());
        }
        let xml = serialize_with_bin(&t);
        assert!(
            xml.contains("<hp:pic "),
            "셀 문단의 Picture 가 hp:pic 으로 방출되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1379_nested_table_in_cell_recurses_with_unique_para_ids() {
        // 셀 안 표 재귀 — 중첩 hp:tbl 방출 + next_para_id 채번 무충돌.
        let mut outer = empty_table(1, 1);
        {
            let para = &mut outer.cells[0].paragraphs[0];
            para.char_count = 9;
            para.controls
                .push(crate::model::control::Control::Table(Box::new(
                    empty_table(1, 1),
                )));
        }
        let xml = serialize(&outer);
        assert_eq!(
            xml.matches("<hp:tbl ").count(),
            2,
            "중첩 hp:tbl 이 방출되어야 함: {}",
            xml
        );
        assert_eq!(xml.matches("<hp:p ").count(), 2, "문단 2개여야 함");
        for id in 0..2u32 {
            assert_eq!(
                xml.matches(&format!(r#"<hp:p id="{}""#, id)).count(),
                1,
                "id={} 가 없거나 중복 — 재귀 채번 충돌",
                id
            );
        }
    }

    #[test]
    fn task1379_cell_control_slot_position_between_text() {
        // char_offsets 8 유닛 갭 위치에서 컨트롤이 정확히 방출되어야 함.
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "ab".to_string();
            para.char_offsets = vec![0, 9]; // a=0, 슬롯=1..9, b=9
            para.char_count = 11;
            para.controls.push(picture_control());
        }
        let xml = serialize_with_bin(&t);
        let a = xml.find("<hp:t>a</hp:t>").expect("a 텍스트");
        let p = xml.find("<hp:pic ").expect("hp:pic");
        let b = xml.find("<hp:t>b</hp:t>").expect("b 텍스트");
        assert!(a < p && p < b, "슬롯이 a 와 b 사이에 와야 함: {}", xml);
    }

    #[test]
    fn page_break_str_is_exact_inverse_of_parser() {
        // 직렬화 문자열은 파서(parser/hwpx/section.rs pageBreak)의 정확한 역이어야
        // HWPX→HWPX 왕복이 충실하다. 파서: "TABLE"→CellBreak, "CELL"/"ROW"→RowBreak.
        // 따라서 직렬화: CellBreak→"TABLE", RowBreak→"CELL". (뒤바뀌면 한컴 HWPX 의
        // CELL↔TABLE 의미가 왕복 시 스왑된다.)
        assert_eq!(table_page_break_str(TablePageBreak::None), "NONE");
        assert_eq!(table_page_break_str(TablePageBreak::CellBreak), "TABLE");
        assert_eq!(table_page_break_str(TablePageBreak::RowBreak), "CELL");
    }

    // ---------- #2697: hp:tbl 크기·번호 범주 속성 라운드트립 ----------

    #[test]
    fn task2697_sz_criteria_and_protect_emitted_from_ir() {
        // [#2697] hp:sz 의 widthRelTo/heightRelTo/protect 는 IR 을 보존해야 한다.
        // 종전 "ABSOLUTE"/"ABSOLUTE"/"0" 하드코딩은 파서가 이미 읽어 둔 값을 버렸다. RED.
        let mut t = empty_table(1, 1);
        t.common.width_criterion = SizeCriterion::Column;
        t.common.height_criterion = SizeCriterion::Paper;
        t.common.size_protect = true;
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"widthRelTo="COLUMN""#),
            "widthRelTo 가 IR(Column)로 방출돼야 함(현재 ABSOLUTE 하드코딩): {}",
            &xml[..xml.len().min(400)]
        );
        assert!(
            xml.contains(r#"heightRelTo="PAPER""#),
            "heightRelTo 가 IR(Paper)로 방출돼야 함(현재 ABSOLUTE 하드코딩): {}",
            &xml[..xml.len().min(400)]
        );
        assert!(
            xml.contains(r#"protect="1""#),
            "protect 가 IR(size_protect=true)로 방출돼야 함(현재 0 하드코딩): {}",
            &xml[..xml.len().min(400)]
        );
    }

    #[test]
    fn task2697_sz_defaults_unchanged() {
        // 기본 IR(Absolute/Absolute/false)은 종전 출력과 동일해야 한다(무변화 보장).
        let t = empty_table(1, 1);
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"widthRelTo="ABSOLUTE""#)
                && xml.contains(r#"heightRelTo="ABSOLUTE""#)
                && xml.contains(r#"protect="0""#),
            "기본값 출력이 바뀌면 안 됨: {}",
            &xml[..xml.len().min(400)]
        );
    }

    #[test]
    fn task2697_numbering_type_emitted_from_ir() {
        // [#2697] numberingType 은 IR 을 보존해야 한다. 종전 "TABLE" 리터럴. RED.
        use crate::model::shape::ObjectNumberingType;
        let mut t = empty_table(1, 1);
        t.common.numbering_type = ObjectNumberingType::Picture;
        let xml = serialize(&t);
        assert!(
            xml.contains(r#"numberingType="PICTURE""#),
            "numberingType 이 IR(Picture)로 방출돼야 함(현재 TABLE 하드코딩): {}",
            &xml[..xml.len().min(400)]
        );
        // 기본값(Table)은 종전 출력과 동일.
        let mut t2 = empty_table(1, 1);
        t2.common.numbering_type = ObjectNumberingType::Table;
        assert!(serialize(&t2).contains(r#"numberingType="TABLE""#));
    }

    #[test]
    fn task2697_tbl_attrs_survive_xml_ir_xml_roundtrip() {
        // XML → IR → XML 전 구간. 파서 arm 부재(protect/numberingType)와 방출 하드코딩이
        // 모두 걸리는 통합 케이스.
        use crate::model::shape::ObjectNumberingType;
        use crate::parser::hwpx::section::parse_hwpx_section;

        let src = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph"
        xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">
  <hp:p paraPrIDRef="0" styleIDRef="0">
    <hp:tbl numberingType="PICTURE" textWrap="TOP_AND_BOTTOM" pageBreak="CELL"
            repeatHeader="0" rowCnt="1" colCnt="1" cellSpacing="0" borderFillIDRef="0"
            noAdjust="0">
      <hp:sz width="42520" widthRelTo="COLUMN" height="10000" heightRelTo="PAPER" protect="1"/>
      <hp:pos treatAsChar="0" flowWithText="1" allowOverlap="0"
              vertRelTo="PARA" horzRelTo="COLUMN" vertAlign="TOP" horzAlign="LEFT"
              vertOffset="0" horzOffset="0"/>
      <hp:outMargin left="0" right="0" top="0" bottom="0"/>
      <hp:inMargin left="0" right="0" top="0" bottom="0"/>
      <hp:tr>
        <hp:tc borderFillIDRef="0">
          <hp:cellAddr colAddr="0" rowAddr="0"/>
          <hp:cellSpan colSpan="1" rowSpan="1"/>
          <hp:cellSz width="42520" height="10000"/>
        </hp:tc>
      </hp:tr>
    </hp:tbl>
  </hp:p>
</hs:sec>"#;

        let section = parse_hwpx_section(src).expect("파싱");
        let table = match &section.paragraphs[0].controls[0] {
            crate::model::control::Control::Table(t) => t.as_ref().clone(),
            other => panic!("표가 아님: {other:?}"),
        };

        // IR 단계 — 파서가 4속성을 모두 읽어야 한다.
        assert_eq!(
            table.common.width_criterion,
            SizeCriterion::Column,
            "widthRelTo=COLUMN 이 IR 에 남아야 함"
        );
        assert_eq!(
            table.common.height_criterion,
            SizeCriterion::Paper,
            "heightRelTo=PAPER 가 IR 에 남아야 함"
        );
        assert!(
            table.common.size_protect,
            "protect=1 이 IR(size_protect)에 남아야 함(파서 arm 누락)"
        );
        assert_eq!(
            table.common.numbering_type,
            ObjectNumberingType::Picture,
            "numberingType=PICTURE 가 IR 에 남아야 함(파서 arm 누락)"
        );
        // numberingType 이 TABLE 이 아니므로 "표 번호" attr 비트는 서지 않는다.
        assert_eq!(
            table.common.attr & 0x0800_0000,
            0,
            "PICTURE 번호 표에 TABLE 번호 비트가 서면 IR 모순: {:#010x}",
            table.common.attr
        );

        // 방출 단계 — 4속성이 그대로 되살아나야 한다.
        let xml = serialize(&table);
        for expected in [
            r#"numberingType="PICTURE""#,
            r#"widthRelTo="COLUMN""#,
            r#"heightRelTo="PAPER""#,
            r#"protect="1""#,
        ] {
            assert!(xml.contains(expected), "{expected} 유실: {xml}");
        }
    }

    #[test]
    fn task2855_tbl_lock_survives_xml_ir_xml_roundtrip() {
        // [#2855] <hp:tbl> 의 lock(개체 잠금)이 parse_table 에 arm 이 없어 파싱 단계에서
        // 버려지고, 방출측(이 파일 62행)도 bool01(false) 로 하드코딩되어 있어 왕복 시
        // 원본 lock="1" 이 소리 없이 lock="0" 으로 풀린다. RED.
        use crate::parser::hwpx::section::parse_hwpx_section;

        let src = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph"
        xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section">
  <hp:p paraPrIDRef="0" styleIDRef="0">
    <hp:tbl lock="1" rowCnt="1" colCnt="1" cellSpacing="0" borderFillIDRef="0">
      <hp:sz width="1000" widthRelTo="ABSOLUTE" height="1000" heightRelTo="ABSOLUTE"/>
      <hp:pos treatAsChar="0" flowWithText="1" allowOverlap="0"
              vertRelTo="PARA" horzRelTo="COLUMN" vertAlign="TOP" horzAlign="LEFT"
              vertOffset="0" horzOffset="0"/>
      <hp:outMargin left="0" right="0" top="0" bottom="0"/>
      <hp:inMargin left="0" right="0" top="0" bottom="0"/>
      <hp:tr>
        <hp:tc borderFillIDRef="0">
          <hp:cellAddr colAddr="0" rowAddr="0"/>
          <hp:cellSpan colSpan="1" rowSpan="1"/>
          <hp:cellSz width="1000" height="1000"/>
        </hp:tc>
      </hp:tr>
    </hp:tbl>
  </hp:p>
</hs:sec>"#;

        let section = parse_hwpx_section(src).expect("파싱");
        let table = match &section.paragraphs[0].controls[0] {
            crate::model::control::Control::Table(t) => t.as_ref().clone(),
            other => panic!("표가 아님: {other:?}"),
        };

        assert!(
            table.common.locked,
            "lock=\"1\" 이 IR(common.locked)에 남아야 함(parse_table 에 lock arm 누락)"
        );
        let xml = serialize(&table);
        assert!(
            xml.contains(r#"lock="1""#),
            "lock 이 IR 에서 방출돼야 함(현재 bool01(false) 하드코딩): {}",
            &xml[..xml.len().min(400)]
        );
    }

    #[test]
    fn task2697_height_criterion_str_is_exact_inverse_of_parser() {
        // 파서는 높이를 parse_size_criterion(_, allow_column_para=false) 로 읽으므로
        // (section.rs:1693) 치역이 {Paper, Page, Absolute} 3값뿐이다. 방출이 COLUMN/PARA 를
        // 내면 재파싱 시 Absolute 로 접혀 왕복이 비가역이 된다. 너비만 5값 전체를 낸다.
        assert_eq!(height_criterion_str(SizeCriterion::Paper), "PAPER");
        assert_eq!(height_criterion_str(SizeCriterion::Page), "PAGE");
        assert_eq!(height_criterion_str(SizeCriterion::Absolute), "ABSOLUTE");
        assert_eq!(height_criterion_str(SizeCriterion::Column), "ABSOLUTE");
        assert_eq!(height_criterion_str(SizeCriterion::Para), "ABSOLUTE");

        assert_eq!(size_criterion_str(SizeCriterion::Paper), "PAPER");
        assert_eq!(size_criterion_str(SizeCriterion::Page), "PAGE");
        assert_eq!(size_criterion_str(SizeCriterion::Column), "COLUMN");
        assert_eq!(size_criterion_str(SizeCriterion::Para), "PARA");
        assert_eq!(size_criterion_str(SizeCriterion::Absolute), "ABSOLUTE");
    }

    #[test]
    fn task1379_cell_char_shape_boundary_after_control_restored() {
        // #1378 게이트의 경계 8×컨트롤수 시프트 해소 — 경계 (8,77) 이 컨트롤 뒤에 복원.
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "ab".to_string();
            para.char_offsets = vec![8, 9]; // 슬롯=0..8, a=8, b=9
            para.char_count = 11;
            para.char_shapes = vec![cs(0, 1), cs(8, 77)];
            para.controls.push(picture_control());
        }
        let xml = serialize_with_bin(&t);
        assert!(
            xml.contains(r#"<hp:run charPrIDRef="1"><hp:pic "#),
            "run1 은 컨트롤만 포함해야 함: {}",
            xml
        );
        assert!(
            xml.contains(r#"<hp:run charPrIDRef="77"><hp:t>ab</hp:t></hp:run>"#),
            "경계(pos=8)가 컨트롤 뒤 텍스트 앞에 복원되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1379_cell_lineseg_preserved_from_ir() {
        // 합성 lineseg 제거 — IR line_segs 가 있으면 값 그대로 보존 (#177 정렬).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.line_segs.push(crate::model::paragraph::LineSeg {
                text_start: 0,
                vertical_pos: 1234,
                line_height: 900,
                text_height: 900,
                baseline_distance: 765,
                line_spacing: 540,
                column_start: 0,
                segment_width: 7777,
                tag: 0x60000,
            });
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:lineseg textpos="0" vertpos="1234" vertsize="900" textheight="900" baseline="765" spacing="540" horzpos="0" horzsize="7777" flags="393216"/>"#
            ),
            "IR lineseg 값이 그대로 방출되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1379_cell_char_overlap_emitted_as_compose() {
        // 셀 내 글자겹침 — render_control_slot CharOverlap arm (mel-001 양상).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.char_count = 9;
            para.controls
                .push(crate::model::control::Control::CharOverlap(
                    crate::model::control::CharOverlap {
                        chars: vec!['장'],
                        border_type: 0,
                        inner_char_size: -3,
                        expansion: 1,
                        char_shape_ids: vec![37, u32::MAX],
                        hwp_wire_chars: false,
                    },
                ));
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:compose circleType="CHAR" charSz="-3" composeType="OVERLAP" charPrCnt="2" composeText="장">"#
            ),
            "compose 속성이 원본 형태로 방출되어야 함: {}",
            xml
        );
        assert!(
            xml.contains(
                r#"<hp:charPr prIDRef="37"/><hp:charPr prIDRef="4294967295"/></hp:compose>"#
            ),
            "charPr 목록이 미설정(u32::MAX) 포함 그대로 방출되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1387_ta_pic_001_r_roundtrip_preserves_caption() {
        // 이슈 #1387 대표 샘플 — roundtrip 후 표 캡션(문단 텍스트 포함) 보존.
        fn first_table_caption(doc: &Document) -> Option<crate::model::shape::Caption> {
            doc.sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .flat_map(|p| &p.controls)
                .find_map(|c| match c {
                    crate::model::control::Control::Table(t) => t.caption.clone(),
                    _ => None,
                })
        }
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc1 = crate::parser::hwpx::parse_hwpx(&bytes).expect("파싱");
        let cap1 = first_table_caption(&doc1).expect("픽스처 전제: 원본 표에 캡션 존재");
        assert!(
            cap1.paragraphs[0].text.contains("의정활동"),
            "원본 캡션 텍스트 확인: {:?}",
            cap1.paragraphs[0].text
        );
        let out = crate::serializer::hwpx::serialize_hwpx(&doc1).expect("직렬화");
        let doc2 = crate::parser::hwpx::parse_hwpx(&out).expect("재파싱");
        let cap2 = first_table_caption(&doc2).expect("roundtrip 후 캡션이 보존되어야 함");
        assert_eq!(cap1.paragraphs.len(), cap2.paragraphs.len());
        assert_eq!(cap1.width, cap2.width);
        assert_eq!(cap1.spacing, cap2.spacing);
        assert_eq!(cap1.max_width, cap2.max_width);
        assert_eq!(cap1.direction, cap2.direction);
        assert_eq!(cap1.include_margin, cap2.include_margin);
        // #1382 해소(autoNum 폭 축 일관화) 후 텍스트 완전 일치로 승격 —
        // 종전에는 placeholder 변위로 trim_end 비교만 가능했다.
        assert_eq!(
            cap2.paragraphs[0].text, cap1.paragraphs[0].text,
            "캡션 텍스트 완전 일치 (#1382 해소 승격)"
        );
        assert_eq!(
            cap2.paragraphs[0].char_offsets, cap1.paragraphs[0].char_offsets,
            "캡션 char_offsets 보존 — autoNum 8-jump 포함 (#1382)"
        );
        assert_eq!(
            cap1.paragraphs[0].controls.len(),
            cap2.paragraphs[0].controls.len(),
            "캡션 내 컨트롤(autoNum) 수 보존"
        );
    }

    #[test]
    fn task1382_ta_pic_caption_autonum_slot_at_midtext() {
        // 캡션 autoNum 슬롯 위치 회귀 테스트 — RT XML 에서 ctrl 이 한컴 원본 동형의
        // mid-text 위치(`<hp:t>…그림 </hp:t><hp:ctrl>` 패턴)에 방출되는지 고정.
        // (#1387 1차 한컴 판정의 "번호 문장 끝 밀림" 재발 방지)
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc = crate::parser::hwpx::parse_hwpx(&bytes).expect("파싱");
        let out = crate::serializer::hwpx::serialize_hwpx(&doc).expect("직렬화");
        // section0.xml 추출 없이 zip 바이트에서 직접 패턴 탐색은 불가 — 재파싱 IR 로
        // 위치를 검증하고, XML 패턴은 단위 테스트(task1382_autonum_slot_emitted_at_placeholder)가 고정.
        let doc2 = crate::parser::hwpx::parse_hwpx(&out).expect("재파싱");
        let cap = doc2
            .sections
            .iter()
            .flat_map(|s| &s.paragraphs)
            .flat_map(|p| &p.controls)
            .find_map(|c| match c {
                crate::model::control::Control::Table(t) => t.caption.clone(),
                _ => None,
            })
            .expect("RT 캡션");
        let p = &cap.paragraphs[0];
        // placeholder(공백)가 mid-text 위치(인덱스 4)에 있고 직후 offset 이 +8 jump —
        // ctrl 이 끝으로 밀렸다면 jump 가 끝에 가 있거나 소실된다.
        assert_eq!(p.char_offsets.get(4), Some(&4), "placeholder 위치 4");
        assert_eq!(p.char_offsets.get(5), Some(&12), "autoNum 8-jump 직후 12");
    }

    #[test]
    fn task1387_mel_001_roundtrip_caption_text_exact() {
        // autoNum 없는 캡션(mel-001, side=TOP) — 텍스트 완전 일치 + side 역매핑 검증.
        fn first_table_caption(doc: &Document) -> Option<crate::model::shape::Caption> {
            doc.sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .flat_map(|p| &p.controls)
                .find_map(|c| match c {
                    crate::model::control::Control::Table(t) => t.caption.clone(),
                    _ => None,
                })
        }
        let bytes = std::fs::read("samples/hwpx/mel-001.hwpx").expect("샘플 읽기");
        let doc1 = crate::parser::hwpx::parse_hwpx(&bytes).expect("파싱");
        let cap1 = first_table_caption(&doc1).expect("픽스처 전제: 원본 표에 캡션 존재");
        assert_eq!(cap1.direction, crate::model::shape::CaptionDirection::Top);
        let out = crate::serializer::hwpx::serialize_hwpx(&doc1).expect("직렬화");
        let doc2 = crate::parser::hwpx::parse_hwpx(&out).expect("재파싱");
        let cap2 = first_table_caption(&doc2).expect("roundtrip 후 캡션 보존");
        assert_eq!(cap1.paragraphs[0].text, cap2.paragraphs[0].text);
        assert_eq!(cap1.direction, cap2.direction);
    }

    #[test]
    fn task1379_ta_pic_001_r_roundtrip_preserves_cell_pictures() {
        // 이슈 #1379 대표 샘플 — roundtrip 후 셀 내 Picture 전수(실측 2개) 보존.
        fn count_cell_pictures(doc: &Document) -> usize {
            doc.sections
                .iter()
                .flat_map(|s| &s.paragraphs)
                .flat_map(|p| &p.controls)
                .filter_map(|c| match c {
                    crate::model::control::Control::Table(t) => Some(t),
                    _ => None,
                })
                .flat_map(|t| &t.cells)
                .flat_map(|c| &c.paragraphs)
                .flat_map(|p| &p.controls)
                .filter(|c| matches!(c, crate::model::control::Control::Picture(_)))
                .count()
        }
        let bytes = std::fs::read("samples/hwpx/ta-pic-001-r.hwpx").expect("샘플 읽기");
        let doc1 = crate::parser::hwpx::parse_hwpx(&bytes).expect("파싱");
        let n1 = count_cell_pictures(&doc1);
        // 원본 section0.xml 실측 hp:pic 2개 (전부 셀 내부) — 이슈 본문의 "4개" 는
        // 부정확 수치로 확인됨 (stage2 보고서 참조).
        assert_eq!(n1, 2, "원본 셀 내 Picture 는 2개여야 함");
        let out = crate::serializer::hwpx::serialize_hwpx(&doc1).expect("직렬화");
        let doc2 = crate::parser::hwpx::parse_hwpx(&out).expect("재파싱");
        assert_eq!(
            count_cell_pictures(&doc2),
            n1,
            "roundtrip 후 셀 내 Picture 수가 보존되어야 함"
        );
    }

    #[test]
    fn task1379_cell_column_def_emits_col_pr() {
        // 셀 문단의 ColumnDef 가 hp:ctrl/hp:colPr 인라인으로 방출되어야 함 (#1379 3단계).
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.char_count = 9; // 슬롯 1개(8 유닛) + 종단 1
            let mut cd = crate::model::page::ColumnDef::default();
            cd.column_count = 1;
            cd.same_width = true;
            para.controls
                .push(crate::model::control::Control::ColumnDef(cd));
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:ctrl><hp:colPr id="" type="NEWSPAPER" layout="LEFT" colCount="1" sameSz="1" sameGap="0"/></hp:ctrl>"#
            ),
            "셀 문단의 ColumnDef 가 hp:colPr 로 방출되어야 함: {}",
            xml
        );
    }

    #[test]
    fn task1379_cell_column_def_col_line_emitted_when_separator() {
        // separator_type≠0 인 경우 hp:colLine 자식 방출.
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.char_count = 9;
            let mut cd = crate::model::page::ColumnDef::default();
            cd.column_count = 2;
            cd.same_width = true;
            cd.spacing = 1134;
            cd.separator_type = 2; // DASH
            cd.separator_width = 1; // 0.12 mm
            para.controls
                .push(crate::model::control::Control::ColumnDef(cd));
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(r##"<hp:colLine type="DASH" width="0.12 mm" color="#000000"/>"##),
            "separator 있는 ColumnDef 는 hp:colLine 을 방출해야 함: {}",
            xml
        );
    }

    #[test]
    fn task1378_cell_tab_in_split_runs() {
        // 탭 포함 셀 문단 run 분할 — 탭은 첫 run 에, 분할 텍스트는 새 run 에.
        let mut t = empty_table(1, 1);
        {
            let para = &mut t.cells[0].paragraphs[0];
            para.text = "a\tb".to_string();
            para.char_offsets = vec![0, 1, 2];
            para.char_count = 4;
            para.char_shapes = vec![cs(0, 1), cs(2, 2)];
            para.tab_extended = vec![[2000, 0, 0x0100, 0, 0, 0, 0]];
        }
        let xml = serialize(&t);
        assert!(
            xml.contains(
                r#"<hp:run charPrIDRef="1"><hp:t>a<hp:tab width="2000" leader="0" type="1"/></hp:t></hp:run><hp:run charPrIDRef="2"><hp:t>b</hp:t></hp:run>"#
            ),
            "탭 포함 분할: run1=a+tab, run2=b 여야 함: {}",
            xml
        );
    }
}