unhwp 0.5.1

A high-performance library for extracting HWP/HWPX documents into structured Markdown
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
//! Section parsing for HWPX documents.

use crate::error::Result;
use crate::model::{
    Block, Equation, ImageRef, InlineContent, Paragraph, ParagraphStyle, Section, StyleRegistry,
    Table, TableCell, TableRow, TextRun,
};
use quick_xml::events::Event;
use quick_xml::Reader;

/// Parses a section XML file.
pub fn parse_section(xml: &str, section_index: usize, styles: &StyleRegistry) -> Result<Section> {
    let mut section = Section::new(section_index);
    let mut parser = SectionParser::new(xml, styles);
    parser.parse(&mut section)?;
    Ok(section)
}

/// Extracted paragraph attributes from XML.
#[derive(Default)]
struct ParaAttrs {
    para_pr_id: Option<u32>,
    style_id: Option<u32>,
}

/// Extracted run attributes from XML.
#[derive(Default)]
struct RunAttrs {
    char_pr_id: Option<u32>,
}

/// Marker type for cell attributes (colspan/rowspan parsed from child elements).
#[derive(Default)]
struct CellAttrs;

/// Section parser state machine.
struct SectionParser<'a> {
    reader: Reader<&'a [u8]>,
    styles: &'a StyleRegistry,
}

impl<'a> SectionParser<'a> {
    fn new(xml: &'a str, styles: &'a StyleRegistry) -> Self {
        let mut reader = Reader::from_str(xml);
        // Keep text verbatim. `<hp:t>` content (the body text) is only captured
        // inside the element's Start/End (the `in_text_element` guard in
        // `parse_run`), so inter-element indentation whitespace is naturally
        // ignored, while meaningful leading/trailing spaces inside `<hp:t>`
        // (e.g. a TOC entry "1. ") are preserved. Trimming here would drop them
        // and glue adjacent runs together (`**1.**바코드`). The two capture sites
        // that are NOT `<hp:t>`-scoped (equation script, footnote text) trim
        // explicitly below.
        reader.config_mut().trim_text(false);

        Self { reader, styles }
    }

    fn parse(&mut self, section: &mut Section) -> Result<()> {
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    match name.as_str() {
                        "p" => {
                            let attrs = ParaAttrs {
                                para_pr_id: get_attr_u32(&e, "paraPrIDRef"),
                                style_id: get_attr_u32(&e, "styleIDRef"),
                            };
                            buf.clear();
                            let para = self.parse_paragraph(attrs, Some(section))?;
                            // Don't filter empty paragraphs here — let the renderer
                            // decide based on include_empty_paragraphs option.
                            // This matches HWP5 behavior for consistency.
                            section.content.push(Block::Paragraph(para));
                        }
                        "tbl" => {
                            buf.clear();
                            let table = self.parse_table()?;
                            section.content.push(Block::Table(table));
                        }
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(())
    }

    /// Parses a <hp:p> paragraph element.
    fn parse_paragraph(
        &mut self,
        attrs: ParaAttrs,
        section: Option<&mut Section>,
    ) -> Result<Paragraph> {
        // Build paragraph style from references
        let mut para_style = ParagraphStyle::default();

        if let Some(id) = attrs.para_pr_id {
            if let Some(style) = self.styles.get_para_style(id) {
                para_style = style.clone();
            }
        }

        if let Some(id) = attrs.style_id {
            if let Some(style) = self.styles.get_para_style(id) {
                if style.heading_level > 0 {
                    para_style.heading_level = style.heading_level;
                }
            }
        }

        let mut paragraph = Paragraph::with_style(para_style);
        let mut buf = Vec::new();

        // Collect tables found in runs (to add to section after paragraph)
        let mut tables_found: Vec<Table> = Vec::new();

        // Parse paragraph content
        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    match name.as_str() {
                        "run" => {
                            let run_attrs = RunAttrs {
                                char_pr_id: get_attr_u32(&e, "charPrIDRef"),
                            };
                            buf.clear();
                            let run =
                                self.parse_run(run_attrs, &mut paragraph, &mut tables_found)?;
                            if !run.text.is_empty() {
                                paragraph.content.push(InlineContent::Text(run));
                            }
                        }
                        "linesegarray" | "lineSeg" => {
                            // Line segment info - skip
                            buf.clear();
                            skip_element(&mut self.reader)?;
                        }
                        "ctrl" => {
                            // Control element (table, image, etc.)
                            buf.clear();
                            self.parse_control(&mut paragraph, &mut tables_found)?;
                        }
                        _ => {}
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "p" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        // Add any tables found to section
        if let Some(sec) = section {
            for table in tables_found {
                sec.content.push(Block::Table(table));
            }
        }

        Ok(paragraph)
    }

    /// Parses a <hp:run> text run element, returning the text run and any images found.
    fn parse_run(
        &mut self,
        attrs: RunAttrs,
        paragraph: &mut Paragraph,
        tables: &mut Vec<Table>,
    ) -> Result<TextRun> {
        let text_style = attrs
            .char_pr_id
            .and_then(|id| self.styles.get_char_style(id))
            .cloned()
            .unwrap_or_default();

        let mut text = String::new();
        let mut buf = Vec::new();
        let mut in_pic = false;
        let mut pic_floating = false; // Whether the current <hp:pic> floats over text
        let mut in_ctrl = false; // Track if we're inside a control element (to skip formula fields etc.)
        let mut in_text_element = false; // Track if we're inside <hp:t> element

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    if name == "t" {
                        // Text content element - mark we're inside <hp:t>
                        in_text_element = true;
                    } else if name == "ctrl" {
                        // Control element (fieldBegin, fieldEnd, etc.) - skip its content
                        in_ctrl = true;
                    } else if name == "pic" {
                        // Start of picture element
                        in_pic = true;
                        pic_floating = is_floating_pic(&e);
                    } else if in_pic && name == "img" {
                        // Look for binaryItemIDRef in <hc:img> element
                        if let Some(id) = get_attr_string(&e, "binaryItemIDRef") {
                            paragraph.content.push(InlineContent::Image(
                                ImageRef::new(id).floating(pic_floating),
                            ));
                        }
                    } else if name == "tbl" {
                        // Table inside run - parse and collect
                        buf.clear();
                        let table = self.parse_table()?;
                        tables.push(table);
                    }
                }
                Ok(Event::Empty(e)) => {
                    let name = get_local_name(&e);

                    if name == "t" {
                        // Empty text element - skip
                    } else if name == "tab" && !in_ctrl {
                        // <hp:tab/> is a layout tab (often a TOC leader between a title
                        // and its page number). Markdown has no tab concept, so emit a
                        // single space to preserve the word boundary instead of letting
                        // the surrounding text collapse together (e.g. `재고관리1`).
                        text.push(' ');
                    } else if in_pic && name == "img" {
                        // Look for binaryItemIDRef in <hc:img/> element
                        if let Some(id) = get_attr_string(&e, "binaryItemIDRef") {
                            paragraph.content.push(InlineContent::Image(
                                ImageRef::new(id).floating(pic_floating),
                            ));
                        }
                    }
                }
                Ok(Event::Text(t)) if in_text_element && !in_ctrl => {
                    // Only capture text inside <hp:t> elements, not inside control elements
                    if let Ok(s) = t.unescape() {
                        text.push_str(&s);
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "t" {
                        in_text_element = false;
                    } else if name == "ctrl" {
                        in_ctrl = false;
                    } else if name == "pic" {
                        in_pic = false;
                        pic_floating = false;
                    } else if name == "run" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(TextRun::with_style(text, text_style))
    }

    /// Parses a <hp:ctrl> control element.
    ///
    /// Handles various control types:
    /// - pic: Pictures/images
    /// - eqEdit: Equations (mathematical formulas)
    /// - fn: Footnotes
    /// - en: Endnotes
    /// - tbl: Tables
    fn parse_control(&mut self, paragraph: &mut Paragraph, tables: &mut Vec<Table>) -> Result<()> {
        let mut buf = Vec::new();
        let mut in_pic = false;
        let mut pic_floating = false;
        let mut in_equation = false;
        let mut in_footnote = false;
        let mut equation_script = String::new();
        let mut footnote_text = String::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    match name.as_str() {
                        "pic" => {
                            in_pic = true;
                            pic_floating = is_floating_pic(&e);
                        }
                        "eqEdit" | "equation" => in_equation = true,
                        "fn" | "footnote" => in_footnote = true,
                        "en" | "endnote" => in_footnote = true, // Treat endnotes like footnotes
                        "tbl" => {
                            // Table inside control - parse and collect
                            buf.clear();
                            let table = self.parse_table()?;
                            tables.push(table);
                        }
                        "img" if in_pic => {
                            // Look for binaryItemIDRef attribute in <hc:img> element
                            if let Some(id) = get_attr_string(&e, "binaryItemIDRef") {
                                paragraph.content.push(InlineContent::Image(
                                    ImageRef::new(id).floating(pic_floating),
                                ));
                            }
                        }
                        "script" if in_equation => {
                            // Equation script content will be in text node
                        }
                        "subList" if in_footnote => {
                            // Footnote content is in subList > p elements
                            buf.clear();
                            footnote_text = self.parse_footnote_content()?;
                        }
                        _ => {}
                    }
                }
                Ok(Event::Empty(e)) => {
                    let name = get_local_name(&e);

                    if in_pic && name == "img" {
                        // Look for binaryItemIDRef attribute in <hc:img/> element
                        if let Some(id) = get_attr_string(&e, "binaryItemIDRef") {
                            paragraph.content.push(InlineContent::Image(
                                ImageRef::new(id).floating(pic_floating),
                            ));
                        }
                    }
                }
                Ok(Event::Text(t)) if in_equation => {
                    // Collect equation script text
                    if let Ok(s) = t.unescape() {
                        equation_script.push_str(&s);
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    match name.as_str() {
                        "pic" => {
                            in_pic = false;
                            pic_floating = false;
                        }
                        "eqEdit" | "equation" => {
                            // Equation text is captured for the whole `in_equation`
                            // span, so with trim_text(false) it can pick up
                            // inter-element indentation; trim the assembled script.
                            let script = std::mem::take(&mut equation_script);
                            let script = script.trim();
                            if !script.is_empty() {
                                let eq = Equation::new(script.to_string());
                                paragraph.content.push(InlineContent::Equation(eq));
                            }
                            in_equation = false;
                        }
                        "fn" | "footnote" | "en" | "endnote" => {
                            if !footnote_text.is_empty() {
                                paragraph
                                    .content
                                    .push(InlineContent::Footnote(std::mem::take(
                                        &mut footnote_text,
                                    )));
                            }
                            in_footnote = false;
                        }
                        "ctrl" => break,
                        _ => {}
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(())
    }

    /// Parses footnote content from subList element.
    fn parse_footnote_content(&mut self) -> Result<String> {
        let mut text = String::new();
        let mut buf = Vec::new();
        let mut depth = 1;

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);
                    if name == "t" {
                        // Text element inside footnote paragraph
                    } else {
                        depth += 1;
                    }
                }
                Ok(Event::Text(t)) => {
                    if let Ok(s) = t.unescape() {
                        // This site is not `<hp:t>`-scoped, so with trim_text(false)
                        // it also receives inter-element indentation. Skip
                        // whitespace-only events; join real fragments with a single
                        // space (footnote paragraphs flatten to one line).
                        let trimmed = s.trim();
                        if !trimmed.is_empty() {
                            if !text.is_empty() && !text.ends_with(' ') {
                                text.push(' ');
                            }
                            text.push_str(trimmed);
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "subList" {
                        break;
                    }
                    depth -= 1;
                    if depth == 0 {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(text.trim().to_string())
    }

    /// Parses a <hp:tbl> table element.
    fn parse_table(&mut self) -> Result<Table> {
        let mut table = Table::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    if name == "tr" {
                        buf.clear();
                        let row = self.parse_table_row()?;
                        table.rows.push(row);
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "tbl" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        // Mark first row as header if it exists
        if !table.rows.is_empty() {
            table.has_header = true;
        }

        Ok(table)
    }

    /// Parses a <hp:tr> table row element.
    fn parse_table_row(&mut self) -> Result<TableRow> {
        let mut row = TableRow::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    if name == "tc" {
                        buf.clear();
                        let cell = self.parse_table_cell(CellAttrs)?;
                        row.cells.push(cell);
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "tr" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        Ok(row)
    }

    /// Parses a <hp:tc> table cell element.
    fn parse_table_cell(&mut self, _attrs: CellAttrs) -> Result<TableCell> {
        let mut rowspan: u32 = 1;
        let mut colspan: u32 = 1;
        let mut paragraphs: Vec<Paragraph> = Vec::new();
        let mut buf = Vec::new();

        loop {
            match self.reader.read_event_into(&mut buf) {
                Ok(Event::Start(e)) => {
                    let name = get_local_name(&e);

                    // Cell content is in subList > p
                    if name == "p" {
                        let para_attrs = ParaAttrs {
                            para_pr_id: get_attr_u32(&e, "paraPrIDRef"),
                            style_id: get_attr_u32(&e, "styleIDRef"),
                        };
                        buf.clear();
                        // Pass None for section since we're inside a table cell
                        let para = self.parse_paragraph(para_attrs, None)?;
                        // Don't filter empty paragraphs here — renderer handles it.
                        // This matches HWP5 cell parsing behavior.
                        paragraphs.push(para);
                    }
                }
                Ok(Event::Empty(e)) => {
                    let name = get_local_name(&e);

                    // cellSpan element contains colspan/rowspan as attributes
                    if name == "cellSpan" {
                        if let Some(cs) = get_attr_u32(&e, "colSpan") {
                            colspan = cs;
                        }
                        if let Some(rs) = get_attr_u32(&e, "rowSpan") {
                            rowspan = rs;
                        }
                    }
                }
                Ok(Event::End(e)) => {
                    let name = get_local_name_end(&e);
                    if name == "tc" {
                        break;
                    }
                }
                Ok(Event::Eof) => break,
                Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
                _ => {}
            }
            buf.clear();
        }

        let mut cell = TableCell::merged(rowspan, colspan);
        cell.content = paragraphs;
        Ok(cell)
    }
}

/// Gets the local name of an element (without namespace prefix).
fn get_local_name(e: &quick_xml::events::BytesStart) -> String {
    std::str::from_utf8(e.local_name().as_ref())
        .unwrap_or("")
        .to_string()
}

fn get_local_name_end(e: &quick_xml::events::BytesEnd) -> String {
    std::str::from_utf8(e.local_name().as_ref())
        .unwrap_or("")
        .to_string()
}

/// Gets a u32 attribute value.
fn get_attr_u32(e: &quick_xml::events::BytesStart, name: &str) -> Option<u32> {
    for attr in e.attributes().flatten() {
        if attr.key.as_ref() == name.as_bytes() {
            if let Ok(val) = std::str::from_utf8(&attr.value) {
                return val.parse().ok();
            }
        }
    }
    None
}

/// Gets a string attribute value.
fn get_attr_string(e: &quick_xml::events::BytesStart, name: &str) -> Option<String> {
    for attr in e.attributes().flatten() {
        if attr.key.as_ref() == name.as_bytes() {
            if let Ok(val) = std::str::from_utf8(&attr.value) {
                return Some(val.to_string());
            }
        }
    }
    None
}

/// Returns true if a `<hp:pic>` `textWrap` value denotes a floating object that
/// is layered over/under the text rather than embedded in the text flow.
///
/// `IN_FRONT_OF_TEXT`/`BEHIND_TEXT` are stamps, signatures, and watermarks that
/// must not glue to adjacent text. Other wraps (e.g. `SQUARE`, default) keep the
/// existing inline behaviour to avoid regressing embedded illustrations.
fn is_floating_pic(e: &quick_xml::events::BytesStart) -> bool {
    matches!(
        get_attr_string(e, "textWrap").as_deref(),
        Some("IN_FRONT_OF_TEXT") | Some("BEHIND_TEXT")
    )
}

/// Skips an element and all its children.
fn skip_element(reader: &mut Reader<&[u8]>) -> Result<()> {
    let mut depth = 1;
    let mut buf = Vec::new();

    loop {
        match reader.read_event_into(&mut buf) {
            Ok(Event::Start(_)) => depth += 1,
            Ok(Event::End(_)) => {
                depth -= 1;
                if depth == 0 {
                    break;
                }
            }
            Ok(Event::Eof) => break,
            Err(e) => return Err(crate::error::Error::XmlParse(e.to_string())),
            _ => {}
        }
        buf.clear();
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::model::InlineContent;

    /// Collects the text of every `InlineContent::Text` run in the first
    /// paragraph of a parsed section, preserving order.
    fn run_texts(xml: &str) -> Vec<String> {
        let styles = StyleRegistry::new();
        let section = parse_section(xml, 0, &styles).expect("section must parse");
        let para = section
            .content
            .iter()
            .find_map(|b| match b {
                Block::Paragraph(p) => Some(p),
                _ => None,
            })
            .expect("a paragraph");
        para.content
            .iter()
            .filter_map(|c| match c {
                InlineContent::Text(run) => Some(run.text.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn test_hp_t_trailing_space_preserved() {
        // `<hp:t>1. </hp:t>` followed by a plain run must keep the separating
        // space so the renderer emits `**1.** 바코드`, not `**1.**바코드`.
        // Regression for D8: trim_text(true) used to strip it.
        let xml = r#"<hs:sec xmlns:hp="x"><hp:p><hp:run><hp:t>1. </hp:t></hp:run><hp:run><hp:t>바코드</hp:t></hp:run></hp:p></hs:sec>"#;
        assert_eq!(
            run_texts(xml),
            vec!["1. ".to_string(), "바코드".to_string()]
        );
    }

    #[test]
    fn test_hp_t_leading_space_preserved() {
        // Leading whitespace inside <hp:t> is meaningful content and must
        // survive parsing.
        let xml = r#"<hs:sec xmlns:hp="x"><hp:p><hp:run><hp:t>가</hp:t></hp:run><hp:run><hp:t> 나</hp:t></hp:run></hp:p></hs:sec>"#;
        assert_eq!(run_texts(xml), vec!["".to_string(), "".to_string()]);
    }

    #[test]
    fn test_interelement_indentation_not_captured() {
        // Pretty-printed XML with newline+indent whitespace between elements
        // must NOT leak into run text — only `<hp:t>` content is captured.
        let xml = "<hs:sec xmlns:hp=\"x\">\n  <hp:p>\n    <hp:run>\n      <hp:t>foo</hp:t>\n    </hp:run>\n  </hp:p>\n</hs:sec>";
        assert_eq!(run_texts(xml), vec!["foo".to_string()]);
    }

    /// Collects equation scripts from the first paragraph of a parsed section.
    fn equation_scripts(xml: &str) -> Vec<String> {
        let styles = StyleRegistry::new();
        let section = parse_section(xml, 0, &styles).expect("section must parse");
        let para = section
            .content
            .iter()
            .find_map(|b| match b {
                Block::Paragraph(p) => Some(p),
                _ => None,
            })
            .expect("a paragraph");
        para.content
            .iter()
            .filter_map(|c| match c {
                InlineContent::Equation(e) => Some(e.script.clone()),
                _ => None,
            })
            .collect()
    }

    /// Collects footnote texts from the first paragraph of a parsed section.
    fn footnote_texts(xml: &str) -> Vec<String> {
        let styles = StyleRegistry::new();
        let section = parse_section(xml, 0, &styles).expect("section must parse");
        let para = section
            .content
            .iter()
            .find_map(|b| match b {
                Block::Paragraph(p) => Some(p),
                _ => None,
            })
            .expect("a paragraph");
        para.content
            .iter()
            .filter_map(|c| match c {
                InlineContent::Footnote(t) => Some(t.clone()),
                _ => None,
            })
            .collect()
    }

    #[test]
    fn test_equation_script_trimmed_under_no_trim_reader() {
        // With trim_text(false) the equation capture spans the whole eqEdit and
        // would otherwise swallow inter-element indentation ("\n  x + y\n").
        // The explicit trim must strip the surrounding whitespace while keeping
        // internal spacing.
        let xml = "<hs:sec xmlns:hp=\"x\"><hp:p><hp:ctrl><hp:equation>\n      <hp:script>x + y</hp:script>\n    </hp:equation></hp:ctrl></hp:p></hs:sec>";
        assert_eq!(equation_scripts(xml), vec!["x + y".to_string()]);
    }

    #[test]
    fn test_footnote_text_clean_under_no_trim_reader() {
        // Pretty-printed footnote subList: with trim_text(false) every newline+
        // indent is now a Text event. The whitespace-only-skip guard must drop
        // them, and real fragments across runs join with a single space.
        let xml = "<hs:sec xmlns:hp=\"x\"><hp:p><hp:ctrl><hp:fn>\n  <hp:subList>\n    <hp:p>\n      <hp:run><hp:t>각주</hp:t></hp:run>\n      <hp:run><hp:t>내용</hp:t></hp:run>\n    </hp:p>\n  </hp:subList>\n</hp:fn></hp:ctrl></hp:p></hs:sec>";
        assert_eq!(footnote_texts(xml), vec!["각주 내용".to_string()]);
    }

    #[test]
    fn test_whitespace_only_run_preserved_between_words() {
        // A run whose only content is a space (`<hp:t> </hp:t>`) is a real
        // inter-word space; it must not be dropped.
        let xml = r#"<hs:sec xmlns:hp="x"><hp:p><hp:run><hp:t>가</hp:t></hp:run><hp:run><hp:t> </hp:t></hp:run><hp:run><hp:t>나</hp:t></hp:run></hp:p></hs:sec>"#;
        assert_eq!(
            run_texts(xml),
            vec!["".to_string(), " ".to_string(), "".to_string()]
        );
    }
}