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

// ── Table writer tests ────────────────────────────────────────────────────
//
// Verify that Block::Table is emitted as a fully-compliant OWPML `<hp:tbl>`
// element containing all required child elements, and that cell text is
// preserved across a write-then-read roundtrip.

// ── helpers ───────────────────────────────────────────────────────────────

/// Build a `Document` containing a single table with the given rows.
fn table_doc(rows: Vec<ir::TableRow>) -> Document {
    let col_count = rows.iter().map(|r| r.cells.len()).max().unwrap_or(0);
    Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Table { rows, col_count, inner_margin: None }],
            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    }
}

/// Construct a plain-text `TableCell` with a single paragraph.
fn text_cell(text: &str) -> ir::TableCell {
    ir::TableCell {
        blocks: vec![Block::Paragraph {
            inlines: vec![Inline::plain(text)],
        }],
        colspan: 1,
        rowspan: 1,
    }
}

/// Construct a `TableRow` from a slice of cell text strings.
fn text_row(texts: &[&str], is_header: bool) -> ir::TableRow {
    ir::TableRow {
        cells: texts.iter().map(|t| text_cell(t)).collect(),
        is_header,
    }
}

// ── Test: required OWPML elements present in section XML ─────────────────

/// A 2-column × 3-row table must produce section XML that contains every
/// mandatory OWPML child element of `<hp:tbl>`.
#[test]
fn write_table_2x3_has_required_elements() {
    let rows = vec![
        text_row(&["A1", "A2"], true),
        text_row(&["B1", "B2"], false),
        text_row(&["C1", "C2"], false),
    ];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    assert!(xml.contains("<hp:tbl "), "must contain <hp:tbl>: {xml}");
    assert!(
        xml.contains("<hp:tblPr>"),
        "must contain <hp:tblPr>: {xml}"
    );
    assert!(
        xml.contains("<hp:inMargin "),
        "must contain <hp:inMargin>: {xml}"
    );
    assert!(
        xml.contains(r#"borderFillIDRef="2""#),
        "tbl must reference borderFill id=2: {xml}"
    );
    assert!(
        xml.contains(r#"noAdjust="0""#),
        "tbl must have noAdjust=\"0\": {xml}"
    );
    assert!(xml.contains("<hp:sz "), "must contain <hp:sz>: {xml}");
    assert!(xml.contains("<hp:pos "), "must contain <hp:pos>: {xml}");
    assert!(
        xml.contains("<hp:trHeight "),
        "must contain <hp:trHeight>: {xml}"
    );
    assert!(
        xml.contains("<hp:cellAddr "),
        "must contain <hp:cellAddr>: {xml}"
    );
    assert!(
        xml.contains("<hp:cellSpan "),
        "must contain <hp:cellSpan>: {xml}"
    );
    assert!(
        xml.contains("<hp:cellSz "),
        "must contain <hp:cellSz>: {xml}"
    );
    assert!(
        xml.contains("<hp:cellMargin "),
        "must contain <hp:cellMargin>: {xml}"
    );
    // Pin cell padding attribute values against silent const drift.
    let cm_start = xml.find("<hp:cellMargin ").expect("<hp:cellMargin> missing");
    let cm_end = xml[cm_start..].find("/>").expect("/>") + cm_start;
    let cm_tag = &xml[cm_start..=cm_end + 1];
    assert!(cm_tag.contains(r#"left="510""#),   "cellMargin left must be 510: {cm_tag}");
    assert!(cm_tag.contains(r#"right="510""#),  "cellMargin right must be 510: {cm_tag}");
    assert!(cm_tag.contains(r#"top="141""#),    "cellMargin top must be 141: {cm_tag}");
    assert!(cm_tag.contains(r#"bottom="141""#), "cellMargin bottom must be 141: {cm_tag}");
    assert!(
        xml.contains("<hp:subList>"),
        "must contain <hp:subList>: {xml}"
    );
    assert!(
        xml.contains("</hp:subList>"),
        "must close </hp:subList>: {xml}"
    );
}

/// The `<hp:tbl>` element must carry the correct `rowCnt` and `colCnt`
/// attributes derived from the IR table dimensions.
#[test]
fn write_table_row_col_count_attributes() {
    let rows = vec![
        text_row(&["A1", "A2", "A3"], true),
        text_row(&["B1", "B2", "B3"], false),
    ];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    assert!(
        xml.contains(r#"rowCnt="2""#),
        "rowCnt must be 2: {xml}"
    );
    assert!(
        xml.contains(r#"colCnt="3""#),
        "colCnt must be 3: {xml}"
    );
}

/// Cell address attributes `colAddr` and `rowAddr` must reflect the
/// zero-based column and row indices of each cell.
#[test]
fn write_table_cell_addr_indices() {
    let rows = vec![
        text_row(&["R0C0", "R0C1"], true),
        text_row(&["R1C0", "R1C1"], false),
    ];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    assert!(
        xml.contains(r#"colAddr="0" rowAddr="0""#),
        "first cell must have colAddr=0 rowAddr=0: {xml}"
    );
    assert!(
        xml.contains(r#"colAddr="1" rowAddr="0""#),
        "second cell of first row must have colAddr=1 rowAddr=0: {xml}"
    );
    assert!(
        xml.contains(r#"colAddr="0" rowAddr="1""#),
        "first cell of second row must have colAddr=0 rowAddr=1: {xml}"
    );
}

/// header.xml must contain a second `<hh:borderFill>` entry with id="2"
/// (the solid-border entry referenced by table cells).
#[test]
fn header_xml_contains_border_fill_id_2() {
    let rows = vec![text_row(&["cell"], false)];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let header =
        super::header::generate_header_xml(&doc, &tables).expect("generate_header_xml failed");

    assert!(
        header.contains(r#"id="2""#),
        "header must contain borderFill id=\"2\": {header}"
    );
    assert!(
        header.contains(r#"itemCnt="2""#),
        "borderFills must declare itemCnt=\"2\": {header}"
    );
}

// ── Test: roundtrip cell text preservation ────────────────────────────────

/// Write a table document to HWPX, read it back, and verify that the text
/// content of all cells is preserved.
#[test]
fn write_table_roundtrip_cell_text() {
    let rows = vec![
        text_row(&["Alpha", "Beta"], true),
        text_row(&["Gamma", "Delta"], false),
    ];
    let doc = table_doc(rows);

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

    let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

    // Find the first Table block in the read-back document.
    let table_block = read_back
        .sections
        .into_iter()
        .flat_map(|s| s.blocks)
        .find_map(|b| match b {
            Block::Table { rows, .. } => Some(rows),
            _ => None,
        })
        .expect("no Table block found after roundtrip");

    assert_eq!(table_block.len(), 2, "expected 2 rows: {table_block:?}");
    assert_eq!(
        table_block[0].cells.len(),
        2,
        "first row must have 2 cells: {table_block:?}"
    );

    // Extract flat text from a cell's block content.
    let cell_text = |cell: &ir::TableCell| -> String {
        cell.blocks
            .iter()
            .flat_map(|b| match b {
                Block::Paragraph { inlines } => inlines.iter().map(|i| i.text.as_str()).collect::<Vec<_>>(),
                _ => vec![],
            })
            .collect::<Vec<_>>()
            .join("")
    };

    assert_eq!(
        cell_text(&table_block[0].cells[0]),
        "Alpha",
        "cell [0][0] text mismatch"
    );
    assert_eq!(
        cell_text(&table_block[0].cells[1]),
        "Beta",
        "cell [0][1] text mismatch"
    );
    assert_eq!(
        cell_text(&table_block[1].cells[0]),
        "Gamma",
        "cell [1][0] text mismatch"
    );
    assert_eq!(
        cell_text(&table_block[1].cells[1]),
        "Delta",
        "cell [1][1] text mismatch"
    );
}

/// A cell with `colspan=2, rowspan=1` must emit `<hp:cellSz width="16000"` (2 × 8000).
///
/// The writer scales `width` by `colspan` so that merged cells span the correct
/// horizontal extent in OWPML.  A normal cell (`colspan=1`) must still have
/// `width="8000"`.
#[test]
fn write_table_colspan_cellsz_scaled() {
    // Row 0: one merged cell (colspan=2) followed by a normal cell (colspan=1).
    let merged_cell = ir::TableCell {
        blocks: vec![Block::Paragraph {
            inlines: vec![Inline::plain("merged")],
        }],
        colspan: 2,
        rowspan: 1,
    };
    let normal_cell = ir::TableCell {
        blocks: vec![Block::Paragraph {
            inlines: vec![Inline::plain("normal")],
        }],
        colspan: 1,
        rowspan: 1,
    };
    let rows = vec![ir::TableRow {
        cells: vec![merged_cell, normal_cell],
        is_header: false,
    }];
    // col_count reflects the *logical* column count (3 columns: 2 merged + 1).
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Table { rows, col_count: 3, inner_margin: None }],
            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    // Merged cell (colspan=2) must emit exactly one width="16000".
    let count_16000 = xml.matches(r#"width="16000""#).count();
    assert_eq!(
        count_16000, 1,
        "expected exactly 1 occurrence of width=\"16000\" (merged cell): {xml}"
    );
    // Normal cell (colspan=1) must emit exactly one width="8000".
    let count_8000 = xml.matches(r#"width="8000""#).count();
    assert_eq!(
        count_8000, 1,
        "expected exactly 1 occurrence of width=\"8000\" (normal cell): {xml}"
    );
}

/// A cell with `colspan=2, rowspan=1` must emit `<hp:cellSpan colSpan="2" rowSpan="1"/>`.
#[test]
fn write_table_colspan_emitted_in_cell_span() {
    let rows = vec![ir::TableRow {
        cells: vec![ir::TableCell {
            blocks: vec![Block::Paragraph {
                inlines: vec![Inline::plain("merged")],
            }],
            colspan: 2,
            rowspan: 1,
        }],
        is_header: false,
    }];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    assert!(
        xml.contains(r#"<hp:cellSpan colSpan="2" rowSpan="1""#),
        "cellSpan must reflect colspan=2: {xml}"
    );
}

/// The `<hp:tbl>` element must contain a `<hp:tblPr>` child with an
/// `<hp:inMargin>` specifying the inner cell gap.
#[test]
fn write_table_has_tblpr() {
    let rows = vec![text_row(&["A", "B"], false)];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    assert!(
        xml.contains("<hp:tblPr>"),
        "must contain <hp:tblPr>: {xml}"
    );
    assert!(
        xml.contains("</hp:tblPr>"),
        "must close </hp:tblPr>: {xml}"
    );
    assert!(
        xml.contains("<hp:inMargin "),
        "must contain <hp:inMargin>: {xml}"
    );
    // Extract the inMargin element to check all four attributes without
    // false positives from cellMargin which also uses "141".
    let im_start = xml.find("<hp:inMargin ").expect("<hp:inMargin> missing");
    let im_end = xml[im_start..].find("/>").expect("/>") + im_start;
    let im_tag = &xml[im_start..=im_end + 1];
    assert!(im_tag.contains(r#"left="141""#),   "inMargin left must be 141: {im_tag}");
    assert!(im_tag.contains(r#"right="141""#),  "inMargin right must be 141: {im_tag}");
    assert!(im_tag.contains(r#"top="141""#),    "inMargin top must be 141: {im_tag}");
    assert!(im_tag.contains(r#"bottom="141""#), "inMargin bottom must be 141: {im_tag}");

    // tblPr must appear before sz (OWPML child-order requirement).
    let tblpr_pos = xml.find("<hp:tblPr>").expect("<hp:tblPr> missing");
    let sz_pos = xml.find("<hp:sz ").expect("<hp:sz> missing");
    assert!(
        tblpr_pos < sz_pos,
        "<hp:tblPr> must appear before <hp:sz>: tblPr@{tblpr_pos}, sz@{sz_pos}"
    );
}

// ── Test: custom inner_margin is honoured by the writer ───────────────────

/// When `Block::Table` carries a non-`None` `inner_margin`, the writer must
/// emit those values in `<hp:inMargin>` instead of the default 141.
#[test]
fn write_table_custom_inner_margin_emitted() {
    use ir::TableInnerMargin;
    let rows = vec![text_row(&["A", "B"], false)];
    let col_count = 2;
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Table {
                rows,
                col_count,
                inner_margin: Some(TableInnerMargin { left: 200, right: 200, top: 100, bottom: 100 }),
            }],
            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    let im_start = xml.find("<hp:inMargin ").expect("<hp:inMargin> missing");
    let im_end = xml[im_start..].find("/>").expect("/>") + im_start;
    let im_tag = &xml[im_start..=im_end + 1];
    assert!(im_tag.contains(r#"left="200""#),   "inMargin left must be 200: {im_tag}");
    assert!(im_tag.contains(r#"right="200""#),  "inMargin right must be 200: {im_tag}");
    assert!(im_tag.contains(r#"top="100""#),    "inMargin top must be 100: {im_tag}");
    assert!(im_tag.contains(r#"bottom="100""#), "inMargin bottom must be 100: {im_tag}");
}

/// When `inner_margin` is `None` (the default), the writer must still emit
/// the standard 141-unit margin — no regression from adding the field.
#[test]
fn write_table_default_inner_margin_when_none() {
    let rows = vec![text_row(&["X"], false)];
    let doc = table_doc(rows);
    let tables = RefTables::build(&doc, None);
    let sec = &doc.sections[0];
    let asset_map = ImageAssetMap::new();
    let xml =
        generate_section_xml(sec, 0, &tables, &asset_map).expect("generate_section_xml failed");

    let im_start = xml.find("<hp:inMargin ").expect("<hp:inMargin> missing");
    let im_end = xml[im_start..].find("/>").expect("/>") + im_start;
    let im_tag = &xml[im_start..=im_end + 1];
    assert!(im_tag.contains(r#"left="141""#),   "default left must be 141: {im_tag}");
    assert!(im_tag.contains(r#"right="141""#),  "default right must be 141: {im_tag}");
    assert!(im_tag.contains(r#"top="141""#),    "default top must be 141: {im_tag}");
    assert!(im_tag.contains(r#"bottom="141""#), "default bottom must be 141: {im_tag}");
}

/// Write a table with a custom `inner_margin`, read it back, and verify the
/// margin is preserved in the parsed `Block::Table`.
#[test]
fn write_table_inner_margin_roundtrip() {
    use ir::TableInnerMargin;
    let rows = vec![text_row(&["Hello"], false)];
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Table {
                rows,
                col_count: 1,
                inner_margin: Some(TableInnerMargin { left: 300, right: 300, top: 50, bottom: 50 }),
            }],
            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

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

    let read_back = read_hwpx(tmp.path()).expect("read_hwpx");

    let table_margin = read_back
        .sections
        .into_iter()
        .flat_map(|s| s.blocks)
        .find_map(|b| match b {
            Block::Table { inner_margin, .. } => Some(inner_margin),
            _ => None,
        })
        .expect("no Table block found after roundtrip");

    let m = table_margin.expect("inner_margin must be Some after roundtrip");
    assert_eq!(m.left,   300, "roundtrip left");
    assert_eq!(m.right,  300, "roundtrip right");
    assert_eq!(m.top,     50, "roundtrip top");
    assert_eq!(m.bottom,  50, "roundtrip bottom");
}

/// All four margin axes must survive the roundtrip independently — catches
/// axis mix-ups (e.g. top written into bottom) that symmetric values hide.
#[test]
fn write_table_asymmetric_inner_margin_roundtrip() {
    use ir::TableInnerMargin;
    let rows = vec![text_row(&["X"], false)];
    let doc = Document {
        metadata: Metadata::default(),
        sections: vec![Section {
            blocks: vec![Block::Table {
                rows,
                col_count: 1,
                inner_margin: Some(TableInnerMargin { left: 11, right: 22, top: 33, bottom: 44 }),
            }],
            page_layout: None,
            ..Default::default()
        }],
        assets: Vec::new(),
    };

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

    let m = read_back
        .sections
        .into_iter()
        .flat_map(|s| s.blocks)
        .find_map(|b| match b {
            Block::Table { inner_margin, .. } => inner_margin,
            _ => None,
        })
        .expect("inner_margin must be Some after roundtrip");

    assert_eq!(m.left,   11, "roundtrip left");
    assert_eq!(m.right,  22, "roundtrip right");
    assert_eq!(m.top,    33, "roundtrip top");
    assert_eq!(m.bottom, 44, "roundtrip bottom");
}