hwp2md 0.4.0

HWP/HWPX ↔ Markdown bidirectional converter
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
use super::*;

// -----------------------------------------------------------------------
// Existing parse_heading_style tests
// -----------------------------------------------------------------------

#[test]
fn parse_heading_style_heading1() {
    assert_eq!(parse_heading_style("Heading1"), Some(1));
}

#[test]
fn parse_heading_style_heading6() {
    assert_eq!(parse_heading_style("Heading6"), Some(6));
}

#[test]
fn parse_heading_style_korean_title() {
    // "제목1" -> 1
    assert_eq!(parse_heading_style("제목1"), Some(1));
}

#[test]
fn parse_heading_style_korean_outline_3() {
    // "개요3" -> 3
    assert_eq!(parse_heading_style("개요3"), Some(3));
}

#[test]
fn parse_heading_style_normal_is_none() {
    assert_eq!(parse_heading_style("Normal"), None);
}

#[test]
fn parse_heading_style_body_text_is_none() {
    assert_eq!(parse_heading_style("BodyText"), None);
}

#[test]
fn parse_heading_style_heading_no_digit_defaults_to_1() {
    // "Heading" without a trailing digit -> defaults to level 1.
    assert_eq!(parse_heading_style("Heading"), Some(1));
}

#[test]
fn parse_heading_style_case_insensitive() {
    assert_eq!(parse_heading_style("HEADING2"), Some(2));
}

// -----------------------------------------------------------------------
// parse_section_xml -- helper for asserting on the returned Section
// -----------------------------------------------------------------------

/// Unwrap the section and panic with a descriptive message on error.
fn section(xml: &str) -> ir::Section {
    parse_section_xml(xml).expect("parse_section_xml must not fail")
}

// -----------------------------------------------------------------------
// parse_section_xml -- empty / minimal documents
// -----------------------------------------------------------------------

#[test]
fn empty_document_produces_no_blocks() {
    let s = section("<root/>");
    assert!(s.blocks.is_empty(), "expected no blocks for empty XML");
}

#[test]
fn empty_paragraph_produces_no_blocks() {
    // A paragraph element with no run content must be silently dropped.
    let xml = r#"<root><hp:p></hp:p></root>"#;
    let s = section(xml);
    assert!(
        s.blocks.is_empty(),
        "empty paragraph must not produce a block"
    );
}

// -----------------------------------------------------------------------
// parse_section_xml -- simple paragraph
// -----------------------------------------------------------------------

#[test]
fn simple_paragraph_text() {
    // Compact XML -- no whitespace text nodes between tags (matches real HWPX).
    let xml = r#"<root><hp:p><hp:run><hp:t>Hello World</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines.len(), 1);
            assert_eq!(inlines[0].text, "Hello World");
            assert!(!inlines[0].bold);
            assert!(!inlines[0].italic);
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn paragraph_without_hp_prefix() {
    // Bare element names (no namespace prefix) must also parse correctly.
    let xml = r#"<root><p><run><t>bare prefix</t></run></p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines[0].text, "bare prefix");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn multiple_runs_in_one_paragraph_produce_multiple_inlines() {
    let xml = r#"<root><hp:p><hp:run><hp:t>first</hp:t></hp:run><hp:run><hp:t>second</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines.len(), 2);
            assert_eq!(inlines[0].text, "first");
            assert_eq!(inlines[1].text, "second");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- heading via styleIDRef
// -----------------------------------------------------------------------

#[test]
fn heading_level2_via_style_id_ref() {
    let xml = r#"<root><hp:p styleIDRef="Heading2"><hp:run><hp:t>Chapter title</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Heading { level, inlines } => {
            assert_eq!(*level, 2);
            assert_eq!(inlines[0].text, "Chapter title");
        }
        other => panic!("expected Heading, got {other:?}"),
    }
}

#[test]
fn heading_level3_korean_style() {
    let xml =
        r#"<root><hp:p styleIDRef="제목3"><hp:run><hp:t>소제목</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Heading { level, inlines } => {
            assert_eq!(*level, 3);
            assert_eq!(inlines[0].text, "소제목");
        }
        other => panic!("expected Heading, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- bold / italic via Start-element charPr
// -----------------------------------------------------------------------

#[test]
fn bold_text_via_charpr_start_element() {
    // Start-element charPr (non-self-closing) -- handled by handle_start_element.
    let xml = r#"<root><hp:p><hp:run><hp:charPr bold="true" italic="false"></hp:charPr><hp:t>bold text</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(inlines[0].bold, "inline must be bold");
            assert!(!inlines[0].italic, "inline must not be italic");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn italic_text_via_charpr_empty_element() {
    // Self-closing charPr -- handled by handle_empty_element.
    let xml = r#"<root><hp:p><hp:run><hp:charPr bold="false" italic="true"/><hp:t>italic text</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(!inlines[0].bold, "inline must not be bold");
            assert!(inlines[0].italic, "inline must be italic");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn bold_and_italic_via_empty_charpr() {
    let xml = r#"<root><hp:p><hp:run><hp:charPr bold="true" italic="true"/><hp:t>strong em</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(inlines[0].bold);
            assert!(inlines[0].italic);
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn charpr_numeric_1_means_bold() {
    // The parser accepts "1" as well as "true" for boolean attributes.
    let xml = r#"<root><hp:p><hp:run><hp:charPr bold="1"/><hp:t>numeric bold</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(inlines[0].bold, "bold=\"1\" must be treated as true");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn charpr_resets_between_runs() {
    // Second run has no charPr, so bold must revert to false.
    // Compact XML avoids spurious whitespace-only text nodes.
    let xml = r#"<root><hp:p><hp:run><hp:charPr bold="true"/><hp:t>bold</hp:t></hp:run><hp:run><hp:t>plain</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines.len(), 2);
            assert!(inlines[0].bold, "first inline must be bold");
            // The run end event resets bold to false.
            assert!(!inlines[1].bold, "second inline must not be bold");
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- lineBreak (empty element)
// -----------------------------------------------------------------------

#[test]
fn line_break_appends_newline_to_inline_text() {
    // lineBreak is an empty element that appends \n to current_text.
    // It lives outside a <t> so flush_paragraph picks it up at paragraph end.
    let xml = r#"<root><hp:p><hp:run><hp:t>line one</hp:t><hp:lineBreak/></hp:run></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            let full: String = inlines.iter().map(|i| i.text.as_str()).collect();
            assert!(
                full.contains('\n'),
                "paragraph inlines must contain a newline from lineBreak; got: {full:?}"
            );
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- image (empty element)
// -----------------------------------------------------------------------

#[test]
fn image_element_produces_image_block() {
    let xml = r#"<root>
        <hp:img src="image1.png" alt="photo"/>
    </root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Image { src, alt } => {
            assert_eq!(src, "image1.png");
            assert_eq!(alt, "photo");
        }
        other => panic!("expected Image, got {other:?}"),
    }
}

#[test]
fn image_with_empty_src_is_ignored() {
    // An img element with no src attribute must not produce a block.
    let xml = r#"<root><hp:img alt="no src"/></root>"#;
    let s = section(xml);
    assert!(s.blocks.is_empty(), "img without src must be dropped");
}

// -----------------------------------------------------------------------
// parse_section_xml -- equation
// -----------------------------------------------------------------------

#[test]
fn equation_element_produces_math_block() {
    let xml = r#"<root><hp:equation>x^2 + y^2</hp:equation></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Math { display, tex } => {
            assert!(*display, "equation must be display mode");
            assert_eq!(tex, "x^2 + y^2");
        }
        other => panic!("expected Math, got {other:?}"),
    }
}

#[test]
fn empty_equation_produces_no_block() {
    // An equation element with no text content must be silently dropped.
    let xml = r#"<root><hp:equation></hp:equation></root>"#;
    let s = section(xml);
    assert!(
        s.blocks.is_empty(),
        "empty equation must not produce a block"
    );
}

#[test]
fn eqedit_alias_also_produces_math_block() {
    // The parser accepts both <hp:equation> and <hp:eqEdit>.
    let xml = r#"<root><hp:eqEdit>a + b = c</hp:eqEdit></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Math { tex, .. } => assert_eq!(tex, "a + b = c"),
        other => panic!("expected Math, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- table
// -----------------------------------------------------------------------

#[test]
fn simple_table_two_rows_two_cols() {
    let xml = concat!(
        r#"<root><hp:tbl colCnt="2">"#,
        r#"<hp:tr><hp:tc><hp:p><hp:run><hp:t>A1</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>A2</hp:t></hp:run></hp:p></hp:tc></hp:tr>"#,
        r#"<hp:tr><hp:tc><hp:p><hp:run><hp:t>B1</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>B2</hp:t></hp:run></hp:p></hp:tc></hp:tr>"#,
        r#"</hp:tbl></root>"#,
    );
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Table { rows, col_count } => {
            assert_eq!(*col_count, 2);
            assert_eq!(rows.len(), 2);
            // First row is always the header row.
            assert!(rows[0].is_header, "first row must be is_header=true");
            assert!(!rows[1].is_header, "second row must be is_header=false");
            // Verify cell text content.
            let text_of = |row: usize, col: usize| -> String {
                match &rows[row].cells[col].blocks[0] {
                    ir::Block::Paragraph { inlines } => inlines[0].text.clone(),
                    other => panic!("unexpected block {other:?}"),
                }
            };
            assert_eq!(text_of(0, 0), "A1");
            assert_eq!(text_of(0, 1), "A2");
            assert_eq!(text_of(1, 0), "B1");
            assert_eq!(text_of(1, 1), "B2");
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn table_col_count_from_colcnt_attribute() {
    // colCnt="3" but only 2 cells per row -- col_count must be max(3, 2) = 3.
    let xml = concat!(
        r#"<root><hp:tbl colCnt="3"><hp:tr>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>X</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>Y</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { col_count, .. } => {
            assert_eq!(*col_count, 3);
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn table_cell_colspan_from_celladdr() {
    // cellAddr is a self-closing child of tc that sets colspan/rowspan.
    let xml = concat!(
        r#"<root><hp:tbl colCnt="3"><hp:tr>"#,
        r#"<hp:tc><hp:cellAddr colSpan="2" rowSpan="1"/><hp:p><hp:run><hp:t>merged</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>single</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            let cells = &rows[0].cells;
            assert_eq!(cells[0].colspan, 2, "first cell must have colspan=2");
            assert_eq!(cells[0].rowspan, 1, "first cell must have rowspan=1");
            assert_eq!(
                cells[1].colspan, 1,
                "second cell must have default colspan=1"
            );
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn table_cell_rowspan_from_celladdr() {
    let xml = concat!(
        r#"<root><hp:tbl colCnt="1"><hp:tr>"#,
        r#"<hp:tc><hp:cellAddr colSpan="1" rowSpan="3"/><hp:p><hp:run><hp:t>tall</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            assert_eq!(rows[0].cells[0].rowspan, 3);
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn table_default_colspan_rowspan_without_celladdr() {
    // When no cellAddr is present the defaults must be colspan=1, rowspan=1.
    let xml = concat!(
        r#"<root><hp:tbl colCnt="1"><hp:tr>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>cell</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            assert_eq!(rows[0].cells[0].colspan, 1);
            assert_eq!(rows[0].cells[0].rowspan, 1);
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn nested_paragraph_inside_table_cell() {
    // Text inside a table cell must end up in cell blocks, not section blocks.
    let xml = concat!(
        r#"<root><hp:tbl colCnt="1"><hp:tr>"#,
        r#"<hp:tc><hp:p><hp:run><hp:t>cell content</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            let cell = &rows[0].cells[0];
            assert_eq!(cell.blocks.len(), 1);
            match &cell.blocks[0] {
                ir::Block::Paragraph { inlines } => {
                    assert_eq!(inlines[0].text, "cell content");
                }
                other => panic!("expected Paragraph inside cell, got {other:?}"),
            }
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn image_inside_table_cell_goes_to_cell_blocks() {
    let xml = concat!(
        r#"<root><hp:tbl colCnt="1"><hp:tr>"#,
        r#"<hp:tc><hp:img src="fig.png" alt="figure"/></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            let cell = &rows[0].cells[0];
            assert_eq!(cell.blocks.len(), 1);
            match &cell.blocks[0] {
                ir::Block::Image { src, alt } => {
                    assert_eq!(src, "fig.png");
                    assert_eq!(alt, "figure");
                }
                other => panic!("expected Image inside cell, got {other:?}"),
            }
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// parse_section_xml -- list
// -----------------------------------------------------------------------

#[test]
fn ordered_list_without_li_produces_no_block() {
    // The current parser recognises <ol>/<ul> open/close but has no <li>
    // handler, so items will be empty.  The block is only pushed when
    // list_items is non-empty, so an empty ol must produce no block.
    // This test documents the current behaviour explicitly.
    let xml = r#"<root><ol></ol></root>"#;
    let s = section(xml);
    assert!(
        s.blocks.is_empty(),
        "empty <ol> without <li> children must produce no block (current behaviour)"
    );
}

#[test]
fn underline_via_empty_charpr() {
    let xml = r#"<root><hp:p><hp:run><hp:charPr underline="solid"/><hp:t>underlined</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(inlines[0].underline, "inline must be underlined");
            assert!(!inlines[0].bold);
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn strikeout_via_empty_charpr() {
    let xml = r#"<root><hp:p><hp:run><hp:charPr strikeout="true"/><hp:t>struck</hp:t></hp:run></hp:p></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert!(inlines[0].strikethrough, "inline must be strikethrough");
            assert!(!inlines[0].bold);
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn colspan_zero_defaults_to_one() {
    let xml = concat!(
        r#"<root><hp:tbl colCnt="1"><hp:tr>"#,
        r#"<hp:tc><hp:cellAddr colSpan="0" rowSpan="0"/><hp:p><hp:run><hp:t>x</hp:t></hp:run></hp:p></hp:tc>"#,
        r#"</hp:tr></hp:tbl></root>"#,
    );
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::Table { rows, .. } => {
            assert_eq!(rows[0].cells[0].colspan, 1, "colSpan=0 must default to 1");
            assert_eq!(rows[0].cells[0].rowspan, 1, "rowSpan=0 must default to 1");
        }
        other => panic!("expected Table, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// guess_mime_from_name -- all extensions
// -----------------------------------------------------------------------

#[test]
fn guess_mime_png() {
    assert_eq!(guess_mime_from_name("image.png"), "image/png");
}

#[test]
fn guess_mime_jpg() {
    assert_eq!(guess_mime_from_name("photo.jpg"), "image/jpeg");
}

#[test]
fn guess_mime_jpeg() {
    assert_eq!(guess_mime_from_name("photo.jpeg"), "image/jpeg");
}

#[test]
fn guess_mime_gif() {
    assert_eq!(guess_mime_from_name("anim.gif"), "image/gif");
}

#[test]
fn guess_mime_bmp() {
    assert_eq!(guess_mime_from_name("bitmap.bmp"), "image/bmp");
}

#[test]
fn guess_mime_svg() {
    assert_eq!(guess_mime_from_name("vector.svg"), "image/svg+xml");
}

#[test]
fn guess_mime_wmf() {
    assert_eq!(guess_mime_from_name("metafile.wmf"), "image/x-wmf");
}

#[test]
fn guess_mime_emf() {
    assert_eq!(guess_mime_from_name("enhanced.emf"), "image/x-emf");
}

#[test]
fn guess_mime_unknown_extension_falls_back_to_octet_stream() {
    assert_eq!(
        guess_mime_from_name("archive.xyz"),
        "application/octet-stream"
    );
}

#[test]
fn guess_mime_no_extension_falls_back_to_octet_stream() {
    assert_eq!(
        guess_mime_from_name("nodotfile"),
        "application/octet-stream"
    );
}

#[test]
fn guess_mime_case_insensitive_uppercase_png() {
    assert_eq!(guess_mime_from_name("PHOTO.PNG"), "image/png");
}

#[test]
fn guess_mime_case_insensitive_mixed_jpg() {
    assert_eq!(guess_mime_from_name("Photo.Jpg"), "image/jpeg");
}

#[test]
fn guess_mime_case_insensitive_svg() {
    assert_eq!(guess_mime_from_name("LOGO.SVG"), "image/svg+xml");
}

// -----------------------------------------------------------------------
// BinData reference resolution -- resolve_bin_refs + build_bin_map
// -----------------------------------------------------------------------

/// Helper: build a section containing a single top-level Image block.
fn make_image_section(src: &str) -> ir::Section {
    ir::Section {
        blocks: vec![ir::Block::Image {
            src: src.to_string(),
            alt: String::new(),
        }],
    }
}

#[test]
fn resolve_bin_refs_replaces_image_src() {
    // An Image whose src matches a BinData stem must be updated to the
    // full ZIP path, including the extension.
    let bin_files = vec!["BinData/BIN0001.png".to_string()];
    let bin_map = build_bin_map(&bin_files);

    let mut section = make_image_section("BIN0001");
    resolve_bin_refs(&mut section, &bin_map);

    match &section.blocks[0] {
        ir::Block::Image { src, .. } => {
            assert_eq!(
                src, "BinData/BIN0001.png",
                "src must be resolved to full path"
            );
        }
        other => panic!("expected Image, got {other:?}"),
    }
}

#[test]
fn resolve_bin_refs_no_match_leaves_src_unchanged() {
    // An Image with a src that has no entry in the bin_map must not be
    // modified -- e.g. when src is already a full filename or an URL.
    let bin_files = vec!["BinData/BIN0001.png".to_string()];
    let bin_map = build_bin_map(&bin_files);

    let mut section = make_image_section("img.png");
    resolve_bin_refs(&mut section, &bin_map);

    match &section.blocks[0] {
        ir::Block::Image { src, .. } => {
            assert_eq!(src, "img.png", "unmatched src must remain unchanged");
        }
        other => panic!("expected Image, got {other:?}"),
    }
}

#[test]
fn resolve_bin_refs_inside_table_cell() {
    // resolve_block_bin_refs must recurse into Table -> rows -> cells -> blocks.
    let bin_files = vec!["BinData/BIN0002.jpg".to_string()];
    let bin_map = build_bin_map(&bin_files);

    let cell_image = ir::Block::Image {
        src: "BIN0002".to_string(),
        alt: String::new(),
    };
    let cell = ir::TableCell {
        blocks: vec![cell_image],
        colspan: 1,
        rowspan: 1,
    };
    let row = ir::TableRow {
        cells: vec![cell],
        is_header: false,
    };
    let mut section = ir::Section{
        blocks: vec![ir::Block::Table {
            rows: vec![row],
            col_count: 1,
        }],
    
        page_layout: None,};

    resolve_bin_refs(&mut section, &bin_map);

    match &section.blocks[0] {
        ir::Block::Table { rows, .. } => match &rows[0].cells[0].blocks[0] {
            ir::Block::Image { src, .. } => {
                assert_eq!(
                    src, "BinData/BIN0002.jpg",
                    "image inside table cell must be resolved"
                );
            }
            other => panic!("expected Image inside cell, got {other:?}"),
        },
        other => panic!("expected Table, got {other:?}"),
    }
}

#[test]
fn bin_map_from_bin_files() {
    // build_bin_map must produce a map with stem keys and full-path values.
    // It must handle both prefixes (BinData/ and Contents/BinData/).
    let bin_files = vec![
        "BinData/BIN0001.png".to_string(),
        "BinData/BIN0002.jpg".to_string(),
        "Contents/BinData/BIN0003.emf".to_string(),
    ];
    let map = build_bin_map(&bin_files);

    assert_eq!(
        map.get("BIN0001").map(String::as_str),
        Some("BinData/BIN0001.png")
    );
    assert_eq!(
        map.get("BIN0002").map(String::as_str),
        Some("BinData/BIN0002.jpg")
    );
    assert_eq!(
        map.get("BIN0003").map(String::as_str),
        Some("Contents/BinData/BIN0003.emf")
    );
    assert_eq!(map.len(), 3, "map must contain exactly 3 entries");
}
// -----------------------------------------------------------------------
// parse_section_xml -- footnote / endnote parsing
// -----------------------------------------------------------------------

fn first_footnote(s: &ir::Section) -> (&str, &[ir::Block]) {
    match &s.blocks[0] {
        ir::Block::Footnote { id, content } => (id.as_str(), content.as_slice()),
        other => panic!("expected Block::Footnote, got {other:?}"),
    }
}

#[test]
fn footnote_produces_footnote_block() {
    let xml = r#"<root><hp:fn id="1"><hp:p><hp:run><hp:t>note text</hp:t></hp:run></hp:p></hp:fn></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1, "one footnote block expected");
    let (id, content) = first_footnote(&s);
    assert_eq!(id, "1");
    assert_eq!(
        content.len(),
        1,
        "footnote must have exactly one inner block"
    );
    match &content[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines[0].text, "note text");
        }
        other => panic!("expected Paragraph inside footnote, got {other:?}"),
    }
}

#[test]
fn endnote_produces_footnote_block() {
    let xml =
        r#"<root><hp:en id="2"><hp:p><hp:run><hp:t>end note</hp:t></hp:run></hp:p></hp:en></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    let (id, content) = first_footnote(&s);
    assert_eq!(id, "2");
    match &content[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines[0].text, "end note");
        }
        other => panic!("expected Paragraph inside endnote block, got {other:?}"),
    }
}

#[test]
fn footnote_alt_tag_name() {
    let xml = r#"<root><hp:footnote id="3"><hp:p><hp:run><hp:t>alt tag</hp:t></hp:run></hp:p></hp:footnote></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    let (id, content) = first_footnote(&s);
    assert_eq!(id, "3");
    match &content[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines[0].text, "alt tag");
        }
        other => panic!("expected Paragraph inside footnote (alt tag), got {other:?}"),
    }
}

#[test]
fn note_ref_produces_footnote_ref_inline() {
    // <hp:noteRef noteId="1"/> produces an Inline with footnote_ref set and empty text.
    let xml = r#"<root><hp:p><hp:noteRef noteId="1"/></hp:p></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1, "one paragraph block expected");
    match &s.blocks[0] {
        ir::Block::Paragraph { inlines } => {
            assert_eq!(inlines.len(), 1, "one inline expected");
            assert_eq!(
                inlines[0].footnote_ref.as_deref(),
                Some("1"),
                "inline must carry footnote_ref=\"1\""
            );
            assert!(
                inlines[0].text.is_empty(),
                "footnote_ref inline must have empty text"
            );
        }
        other => panic!("expected Paragraph, got {other:?}"),
    }
}

#[test]
fn empty_footnote_ignored() {
    let xml = r#"<root><hp:fn id="1"></hp:fn></root>"#;
    let s = section(xml);
    assert!(
        s.blocks.is_empty(),
        "empty footnote must not produce a Block::Footnote"
    );
}

// -----------------------------------------------------------------------
// Cross-cutting: context x element combinations
// -----------------------------------------------------------------------

#[test]
fn image_inside_footnote_goes_to_footnote_blocks() {
    let xml = r#"<root><hp:fn id="1"><hp:img src="fig.png" alt="fn-img"/></hp:fn></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::Footnote { content, .. } => {
            assert!(
                content
                    .iter()
                    .any(|b| matches!(b, ir::Block::Image { src, .. } if src == "fig.png")),
                "footnote must contain the image block"
            );
        }
        other => panic!("expected Footnote, got {other:?}"),
    }
}

#[test]
fn image_inside_list_item_goes_to_list_item_blocks() {
    let xml = r#"<root><ul><li><hp:img src="pic.png" alt="li-img"/></li></ul></root>"#;
    let s = section(xml);
    assert_eq!(s.blocks.len(), 1);
    match &s.blocks[0] {
        ir::Block::List { items, .. } => {
            assert_eq!(items.len(), 1);
            assert!(
                items[0]
                    .blocks
                    .iter()
                    .any(|b| matches!(b, ir::Block::Image { src, .. } if src == "pic.png")),
                "list item must contain the image block"
            );
        }
        other => panic!("expected List, got {other:?}"),
    }
}

#[test]
fn linebreak_inside_list_item_appends_newline() {
    let xml = r#"<root><ul><li><hp:p><hp:run><hp:t>before</hp:t><hp:lineBreak/></hp:run></hp:p></li></ul></root>"#;
    let s = section(xml);
    match &s.blocks[0] {
        ir::Block::List { items, .. } => {
            let text: String = items[0]
                .blocks
                .iter()
                .filter_map(|b| match b {
                    ir::Block::Paragraph { inlines } => {
                        Some(inlines.iter().map(|i| i.text.as_str()).collect::<String>())
                    }
                    _ => None,
                })
                .collect();
            assert!(
                text.contains('\n'),
                "lineBreak in list item must produce newline; got: {text:?}"
            );
        }
        other => panic!("expected List, got {other:?}"),
    }
}

#[test]
fn resolve_bin_refs_inside_footnote() {
    let bin_map: HashMap<String, String> =
        [("BIN0002".to_string(), "BinData/BIN0002.jpg".to_string())]
            .into_iter()
            .collect();
    let mut section = ir::Section{
        blocks: vec![ir::Block::Footnote {
            id: "1".to_string(),
            content: vec![ir::Block::Image {
                src: "BIN0002".to_string(),
                alt: String::new(),
            }],
        }],
    
        page_layout: None,};
    resolve_bin_refs(&mut section, &bin_map);
    match &section.blocks[0] {
        ir::Block::Footnote { content, .. } => match &content[0] {
            ir::Block::Image { src, .. } => {
                assert_eq!(src, "BinData/BIN0002.jpg");
            }
            other => panic!("expected Image, got {other:?}"),
        },
        other => panic!("expected Footnote, got {other:?}"),
    }
}

#[test]
fn resolve_bin_refs_inside_list() {
    let bin_map: HashMap<String, String> =
        [("BIN0003".to_string(), "BinData/BIN0003.png".to_string())]
            .into_iter()
            .collect();
    let mut section = ir::Section{
        blocks: vec![ir::Block::List {
            ordered: false,
            start: 1,
            items: vec![ir::ListItem {
                blocks: vec![ir::Block::Image {
                    src: "BIN0003".to_string(),
                    alt: String::new(),
                }],
                children: Vec::new(),
            }],
        }],
    
        page_layout: None,};
    resolve_bin_refs(&mut section, &bin_map);
    match &section.blocks[0] {
        ir::Block::List { items, .. } => match &items[0].blocks[0] {
            ir::Block::Image { src, .. } => {
                assert_eq!(src, "BinData/BIN0003.png");
            }
            other => panic!("expected Image, got {other:?}"),
        },
        other => panic!("expected List, got {other:?}"),
    }
}

// -----------------------------------------------------------------------
// apply_charpr_attrs — color attribute parsing
// -----------------------------------------------------------------------

fn make_bytes_start_with_attrs(tag: &str, attrs: &[(&str, &str)]) -> Vec<u8> {
    let mut xml = format!("<{tag}");
    for (k, v) in attrs {
        xml.push_str(&format!(" {k}=\"{v}\""));
    }
    xml.push('>');
    xml.into_bytes()
}

fn apply_attrs_via_xml(tag: &str, attrs: &[(&str, &str)]) -> super::context::ParseContext {
    use quick_xml::events::BytesStart;
    let xml_bytes = make_bytes_start_with_attrs(tag, attrs);
    // Parse just the start tag bytes.
    let start_bytes = xml_bytes
        .iter()
        .take_while(|&&b| b != b'>')
        .cloned()
        .collect::<Vec<_>>();
    let e = BytesStart::from_content(
        std::str::from_utf8(&start_bytes[1..]).unwrap(), // strip leading '<'
        tag.len(),
    );
    let mut ctx = super::context::ParseContext::default();
    super::context::apply_charpr_attrs(&e, &mut ctx);
    ctx
}

#[test]
fn apply_charpr_attrs_color_sets_current_color() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "#FF0000")]);
    assert_eq!(ctx.current_color.as_deref(), Some("#FF0000"));
}

#[test]
fn apply_charpr_attrs_color_without_hash_normalises() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "FF0000")]);
    assert_eq!(ctx.current_color.as_deref(), Some("#FF0000"));
}

#[test]
fn apply_charpr_attrs_black_color_sets_none() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "#000000")]);
    assert!(
        ctx.current_color.is_none(),
        "black color must not be propagated"
    );
}

#[test]
fn apply_charpr_attrs_black_color_without_hash_sets_none() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "000000")]);
    assert!(ctx.current_color.is_none());
}

#[test]
fn apply_charpr_attrs_empty_color_sets_none() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "")]);
    assert!(ctx.current_color.is_none());
}

#[test]
fn apply_charpr_attrs_hp_color_prefix_accepted() {
    let ctx = apply_attrs_via_xml("hp:charPr", &[("hp:color", "0000FF")]);
    assert_eq!(ctx.current_color.as_deref(), Some("#0000FF"));
}

#[test]
fn apply_charpr_attrs_color_lowercase_normalised_to_upper() {
    let ctx = apply_attrs_via_xml("charPr", &[("color", "ff0000")]);
    assert_eq!(ctx.current_color.as_deref(), Some("#FF0000"));
}

// -----------------------------------------------------------------------
// flush_paragraph — color propagation into ir::Inline
// -----------------------------------------------------------------------

#[test]
fn flush_paragraph_propagates_color_to_inline() {
    let mut ctx = super::context::ParseContext::default();
    ctx.in_paragraph = true;
    ctx.current_text = "colored".to_string();
    ctx.current_color = Some("#00FF00".to_string());

    let mut section = crate::ir::Section { blocks: Vec::new(), page_layout: None };
    super::context::flush_paragraph(&mut ctx, &mut section);

    assert_eq!(section.blocks.len(), 1);
    if let crate::ir::Block::Paragraph { inlines } = &section.blocks[0] {
        assert_eq!(inlines[0].color.as_deref(), Some("#00FF00"));
    } else {
        panic!("Expected Paragraph block");
    }
}

#[test]
fn flush_paragraph_no_color_propagates_none() {
    let mut ctx = super::context::ParseContext::default();
    ctx.in_paragraph = true;
    ctx.current_text = "plain".to_string();
    ctx.current_color = None;

    let mut section = crate::ir::Section { blocks: Vec::new(), page_layout: None };
    super::context::flush_paragraph(&mut ctx, &mut section);

    if let crate::ir::Block::Paragraph { inlines } = &section.blocks[0] {
        assert!(inlines[0].color.is_none());
    } else {
        panic!("Expected Paragraph block");
    }
}

// -----------------------------------------------------------------------
// Ruby annotation parsing via parse_section_xml
// -----------------------------------------------------------------------

#[test]
fn ruby_element_produces_inline_with_ruby_annotation() {
    let xml = r#"<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
                          xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
        <hp:p><hp:run>
            <hp:ruby>
                <hp:rubyText>한자</hp:rubyText>
                <hp:baseText>漢字</hp:baseText>
            </hp:ruby>
        </hp:run></hp:p>
    </hs:sec>"#;
    let sec = section(xml);
    assert_eq!(sec.blocks.len(), 1, "one paragraph block expected");
    if let ir::Block::Paragraph { inlines } = &sec.blocks[0] {
        let ruby_inline = inlines
            .iter()
            .find(|i| i.ruby.is_some())
            .expect("must have at least one inline with ruby annotation");
        assert_eq!(ruby_inline.text, "漢字");
        assert_eq!(ruby_inline.ruby.as_deref(), Some("한자"));
    } else {
        panic!("expected Paragraph block, got {:?}", sec.blocks[0]);
    }
}

#[test]
fn ruby_element_without_hp_prefix_also_parsed() {
    let xml = r#"<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
                          xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
        <hp:p><hp:run>
            <ruby>
                <rubyText>annotation</rubyText>
                <baseText>base</baseText>
            </ruby>
        </hp:run></hp:p>
    </hs:sec>"#;
    let sec = section(xml);
    assert_eq!(sec.blocks.len(), 1);
    if let ir::Block::Paragraph { inlines } = &sec.blocks[0] {
        let ruby_inline = inlines
            .iter()
            .find(|i| i.ruby.is_some())
            .expect("must have ruby inline");
        assert_eq!(ruby_inline.text, "base");
        assert_eq!(ruby_inline.ruby.as_deref(), Some("annotation"));
    } else {
        panic!("expected Paragraph");
    }
}

#[test]
fn ruby_element_empty_annotation_no_ruby_field() {
    let xml = r#"<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
                          xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
        <hp:p><hp:run>
            <hp:ruby>
                <hp:rubyText></hp:rubyText>
                <hp:baseText>漢字</hp:baseText>
            </hp:ruby>
        </hp:run></hp:p>
    </hs:sec>"#;
    let sec = section(xml);
    if let ir::Block::Paragraph { inlines } = &sec.blocks[0] {
        let inline = inlines
            .iter()
            .find(|i| i.text == "漢字")
            .expect("base text inline must exist");
        assert!(
            inline.ruby.is_none(),
            "empty rubyText must produce None annotation; got {:?}",
            inline.ruby
        );
    }
}

#[test]
fn ruby_inline_renders_to_html_ruby_tags_in_markdown() {
    use crate::md::write_markdown;

    let xml = r#"<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
                          xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
        <hp:p><hp:run>
            <hp:ruby>
                <hp:rubyText>한자</hp:rubyText>
                <hp:baseText>漢字</hp:baseText>
            </hp:ruby>
        </hp:run></hp:p>
    </hs:sec>"#;
    let sec = section(xml);
    let mut doc = crate::ir::Document::new();
    doc.sections.push(sec);
    let md = write_markdown(&doc, false);
    assert!(
        md.contains("<ruby>漢字<rt>한자</rt></ruby>"),
        "markdown output must contain HTML ruby tags; got: {md}"
    );
}