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
/// Phase C-3: Code block language preservation tests.
///
/// Verifies that the language hint stored on `Block::CodeBlock.language` is:
/// 1. Emitted as an XML comment (`<!-- hwp2md:lang:LANG -->`) in section XML.
/// 2. Parsed back by the reader into the `language` field on roundtrip.
/// 3. Rendered with the correct fence in Markdown output.
use super::*;

// ── writer: XML comment emission ──────────────────────────────────────────

/// The writer must emit `<!-- hwp2md:lang:python -->` before the code
/// paragraph when language is `Some("python")`.
#[test]
fn section_xml_code_block_with_language_emits_lang_comment() {
    let xml = section_xml(vec![Block::CodeBlock {
        language: Some("python".into()),
        // Use code without characters that XML-escapes change, to avoid
        // testing XML escaping behaviour here.
        code: "x = 42".into(),
    }]);
    assert!(
        xml.contains("<!--"),
        "section XML must contain an XML comment for language hint: {xml}"
    );
    assert!(
        xml.contains("hwp2md:lang:python"),
        "section XML must contain the language name in the comment: {xml}"
    );
    assert!(
        xml.contains("x = 42"),
        "code content must still appear in the output: {xml}"
    );
}

/// With no language hint, the writer must still emit the sentinel comment
/// `<!-- hwp2md:lang: -->` (empty language) so the reader knows this is a
/// code block rather than a regular paragraph.
#[test]
fn section_xml_code_block_without_language_emits_empty_lang_comment() {
    let xml = section_xml(vec![Block::CodeBlock {
        language: None,
        code: "no lang code".into(),
    }]);
    assert!(
        xml.contains("hwp2md:lang:"),
        "section XML must contain hwp2md:lang: sentinel for code block: {xml}"
    );
    // The language part after the colon must be empty (just whitespace).
    assert!(
        xml.contains("hwp2md:lang: "),
        "empty-language sentinel must end with a space before -->: {xml}"
    );
    assert!(
        xml.contains("no lang code"),
        "code content must still appear: {xml}"
    );
}

/// Language hint comment must appear **before** the `<hp:p>` element, not
/// inside it, so the XML remains well-formed.
#[test]
fn section_xml_lang_comment_precedes_paragraph() {
    let xml = section_xml(vec![Block::CodeBlock {
        language: Some("rust".into()),
        code: "fn main() {}".into(),
    }]);
    let comment_pos = xml
        .find("hwp2md:lang:rust")
        .expect("lang comment must exist");
    let p_pos = xml[comment_pos..]
        .find("<hp:p ")
        .map(|off| comment_pos + off)
        .expect("<hp:p must follow the comment");
    assert!(
        comment_pos < p_pos,
        "language comment must appear before <hp:p: {xml}"
    );
}

/// The language comment must not appear for non-code blocks.
#[test]
fn section_xml_lang_comment_absent_for_paragraph() {
    let xml = section_xml(vec![Block::Paragraph {
        inlines: vec![inline("just text")],
    }]);
    assert!(
        !xml.contains("hwp2md:lang:"),
        "hwp2md:lang: comment must NOT appear for a plain paragraph: {xml}"
    );
}

// ── reader: language hint comment parsing ─────────────────────────────────

/// Given section XML that contains the language-hint comment before a code
/// paragraph, the reader must reconstruct a `Block::CodeBlock` with the
/// correct `language`.
#[test]
fn reader_parses_lang_comment_into_code_block_language() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
        xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <!-- hwp2md:lang:rust -->
  <hp:p id="0" paraPrIDRef="0">
    <hp:run charPrIDRef="2">
      <hp:t>fn hello() {}</hp:t>
    </hp:run>
  </hp:p>
</hs:sec>"#;

    let section = read_hwpx_section_xml(xml);
    assert_eq!(
        section.blocks.len(),
        1,
        "expected 1 block: {:?}",
        section.blocks
    );
    match &section.blocks[0] {
        Block::CodeBlock { language, code } => {
            assert_eq!(
                language.as_deref(),
                Some("rust"),
                "language must be 'rust': {:?}",
                section.blocks
            );
            assert_eq!(code, "fn hello() {}", "code content must be preserved");
        }
        other => panic!("expected CodeBlock, got {other:?}"),
    }
}

/// An empty `<!-- hwp2md:lang: -->` comment must produce a `CodeBlock` with
/// `language: None`.
#[test]
fn reader_parses_empty_lang_comment_into_code_block_no_language() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
        xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <!-- hwp2md:lang: -->
  <hp:p id="0" paraPrIDRef="0">
    <hp:run charPrIDRef="2">
      <hp:t>no language here</hp:t>
    </hp:run>
  </hp:p>
</hs:sec>"#;

    let section = read_hwpx_section_xml(xml);
    assert_eq!(
        section.blocks.len(),
        1,
        "expected 1 block: {:?}",
        section.blocks
    );
    match &section.blocks[0] {
        Block::CodeBlock { language, code } => {
            assert!(
                language.is_none(),
                "language must be None for empty hint: {:?}",
                section.blocks
            );
            assert_eq!(code, "no language here", "code content must be preserved");
        }
        other => panic!("expected CodeBlock, got {other:?}"),
    }
}

/// A comment that does NOT start with `hwp2md:lang:` must not affect parsing.
#[test]
fn reader_ignores_unrelated_xml_comments() {
    let xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<hs:sec xmlns:hs="http://www.hancom.co.kr/hwpml/2011/section"
        xmlns:hp="http://www.hancom.co.kr/hwpml/2011/paragraph">
  <!-- some unrelated comment -->
  <hp:p id="0" paraPrIDRef="0">
    <hp:run charPrIDRef="0">
      <hp:t>normal text</hp:t>
    </hp:run>
  </hp:p>
</hs:sec>"#;

    let section = read_hwpx_section_xml(xml);
    assert_eq!(
        section.blocks.len(),
        1,
        "expected 1 block: {:?}",
        section.blocks
    );
    assert!(
        matches!(&section.blocks[0], Block::Paragraph { .. }),
        "unrelated comment must not turn paragraph into code block: {:?}",
        section.blocks
    );
}

// ── roundtrip: MD language → HWPX → MD ───────────────────────────────────

/// Full HWPX roundtrip: a `CodeBlock` with `language = Some("python")` must
/// survive write-then-read with the language preserved.
#[test]
fn roundtrip_code_block_with_language_preserved() {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::CodeBlock {
                language: Some("python".into()),
                code: "x = 1\nprint(x)\n".into(),
            }],

            page_layout: None,
        }],
        assets: Vec::new(),
    };
    write_hwpx(&doc, tmp.path(), None).expect("write_hwpx");
    let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

    let code_block = read_back
        .sections
        .iter()
        .flat_map(|s| &s.blocks)
        .find(|b| matches!(b, Block::CodeBlock { .. }))
        .expect("CodeBlock must survive HWPX roundtrip");

    match code_block {
        Block::CodeBlock { language, code } => {
            assert_eq!(
                language.as_deref(),
                Some("python"),
                "language must be 'python' after roundtrip"
            );
            assert_eq!(code, "x = 1\nprint(x)\n", "code content must be preserved");
        }
        _ => unreachable!(),
    }
}

/// Full HWPX roundtrip: a `CodeBlock` with no language must survive with
/// `language` remaining `None`.
#[test]
fn roundtrip_code_block_no_language_preserved() {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::CodeBlock {
                language: None,
                code: "plain code".into(),
            }],

            page_layout: None,
        }],
        assets: Vec::new(),
    };
    write_hwpx(&doc, tmp.path(), None).expect("write_hwpx");
    let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

    let code_block = read_back
        .sections
        .iter()
        .flat_map(|s| &s.blocks)
        .find(|b| matches!(b, Block::CodeBlock { .. }))
        .expect("CodeBlock must survive HWPX roundtrip");

    match code_block {
        Block::CodeBlock { language, code } => {
            assert!(
                language.is_none(),
                "language must remain None after roundtrip: {language:?}"
            );
            assert_eq!(code, "plain code", "code content must be preserved");
        }
        _ => unreachable!(),
    }
}

/// Edge case: unusual language names with special characters must roundtrip
/// without corruption.  Tested names: "c++", "objective-c", "shell".
#[test]
fn roundtrip_code_block_unusual_language_names() {
    for lang in &["c++", "objective-c", "shell"] {
        let tmp = tempfile::NamedTempFile::new().expect("tmp file");
        let doc = Document {
            metadata: Metadata::default(),
            sections: vec![Section {
                blocks: vec![Block::CodeBlock {
                    language: Some((*lang).to_string()),
                    code: format!("// {lang} code"),
                }],

                page_layout: None,
            }],
            assets: Vec::new(),
        };
        write_hwpx(&doc, tmp.path(), None).expect("write_hwpx");
        let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

        let code_block = read_back
            .sections
            .iter()
            .flat_map(|s| &s.blocks)
            .find(|b| matches!(b, Block::CodeBlock { .. }))
            .unwrap_or_else(|| panic!("CodeBlock must survive roundtrip for language '{lang}'"));

        match code_block {
            Block::CodeBlock {
                language: found_lang,
                ..
            } => {
                assert_eq!(
                    found_lang.as_deref(),
                    Some(*lang),
                    "language '{lang}' must survive roundtrip"
                );
            }
            _ => unreachable!(),
        }
    }
}

/// A document with a code block followed by a normal paragraph must have both
/// blocks correctly reconstructed after roundtrip.
#[test]
fn roundtrip_code_block_followed_by_paragraph() {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![
                Block::CodeBlock {
                    language: Some("bash".into()),
                    code: "echo hello".into(),
                },
                Block::Paragraph {
                    inlines: vec![inline("after code")],
                },
            ],

            page_layout: None,
        }],
        assets: Vec::new(),
    };
    write_hwpx(&doc, tmp.path(), None).expect("write_hwpx");
    let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

    let blocks: Vec<_> = read_back.sections.iter().flat_map(|s| &s.blocks).collect();

    let has_code = blocks.iter().any(
        |b| matches!(b, Block::CodeBlock { language, .. } if language.as_deref() == Some("bash")),
    );
    let has_para = blocks
        .iter()
        .any(|b| matches!(b, Block::Paragraph { inlines } if inlines.iter().any(|i| i.text == "after code")));

    assert!(has_code, "code block must survive roundtrip: {blocks:?}");
    assert!(has_para, "paragraph must survive roundtrip: {blocks:?}");
}

// ── MD writer: language in fence ──────────────────────────────────────────

/// The Markdown writer must emit ` ```python ` (with language) when
/// `language` is `Some("python")`.
#[test]
fn md_writer_code_block_with_language_emits_fence_with_lang() {
    use crate::md::write_markdown;

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::CodeBlock {
                language: Some("python".into()),
                code: "x = 42\n".into(),
            }],

            page_layout: None,
        }],
        assets: Vec::new(),
    };

    let md = write_markdown(&doc, false);
    assert!(
        md.contains("```python"),
        "Markdown must contain ```python fence: {md}"
    );
    assert!(md.contains("x = 42"), "code content must appear: {md}");
}

/// The Markdown writer must emit a plain ` ``` ` fence (no language label)
/// when `language` is `None`.
#[test]
fn md_writer_code_block_no_language_emits_plain_fence() {
    use crate::md::write_markdown;

    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::CodeBlock {
                language: None,
                code: "no lang\n".into(),
            }],

            page_layout: None,
        }],
        assets: Vec::new(),
    };

    let md = write_markdown(&doc, false);
    // The opening fence must be exactly ``` with no language tag.
    assert!(
        md.contains("```\n"),
        "Markdown must have plain ``` fence when language is None: {md}"
    );
    assert!(md.contains("no lang"), "code content must appear: {md}");
}

// ── XML comment injection guard ───────────────────────────────────────────

/// A language string containing `-->` must not break the surrounding XML
/// comment.  The writer sanitizes `--` → `-` so the emitted comment remains
/// well-formed and parseable.
#[test]
fn section_xml_code_block_language_with_comment_injection_is_sanitized() {
    // A language that embeds `-->` would close the XML comment prematurely
    // and produce invalid XML.  After sanitization `-->` becomes `->`.
    let xml = section_xml(vec![Block::CodeBlock {
        language: Some("x-->inject".into()),
        code: "boom".into(),
    }]);
    // The raw `-->` sequence must NOT appear inside the emitted comment.
    // Find where our comment starts and verify the payload has no `-->`.
    let comment_start = xml
        .find("<!-- hwp2md:lang:")
        .expect("lang comment must be present in XML");
    let comment_end = xml[comment_start..]
        .find("-->")
        .expect("comment must be closed");
    let comment_inner = &xml[comment_start..comment_start + comment_end];
    assert!(
        !comment_inner.contains("-->"),
        "comment interior must not contain `-->` (XML comment injection): {comment_inner}"
    );
    // The sanitized form must still be recognisable as the language prefix.
    assert!(
        xml.contains("hwp2md:lang:"),
        "lang sentinel must be present: {xml}"
    );
    // Code content must survive.
    assert!(xml.contains("boom"), "code content must be present: {xml}");
}

/// A language with a single `-` (not `--`) must pass through unchanged.
#[test]
fn section_xml_code_block_language_single_dash_unchanged() {
    let xml = section_xml(vec![Block::CodeBlock {
        language: Some("objective-c".into()),
        code: "int x;".into(),
    }]);
    assert!(
        xml.contains("hwp2md:lang:objective-c"),
        "single-dash language must not be altered: {xml}"
    );
}