hwp2md 0.2.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
use crate::hwp::eqedit::eqedit_to_latex;
use crate::hwp::model::*;
use crate::ir;
use crate::url_util::is_safe_url_scheme;

/// HWP font height is in 1/100 point units (HWP internal unit).
/// e.g. 1600 = 16pt, 1400 = 14pt, 1200 = 12pt.
const HEADING1_MIN_HEIGHT: u32 = 1600; // 16pt
const HEADING2_MIN_HEIGHT: u32 = 1400; // 14pt
const HEADING3_MIN_HEIGHT: u32 = 1200; // 12pt

pub(crate) fn hwp_to_ir(hwp: &HwpDocument) -> ir::Document {
    let mut doc = ir::Document::new();

    doc.metadata.title = hwp.summary_title.clone();
    doc.metadata.author = hwp.summary_author.clone();
    doc.metadata.subject = hwp.summary_subject.clone();
    doc.metadata.keywords = hwp.summary_keywords.clone();

    let mut footnote_counter: u32 = 0;
    let mut endnote_counter: u32 = 0;

    for section in &hwp.sections {
        let mut ir_section = ir::Section { blocks: Vec::new() };

        for para in &section.paragraphs {
            let blocks = paragraph_to_blocks_counted(
                para,
                &hwp.doc_info,
                &mut footnote_counter,
                &mut endnote_counter,
            );
            ir_section.blocks.extend(blocks);
        }

        doc.sections.push(ir_section);
    }

    for (id, data) in &hwp.bin_data {
        let mime = guess_mime(data);
        let ext = mime_to_ext(&mime);
        doc.assets.push(ir::Asset {
            name: format!("image_{id}.{ext}"),
            data: data.clone(),
            mime_type: mime,
        });
    }

    doc
}

/// Counter-aware variant used by `hwp_to_ir` to assign unique sequential IDs
/// to footnotes and endnotes across the whole document.
fn paragraph_to_blocks_counted(
    para: &HwpParagraph,
    doc_info: &DocInfo,
    footnote_counter: &mut u32,
    endnote_counter: &mut u32,
) -> Vec<ir::Block> {
    let mut blocks: Vec<ir::Block> = Vec::new();

    for ctrl in &para.controls {
        if let Some(block) =
            control_to_block_counted(ctrl, doc_info, footnote_counter, endnote_counter)
        {
            blocks.push(block);
        }
    }

    let text = para.text.trim();
    if !text.is_empty() {
        let heading_level = detect_heading_level(para, doc_info);
        let inlines = build_inlines(para, doc_info);
        if !inlines.is_empty() {
            let ps_id = para.para_shape_id as usize;
            if ps_id < doc_info.para_shapes.len() {
                if let Some(nid) = doc_info.para_shapes[ps_id].numbering_id {
                    tracing::trace!(
                        numbering_id = nid,
                        "paragraph may be a list item; full list conversion not yet implemented"
                    );
                }
            }

            if let Some(level) = heading_level {
                blocks.push(ir::Block::Heading { level, inlines });
            } else {
                blocks.push(ir::Block::Paragraph { inlines });
            }
        }
    }

    blocks
}

/// Counter-aware variant of `control_to_block` that assigns sequential IDs
/// to footnotes (`footnote-1`, `footnote-2`, …) and endnotes (`endnote-1`, …).
fn control_to_block_counted(
    ctrl: &HwpControl,
    doc_info: &DocInfo,
    footnote_counter: &mut u32,
    endnote_counter: &mut u32,
) -> Option<ir::Block> {
    if let HwpControl::FootnoteEndnote {
        is_endnote,
        paragraphs,
    } = ctrl
    {
        let content: Vec<ir::Block> = paragraphs
            .iter()
            .flat_map(|p| {
                paragraph_to_blocks_counted(p, doc_info, footnote_counter, endnote_counter)
            })
            .collect();
        let id = if *is_endnote {
            *endnote_counter += 1;
            format!("endnote-{endnote_counter}")
        } else {
            *footnote_counter += 1;
            format!("footnote-{footnote_counter}")
        };
        return Some(ir::Block::Footnote { id, content });
    }
    control_to_block(ctrl, doc_info)
}

pub(crate) fn paragraph_to_blocks(para: &HwpParagraph, doc_info: &DocInfo) -> Vec<ir::Block> {
    let mut blocks: Vec<ir::Block> = Vec::new();

    // Emit IR blocks for each embedded control first.  Controls are independent
    // of the paragraph text (a paragraph may contain *only* a table, for example).
    for ctrl in &para.controls {
        if let Some(block) = control_to_block(ctrl, doc_info) {
            blocks.push(block);
        }
    }

    // Emit the text content of the paragraph, if any.
    let text = para.text.trim();
    if !text.is_empty() {
        let heading_level = detect_heading_level(para, doc_info);
        let inlines = build_inlines(para, doc_info);
        if !inlines.is_empty() {
            // Log list-item hint when the paragraph has a numbering_id.
            // Full list-item conversion is left for a future implementation pass.
            let ps_id = para.para_shape_id as usize;
            if ps_id < doc_info.para_shapes.len() {
                if let Some(nid) = doc_info.para_shapes[ps_id].numbering_id {
                    tracing::trace!(
                        numbering_id = nid,
                        "paragraph may be a list item; full list conversion not yet implemented"
                    );
                }
            }

            if let Some(level) = heading_level {
                blocks.push(ir::Block::Heading { level, inlines });
            } else {
                blocks.push(ir::Block::Paragraph { inlines });
            }
        }
    }

    blocks
}

/// Convert a single `HwpControl` to an `ir::Block`.  Returns `None` for
/// controls that have no direct IR representation (e.g. page-break hints).
pub(crate) fn control_to_block(ctrl: &HwpControl, doc_info: &DocInfo) -> Option<ir::Block> {
    match ctrl {
        HwpControl::Table {
            row_count,
            col_count,
            cells,
        } => {
            // Group cells by row index, then sort each row by col index.
            let n_rows = *row_count as usize;
            let n_cols = *col_count as usize;
            let effective_cols = if n_cols > 0 {
                n_cols
            } else {
                cells.iter().map(|c| c.col as usize + 1).max().unwrap_or(1)
            };

            let mut rows: Vec<Vec<&HwpTableCell>> = vec![Vec::new(); n_rows.max(1)];
            for cell in cells {
                let row_idx = cell.row as usize;
                if row_idx < rows.len() {
                    rows[row_idx].push(cell);
                } else if row_idx < 10_000 {
                    rows.resize(row_idx + 1, Vec::new());
                    rows[row_idx].push(cell);
                }
            }

            let ir_rows: Vec<ir::TableRow> = rows
                .into_iter()
                .enumerate()
                .map(|(row_idx, row_cells)| {
                    // Capture is_header from the first cell before sorting consumes the vec.
                    // Fall back to row_idx == 0 for empty rows (no cells parsed).
                    let row_is_header = row_cells
                        .first()
                        .map(|c| c.is_header)
                        .unwrap_or(row_idx == 0);
                    let mut sorted = row_cells;
                    sorted.sort_by_key(|c| c.col);
                    let ir_cells: Vec<ir::TableCell> = sorted
                        .into_iter()
                        .map(|cell| ir::TableCell {
                            blocks: cell
                                .paragraphs
                                .iter()
                                .flat_map(|p| paragraph_to_blocks(p, doc_info))
                                .collect(),
                            colspan: cell.col_span as u32,
                            rowspan: cell.row_span as u32,
                        })
                        .collect();
                    ir::TableRow {
                        cells: ir_cells,
                        is_header: row_is_header,
                    }
                })
                .collect();

            Some(ir::Block::Table {
                rows: ir_rows,
                col_count: effective_cols,
            })
        }
        HwpControl::Image { bin_data_id, .. } => {
            let src = format!("image_{bin_data_id}.bin");
            Some(ir::Block::Image {
                src,
                alt: String::new(),
            })
        }
        HwpControl::Equation { script } => {
            let tex = eqedit_to_latex(script);
            Some(ir::Block::Math {
                display: false,
                tex,
            })
        }
        HwpControl::FootnoteEndnote {
            is_endnote,
            paragraphs,
        } => {
            let content: Vec<ir::Block> = paragraphs
                .iter()
                .flat_map(|p| paragraph_to_blocks(p, doc_info))
                .collect();
            let id = if *is_endnote {
                "endnote".to_string()
            } else {
                "footnote".to_string()
            };
            Some(ir::Block::Footnote { id, content })
        }
        HwpControl::Hyperlink { ref url } => {
            if url.is_empty() || !is_safe_url_scheme(url) {
                None
            } else {
                Some(ir::Block::Paragraph {
                    inlines: vec![ir::Inline {
                        text: url.clone(),
                        link: Some(url.clone()),
                        ..Default::default()
                    }],
                })
            }
        }
        HwpControl::Ruby {
            base_text,
            ruby_text,
        } => {
            if base_text.is_empty() && ruby_text.is_empty() {
                return None;
            }
            Some(ir::Block::Paragraph {
                inlines: vec![ir::Inline {
                    text: base_text.clone(),
                    ruby: if ruby_text.is_empty() {
                        None
                    } else {
                        Some(ruby_text.clone())
                    },
                    ..ir::Inline::default()
                }],
            })
        }
        HwpControl::PageBreak | HwpControl::ColumnBreak => None,
    }
}

pub(crate) fn detect_heading_level(para: &HwpParagraph, doc_info: &DocInfo) -> Option<u8> {
    let ps_id = para.para_shape_id as usize;
    if ps_id < doc_info.para_shapes.len() {
        if let Some(level) = doc_info.para_shapes[ps_id].heading_type {
            if level < 7 {
                return Some((level + 1).min(6));
            }
        }
    }

    let text = para.text.trim();
    if text.chars().count() < 100 {
        if let Some(first_cs) = para.char_shape_ids.first() {
            let cs_id = first_cs.1 as usize;
            if cs_id < doc_info.char_shapes.len() {
                let cs = &doc_info.char_shapes[cs_id];
                if cs.height >= HEADING1_MIN_HEIGHT && cs.bold {
                    return Some(1);
                }
                if cs.height >= HEADING2_MIN_HEIGHT && cs.bold {
                    return Some(2);
                }
                if cs.height >= HEADING3_MIN_HEIGHT && cs.bold {
                    return Some(3);
                }
            }
        }
    }

    None
}

pub(crate) fn build_inlines(para: &HwpParagraph, doc_info: &DocInfo) -> Vec<ir::Inline> {
    let text = &para.text;
    if text.is_empty() {
        return Vec::new();
    }

    if para.char_shape_ids.is_empty() {
        return vec![ir::Inline::plain(text.clone())];
    }

    let chars: Vec<char> = text.chars().collect();
    let mut inlines = Vec::new();
    let char_refs = &para.char_shape_ids;

    for (idx, &(pos, cs_id)) in char_refs.iter().enumerate() {
        let start = pos as usize;
        let end = if idx + 1 < char_refs.len() {
            char_refs[idx + 1].0 as usize
        } else {
            chars.len()
        };

        if start >= chars.len() {
            break;
        }
        let end = end.min(chars.len());
        let segment: String = chars[start..end].iter().collect();
        let segment = segment.trim_end_matches('\r').to_string();

        if segment.is_empty() {
            continue;
        }

        let cs_idx = cs_id as usize;
        let inline = if cs_idx < doc_info.char_shapes.len() {
            let cs = &doc_info.char_shapes[cs_idx];

            // HWP color is stored as u32 in BGR byte order:
            //   bits[ 7: 0] = blue, bits[15: 8] = green, bits[23:16] = red.
            // Only emit a color when the value is not black (0x000000) to avoid
            // wrapping every default run in a redundant <span>.
            let color = if cs.color & 0x00FF_FFFF != 0 {
                let b = (cs.color & 0xFF) as u8;
                let g = ((cs.color >> 8) & 0xFF) as u8;
                let r = ((cs.color >> 16) & 0xFF) as u8;
                Some(format!("#{r:02X}{g:02X}{b:02X}"))
            } else {
                None
            };

            // Resolve font name via face_id lookup in the DocInfo face_names table.
            let font_name = doc_info.face_names.get(cs.face_id as usize).cloned();

            ir::Inline {
                text: segment,
                bold: cs.bold,
                italic: cs.italic,
                underline: cs.underline,
                strikethrough: cs.strikethrough,
                superscript: cs.superscript,
                subscript: cs.subscript,
                color,
                font_name,
                ..ir::Inline::default()
            }
        } else {
            ir::Inline::plain(segment)
        };

        inlines.push(inline);
    }

    inlines
}

fn guess_mime(data: &[u8]) -> String {
    if data.len() < 4 {
        return "application/octet-stream".to_string();
    }
    match &data[..4] {
        [0x89, b'P', b'N', b'G'] => "image/png".to_string(),
        [0xFF, 0xD8, 0xFF, _] => "image/jpeg".to_string(),
        [b'G', b'I', b'F', b'8'] => "image/gif".to_string(),
        [b'B', b'M', _, _] => "image/bmp".to_string(),
        _ => {
            if data.len() >= 12 && &data[0..4] == b"RIFF" && &data[8..12] == b"WEBP" {
                "image/webp".to_string()
            } else {
                "application/octet-stream".to_string()
            }
        }
    }
}

fn mime_to_ext(mime: &str) -> &'static str {
    match mime {
        "image/png" => "png",
        "image/jpeg" => "jpg",
        "image/gif" => "gif",
        "image/bmp" => "bmp",
        "image/webp" => "webp",
        _ => "bin",
    }
}

#[cfg(test)]
#[path = "convert_tests_control.rs"]
mod tests_control;

#[cfg(test)]
#[path = "convert_tests_detect.rs"]
mod tests_detect;

#[cfg(test)]
#[path = "convert_tests_ir.rs"]
mod tests_ir;

#[cfg(test)]
#[path = "convert_tests_build.rs"]
mod tests_build;