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
use super::*;

// ── Golden / structural tests ─────────────────────────────────────────────

// ── golden file test: verify actual XML output ─────────────────────────

/// Golden file test that validates the writer's actual XML output byte-for-byte
/// rather than relying on roundtrip fidelity.  Builds a comprehensive IR document
/// (heading, bold paragraph, italic paragraph, table, list), writes it to HWPX,
/// then inspects specific XML files inside the ZIP for expected patterns.
#[test]
fn golden_comprehensive_document_structure() {
    use std::io::Read as _;

    // ── 1. Build a comprehensive IR document ──

    let doc = Document {
        metadata: Metadata {
            title: Some("Golden Test Doc".into()),
            author: Some("Test Author".into()),
            ..Metadata::default()
        },
        sections: vec![Section {
            blocks: vec![
                // H1 heading
                Block::Heading {
                    level: 1,
                    inlines: vec![Inline::plain("Main Title")],
                },
                // Paragraph with bold inline
                Block::Paragraph {
                    inlines: vec![inline("Normal text "), bold_inline("bold text")],
                },
                // Paragraph with italic inline
                Block::Paragraph {
                    inlines: vec![italic_inline("italic text")],
                },
                // 2x2 table
                Block::Table {
                    rows: vec![
                        TableRow {
                            cells: vec![
                                TableCell {
                                    blocks: vec![Block::Paragraph {
                                        inlines: vec![inline("Cell A1")],
                                    }],
                                    colspan: 1,
                                    rowspan: 1,
                                },
                                TableCell {
                                    blocks: vec![Block::Paragraph {
                                        inlines: vec![inline("Cell B1")],
                                    }],
                                    colspan: 1,
                                    rowspan: 1,
                                },
                            ],
                            is_header: true,
                        },
                        TableRow {
                            cells: vec![
                                TableCell {
                                    blocks: vec![Block::Paragraph {
                                        inlines: vec![inline("Cell A2")],
                                    }],
                                    colspan: 1,
                                    rowspan: 1,
                                },
                                TableCell {
                                    blocks: vec![Block::Paragraph {
                                        inlines: vec![inline("Cell B2")],
                                    }],
                                    colspan: 1,
                                    rowspan: 1,
                                },
                            ],
                            is_header: false,
                        },
                    ],
                    col_count: 2,
                },
                // Code block
                Block::CodeBlock {
                    language: Some("rust".into()),
                    code: "fn main() {}".into(),
                },
                // Horizontal rule
                Block::HorizontalRule,
                // Block quote
                Block::BlockQuote {
                    blocks: vec![Block::Paragraph {
                        inlines: vec![inline("quoted text")],
                    }],
                },
                // Unordered list
                Block::List {
                    ordered: false,
                    start: 1,
                    items: vec![
                        ListItem {
                            blocks: vec![Block::Paragraph {
                                inlines: vec![inline("List item one")],
                            }],
                            children: Vec::new(),
                        },
                        ListItem {
                            blocks: vec![Block::Paragraph {
                                inlines: vec![inline("List item two")],
                            }],
                            children: Vec::new(),
                        },
                    ],
                },
            ],

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

    // ── 2. Write to HWPX bytes ──

    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    write_hwpx(&doc, tmp.path(), None).expect("write_hwpx");

    // ── 3. Open the ZIP and read specific XML entries ──

    let file = std::fs::File::open(tmp.path()).expect("open zip");
    let mut archive = zip::ZipArchive::new(file).expect("parse zip");

    // -- section0.xml assertions --
    let section_xml = {
        let mut entry = archive
            .by_name("Contents/section0.xml")
            .expect("section0.xml must exist in HWPX");
        let mut buf = String::new();
        entry.read_to_string(&mut buf).expect("read section0.xml");
        buf
    };

    // Verify heading has styleIDRef
    assert!(
        section_xml.contains(r#"hp:styleIDRef="1""#),
        "H1 heading must have hp:styleIDRef=\"1\" in section XML:\n{section_xml}"
    );

    // Verify heading text
    assert!(
        section_xml.contains("<hp:t>Main Title</hp:t>"),
        "heading text 'Main Title' must appear in <hp:t>:\n{section_xml}"
    );

    // Verify bold inline charPr
    assert!(
        section_xml.contains(r#"bold="true""#),
        "bold inline must emit charPr with bold=\"true\":\n{section_xml}"
    );

    // Verify bold text content
    assert!(
        section_xml.contains("<hp:t>bold text</hp:t>"),
        "bold text content must appear in <hp:t>:\n{section_xml}"
    );

    // Verify italic inline charPr
    assert!(
        section_xml.contains(r#"italic="true""#),
        "italic inline must emit charPr with italic=\"true\":\n{section_xml}"
    );

    // Verify italic text content
    assert!(
        section_xml.contains("<hp:t>italic text</hp:t>"),
        "italic text content must appear in <hp:t>:\n{section_xml}"
    );

    // Verify normal (non-bold, non-italic) text
    assert!(
        section_xml.contains("<hp:t>Normal text </hp:t>"),
        "plain text must appear in <hp:t>:\n{section_xml}"
    );

    // Verify table structure
    assert!(
        section_xml.contains(r#"<hp:tbl"#),
        "table must emit <hp:tbl> element:\n{section_xml}"
    );
    assert!(
        section_xml.contains(r#"rowCnt="2""#),
        "table must have rowCnt=\"2\":\n{section_xml}"
    );
    assert!(
        section_xml.contains(r#"colCnt="2""#),
        "table must have colCnt=\"2\":\n{section_xml}"
    );
    assert!(
        section_xml.contains("<hp:tr>"),
        "table must contain <hp:tr> rows:\n{section_xml}"
    );
    assert!(
        section_xml.contains("<hp:tc>"),
        "table must contain <hp:tc> cells:\n{section_xml}"
    );
    assert!(
        section_xml.contains("<hp:t>Cell A1</hp:t>"),
        "table cell text 'Cell A1' must appear:\n{section_xml}"
    );
    assert!(
        section_xml.contains("<hp:t>Cell B2</hp:t>"),
        "table cell text 'Cell B2' must appear:\n{section_xml}"
    );

    // Verify list items are emitted as paragraphs
    assert!(
        section_xml.contains("<hp:t>List item one</hp:t>"),
        "list item text 'List item one' must appear:\n{section_xml}"
    );
    assert!(
        section_xml.contains("<hp:t>List item two</hp:t>"),
        "list item text 'List item two' must appear:\n{section_xml}"
    );

    // Verify section XML namespace declarations
    assert!(
        section_xml.contains("xmlns:hs="),
        "section XML must declare hs namespace:\n{section_xml}"
    );
    assert!(
        section_xml.contains("xmlns:hp="),
        "section XML must declare hp namespace:\n{section_xml}"
    );

    // Verify no inline <hp:charPr> for plain text runs (the plain text
    // runs should only have a charPrIDRef attribute, not an inline element).
    // We check that the number of <hp:charPr occurrences matches the number
    // of formatted inlines (bold + italic = 2).
    let charpr_count = section_xml.matches("<hp:charPr ").count();
    assert!(
        charpr_count >= 2,
        "at least 2 inline <hp:charPr> elements expected (bold + italic), found {charpr_count}:\n{section_xml}"
    );

    // -- content.hpf assertions --
    let content_hpf = {
        let mut entry = archive
            .by_name("Contents/content.hpf")
            .expect("content.hpf must exist in HWPX");
        let mut buf = String::new();
        entry.read_to_string(&mut buf).expect("read content.hpf");
        buf
    };

    assert!(
        content_hpf.contains("section0.xml"),
        "content.hpf must reference section0.xml:\n{content_hpf}"
    );
    assert!(
        content_hpf.contains("<hp:title>Golden Test Doc</hp:title>"),
        "content.hpf must contain document title:\n{content_hpf}"
    );
    assert!(
        content_hpf.contains("<hp:author>Test Author</hp:author>"),
        "content.hpf must contain document author:\n{content_hpf}"
    );

    // -- header.xml assertions --
    let header_xml = {
        let mut entry = archive
            .by_name("Contents/header.xml")
            .expect("header.xml must exist in HWPX");
        let mut buf = String::new();
        entry.read_to_string(&mut buf).expect("read header.xml");
        buf
    };

    // Header must contain fontface declarations
    assert!(
        header_xml.contains("hh:fontface"),
        "header.xml must contain fontface declarations:\n{header_xml}"
    );

    // Header must contain charProperties
    assert!(
        header_xml.contains("hh:charPr"),
        "header.xml must contain charPr entries:\n{header_xml}"
    );

    // Header must contain styles (heading styles)
    assert!(
        header_xml.contains("hh:style"),
        "header.xml must contain style entries:\n{header_xml}"
    );

    // -- Verify code block text --
    assert!(
        section_xml.contains("<hp:t>fn main() {}</hp:t>"),
        "code block text must appear in <hp:t>:\n{section_xml}"
    );

    // -- Verify horizontal rule produces box-drawing characters --
    assert!(
        section_xml.contains("\u{2500}"),
        "horizontal rule must emit box-drawing characters:\n{section_xml}"
    );

    // -- Verify block quote text (emitted as plain paragraph) --
    assert!(
        section_xml.contains("<hp:t>quoted text</hp:t>"),
        "block quote text must appear in <hp:t>:\n{section_xml}"
    );

    // -- mimetype assertion --
    let mimetype = {
        let mut entry = archive
            .by_name("mimetype")
            .expect("mimetype must exist in HWPX");
        let mut buf = String::new();
        entry.read_to_string(&mut buf).expect("read mimetype");
        buf
    };
    assert_eq!(
        mimetype, "application/hwp+zip",
        "mimetype must be exactly 'application/hwp+zip'"
    );

    // -- version.xml assertion --
    archive
        .by_name("version.xml")
        .expect("version.xml must exist in HWPX");

    // -- META-INF/container.xml assertion --
    let container_xml = {
        let mut entry = archive
            .by_name("META-INF/container.xml")
            .expect("META-INF/container.xml must exist in HWPX");
        let mut buf = String::new();
        entry.read_to_string(&mut buf).expect("read container.xml");
        buf
    };
    assert!(
        container_xml.contains("content.hpf"),
        "container.xml must reference content.hpf:\n{container_xml}"
    );

    // -- Block quote must use paraPrIDRef="1" (indented paragraph) --
    assert!(
        section_xml.contains(r#"paraPrIDRef="1""#),
        "block quote paragraph must use paraPrIDRef=\"1\":\n{section_xml}"
    );

    // -- header.xml must have paraPr id="1" with left margin --
    assert!(
        header_xml.contains(r#"<hh:paraPr id="1">"#),
        "header.xml must contain paraPr id=\"1\" for blockquote indent:\n{header_xml}"
    );
}

// ── Phase A-3 tests: BlockQuote paraPr header + roundtrip ──────────────

#[test]
fn header_xml_contains_blockquote_para_pr() {
    let doc = doc_with_section(vec![Block::Paragraph {
        inlines: vec![inline("text")],
    }]);
    let tables = RefTables::build(&doc);
    let header =
        super::header::generate_header_xml(&doc, &tables).expect("generate_header_xml failed");

    // paraPr id="0" (normal) must exist.
    assert!(
        header.contains(r#"<hh:paraPr id="0">"#),
        "header must contain paraPr id=\"0\":\n{header}"
    );
    // paraPr id="1" (blockquote indent) must exist.
    assert!(
        header.contains(r#"<hh:paraPr id="1">"#),
        "header must contain paraPr id=\"1\":\n{header}"
    );
    // paraPr id="4" (heading — wider line spacing) must exist.
    assert!(
        header.contains(r#"<hh:paraPr id="4">"#),
        "header must contain paraPr id=\"4\" for heading spacing:\n{header}"
    );
    // itemCnt must be "5" for paraProperties (id=0 normal, id=1 blockquote,
    // id=2 list-depth-0, id=3 list-depth-1+, id=4 heading).
    assert!(
        header.contains(r#"itemCnt="5""#),
        "paraProperties itemCnt must be 5:\n{header}"
    );
    // paraPr id="1" must have a left margin value of 800.
    assert!(
        header.contains(r#"<hh:left value="800"/>"#),
        "paraPr id=\"1\" must have left margin 800:\n{header}"
    );
}

#[test]
fn header_xml_para_pr_0_has_zero_left_margin() {
    let doc = doc_with_section(vec![Block::Paragraph {
        inlines: vec![inline("text")],
    }]);
    let tables = RefTables::build(&doc);
    let header =
        super::header::generate_header_xml(&doc, &tables).expect("generate_header_xml failed");

    // paraPr id="0" must have left margin = 0.
    // We verify that the first paraPr (id=0) has <hh:left value="0"/>.
    // Since id=0 comes first, the first occurrence of <hh:left is from id=0.
    let first_left_pos = header
        .find(r#"<hh:left value="#)
        .expect("hh:left must exist");
    let first_left_slice = &header[first_left_pos..];
    assert!(
        first_left_slice.starts_with(r#"<hh:left value="0"/>"#),
        "first paraPr (id=0) must have left margin 0:\n{header}"
    );
}

#[test]
fn roundtrip_blockquote_content_preserved() {
    let tmp = tempfile::NamedTempFile::new().expect("tmp file");
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::BlockQuote {
                blocks: vec![Block::Paragraph {
                    inlines: vec![inline("roundtrip quote")],
                }],
            }],

            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");

    // The text must survive the roundtrip.  The reader currently does not
    // reconstruct BlockQuote from paraPrIDRef, so the content appears as
    // a plain Paragraph -- that is acceptable for now.
    let has_quote_text = read_back
        .sections
        .iter()
        .flat_map(|s| &s.blocks)
        .any(|b| match b {
            Block::Paragraph { inlines } => inlines.iter().any(|i| i.text == "roundtrip quote"),
            Block::BlockQuote { blocks } => blocks.iter().any(|b2| {
                matches!(b2, Block::Paragraph { inlines } if inlines.iter().any(|i| i.text == "roundtrip quote"))
            }),
            _ => false,
        });
    assert!(
        has_quote_text,
        "blockquote text must survive HWPX roundtrip; sections: {:?}",
        read_back.sections
    );
}