Skip to main content

deepdoc_core/extract/ooxml/
docx.rs

1//! Word (`.docx`) extractor.
2//!
3//! What is read: paragraph styles (`Heading1`…`Heading9`, `Title`, plus
4//! `outlineLvl` as a fallback) become headings, numbered paragraphs (`numPr`)
5//! become nested lists with the ordered/bullet choice taken from
6//! `numbering.xml`, `w:tbl` becomes a table, runs carry bold and italic, and
7//! hyperlinks resolve through the part's relationships.
8
9use std::collections::HashMap;
10use std::path::Path;
11
12use crate::detect::{Format, Sniff};
13use crate::error::{Error, Result};
14use crate::extract::container::Container;
15use crate::extract::ooxml::{relationships, toggle};
16use crate::extract::xml::{self, Element};
17use crate::extract::{ExtractOpts, Extractor};
18use crate::model::{Block, Document, Inline, Row, Span};
19
20pub struct DocxExtractor;
21
22impl Extractor for DocxExtractor {
23    fn name(&self) -> &'static str {
24        "docx"
25    }
26
27    fn supports(&self, _path: &Path, sniff: &Sniff) -> bool {
28        crate::detect::detect(sniff) == Some(Format::Docx)
29    }
30
31    fn extract(&self, path: &Path, _opts: &ExtractOpts) -> Result<Document> {
32        let mut container = Container::open(path)?;
33
34        let document = container
35            .read("word/document.xml")
36            .map_err(|message| Error::parse(path, message))?;
37        let numbering = container.read_optional("word/numbering.xml");
38        let rels = container.read_optional("word/_rels/document.xml.rels");
39
40        let blocks = parse(&document, numbering.as_deref(), rels.as_deref())
41            .map_err(|message| Error::parse(path, message))?;
42
43        let mut meta = super::core_properties(&mut container);
44        meta.source_format = Some(Format::Docx);
45        meta.source_path = Some(path.display().to_string());
46
47        Ok(Document { meta, blocks })
48    }
49}
50
51/// Parse `word/document.xml` into blocks. Pure.
52pub fn parse(
53    document: &str,
54    numbering: Option<&str>,
55    rels: Option<&str>,
56) -> std::result::Result<Vec<Block>, String> {
57    let root = xml::parse(document)?;
58    let body = root.child("body").unwrap_or(&root);
59    let context = Context {
60        numbering: NumberingTable::parse(numbering),
61        links: relationships(rels),
62    };
63
64    Ok(context.blocks(body))
65}
66
67struct Context {
68    numbering: NumberingTable,
69    links: HashMap<String, String>,
70}
71
72/// A paragraph that belongs to a list, before nesting is worked out.
73struct ListItem {
74    level: u8,
75    ordered: bool,
76    blocks: Vec<Block>,
77}
78
79impl Context {
80    /// Walk a block container (the body, or a table cell).
81    fn blocks(&self, container: &Element) -> Vec<Block> {
82        let mut blocks = Vec::new();
83        let mut pending: Vec<ListItem> = Vec::new();
84
85        for child in container.elements() {
86            match child.name.as_str() {
87                "p" => match self.list_item(child) {
88                    Some(item) => pending.push(item),
89                    None => {
90                        flush_list(&mut pending, &mut blocks);
91                        blocks.extend(self.paragraph(child));
92                    }
93                },
94                "tbl" => {
95                    flush_list(&mut pending, &mut blocks);
96                    if let Some(table) = self.table(child) {
97                        blocks.push(table);
98                    }
99                }
100                // sectPr, bookmarks, proofing marks and the like carry no text.
101                _ => {}
102            }
103        }
104
105        flush_list(&mut pending, &mut blocks);
106        blocks
107    }
108
109    /// A numbered or bulleted paragraph, if this paragraph is one.
110    fn list_item(&self, paragraph: &Element) -> Option<ListItem> {
111        let properties = paragraph.child("pPr")?;
112        let numbering = properties.child("numPr")?;
113
114        let level = numbering
115            .child("ilvl")
116            .and_then(|ilvl| ilvl.attr_number("val"))
117            .unwrap_or(0)
118            .clamp(0, 8) as u8;
119        let id = numbering
120            .child("numId")
121            .and_then(|num| num.attr_number("val"))
122            .unwrap_or(0);
123
124        Some(ListItem {
125            level,
126            ordered: self.numbering.is_ordered(id, level),
127            blocks: self.paragraph(paragraph),
128        })
129    }
130
131    /// A paragraph becomes a heading or a paragraph, plus any images in it.
132    fn paragraph(&self, paragraph: &Element) -> Vec<Block> {
133        let (inline, images) = self.inline(paragraph);
134
135        let mut blocks = Vec::new();
136        if !inline.plain_text().trim().is_empty() {
137            blocks.push(match heading_level(paragraph) {
138                Some(level) => Block::Heading {
139                    level,
140                    text: inline,
141                },
142                None => Block::Paragraph { text: inline },
143            });
144        }
145        blocks.extend(images);
146        blocks
147    }
148
149    /// Collect the inline content of a paragraph, and any images alongside it.
150    fn inline(&self, paragraph: &Element) -> (Inline, Vec<Block>) {
151        let mut spans = Vec::new();
152        let mut images = Vec::new();
153        self.walk_inline(paragraph, &mut spans, &mut images);
154        (Inline::new(spans), images)
155    }
156
157    fn walk_inline(&self, element: &Element, spans: &mut Vec<Span>, images: &mut Vec<Block>) {
158        for child in element.elements() {
159            match child.name.as_str() {
160                "r" => self.run(child, spans, images),
161                "hyperlink" => {
162                    let mut inner = Vec::new();
163                    self.walk_inline(child, &mut inner, images);
164                    match child.attr("id").and_then(|id| self.links.get(id)) {
165                        Some(href) if !inner.is_empty() => spans.push(Span::Link {
166                            href: href.clone(),
167                            text: inner,
168                        }),
169                        // An internal anchor has no URL worth keeping.
170                        _ => spans.extend(inner),
171                    }
172                }
173                // Content controls, revisions and smart tags wrap runs.
174                "sdt" | "sdtContent" | "ins" | "smartTag" | "bookmarkStart" | "fldSimple" => {
175                    self.walk_inline(child, spans, images);
176                }
177                // Deleted text must not come back.
178                "del" => {}
179                _ => {}
180            }
181        }
182    }
183
184    fn run(&self, run: &Element, spans: &mut Vec<Span>, images: &mut Vec<Block>) {
185        let properties = run.child("rPr");
186        let bold = toggle(properties.and_then(|p| p.child("b")));
187        let italic = toggle(properties.and_then(|p| p.child("i")));
188
189        let mut inner = Vec::new();
190        for child in run.elements() {
191            match child.name.as_str() {
192                "t" => {
193                    let text = child.text();
194                    if !text.is_empty() {
195                        inner.push(Span::Text(text));
196                    }
197                }
198                "br" | "cr" => inner.push(Span::LineBreak),
199                "tab" => inner.push(Span::Text("\t".into())),
200                "noBreakHyphen" => inner.push(Span::Text("-".into())),
201                "drawing" | "pict" | "object" => {
202                    if let Some(image) = image_block(child) {
203                        images.push(image);
204                    }
205                }
206                _ => {}
207            }
208        }
209
210        if inner.is_empty() {
211            return;
212        }
213        spans.push(match (bold, italic) {
214            (false, false) => {
215                spans.extend(inner);
216                return;
217            }
218            (true, false) => Span::Bold(inner),
219            (false, true) => Span::Italic(inner),
220            (true, true) => Span::Bold(vec![Span::Italic(inner)]),
221        });
222    }
223
224    fn table(&self, table: &Element) -> Option<Block> {
225        let mut rows: Vec<Row> = Vec::new();
226
227        for row in table.find_all("tr") {
228            let cells: Vec<Inline> = row
229                .find_all("tc")
230                .into_iter()
231                .map(|cell| {
232                    // A cell holds blocks; a Markdown cell holds one line.
233                    let text = self
234                        .blocks(cell)
235                        .iter()
236                        .map(Block::plain_text)
237                        .collect::<Vec<_>>()
238                        .join(" ");
239                    Inline::text(text.trim())
240                })
241                .collect();
242            if !cells.is_empty() {
243                rows.push(Row::new(cells));
244            }
245        }
246
247        if rows.is_empty() {
248            return None;
249        }
250        // Word documents put the header first; there is no reliable marker for
251        // it, and a Markdown table needs one.
252        let header = rows.remove(0);
253        Some(Block::Table {
254            header: Some(header),
255            rows,
256        })
257    }
258}
259
260/// Turn the collected list paragraphs into nested list blocks.
261fn flush_list(pending: &mut Vec<ListItem>, blocks: &mut Vec<Block>) {
262    if pending.is_empty() {
263        return;
264    }
265    let items = std::mem::take(pending);
266    blocks.push(nest(&items));
267}
268
269/// Build a list from a flat run of items carrying their indent level.
270fn nest(items: &[ListItem]) -> Block {
271    let base = items[0].level;
272    let ordered = items[0].ordered;
273    let mut list_items: Vec<Vec<Block>> = Vec::new();
274
275    let mut index = 0;
276    while index < items.len() {
277        let mut blocks = items[index].blocks.clone();
278
279        // Everything deeper than this item belongs inside it.
280        let children_start = index + 1;
281        let mut children_end = children_start;
282        while children_end < items.len() && items[children_end].level > base {
283            children_end += 1;
284        }
285        if children_end > children_start {
286            blocks.push(nest(&items[children_start..children_end]));
287        }
288
289        list_items.push(blocks);
290        index = children_end;
291    }
292
293    Block::List {
294        ordered,
295        items: list_items,
296    }
297}
298
299/// `Heading2` → 2, `Title` → 1, `outlineLvl 0` → 1.
300fn heading_level(paragraph: &Element) -> Option<u8> {
301    let properties = paragraph.child("pPr")?;
302
303    if let Some(style) = properties.child("pStyle").and_then(|s| s.attr("val")) {
304        let lowered = style.to_ascii_lowercase();
305        if let Some(rest) = lowered.strip_prefix("heading")
306            && let Ok(level) = rest.trim_start_matches('-').parse::<u8>()
307            && level >= 1
308        {
309            return Some(level.min(6));
310        }
311        match lowered.as_str() {
312            "title" => return Some(1),
313            "subtitle" => return Some(2),
314            _ => {}
315        }
316    }
317
318    let outline = properties.child("outlineLvl")?.attr_number("val")?;
319    (0..=8)
320        .contains(&outline)
321        .then(|| (outline as u8 + 1).min(6))
322}
323
324/// A drawing's alt text, from `wp:docPr`.
325fn image_block(drawing: &Element) -> Option<Block> {
326    let properties = drawing.find("docPr")?;
327    let alt = properties
328        .attr("descr")
329        .or_else(|| properties.attr("name"))
330        .map(str::trim)
331        .filter(|alt| !alt.is_empty())
332        .map(str::to_string);
333    Some(Block::Image { alt })
334}
335
336/// Which `numId`/level combinations are ordered rather than bulleted.
337#[derive(Default)]
338struct NumberingTable {
339    /// (numId, level) → ordered
340    formats: HashMap<(i64, u8), bool>,
341}
342
343impl NumberingTable {
344    fn parse(source: Option<&str>) -> NumberingTable {
345        let Some(root) = source.and_then(|source| xml::parse(source).ok()) else {
346            return NumberingTable::default();
347        };
348
349        // abstractNumId → level → ordered
350        let mut abstracts: HashMap<i64, HashMap<u8, bool>> = HashMap::new();
351        for definition in root.find_all("abstractNum") {
352            let Some(id) = definition.attr_number("abstractNumId") else {
353                continue;
354            };
355            let levels = abstracts.entry(id).or_default();
356            for level in definition.find_all("lvl") {
357                let index = level.attr_number("ilvl").unwrap_or(0).clamp(0, 8) as u8;
358                let format = level
359                    .child("numFmt")
360                    .and_then(|fmt| fmt.attr("val"))
361                    .unwrap_or("bullet");
362                levels.insert(index, format != "bullet" && format != "none");
363            }
364        }
365
366        let mut formats = HashMap::new();
367        for num in root.find_all("num") {
368            let Some(id) = num.attr_number("numId") else {
369                continue;
370            };
371            let Some(abstract_id) = num
372                .child("abstractNumId")
373                .and_then(|element| element.attr_number("val"))
374            else {
375                continue;
376            };
377            if let Some(levels) = abstracts.get(&abstract_id) {
378                for (level, ordered) in levels {
379                    formats.insert((id, *level), *ordered);
380                }
381            }
382        }
383
384        NumberingTable { formats }
385    }
386
387    /// Bulleted unless the numbering table says otherwise — a missing or
388    /// unreadable `numbering.xml` should not invent numbers.
389    fn is_ordered(&self, id: i64, level: u8) -> bool {
390        self.formats.get(&(id, level)).copied().unwrap_or(false)
391    }
392}
393
394#[cfg(test)]
395mod tests {
396    use super::*;
397    use crate::model::Metadata;
398    use crate::render::{RenderOpts, to_markdown};
399
400    fn document(body: &str) -> String {
401        format!(r#"<w:document xmlns:w="w"><w:body>{body}</w:body></w:document>"#)
402    }
403
404    fn blocks(body: &str) -> Vec<Block> {
405        parse(&document(body), None, None).expect("valid docx xml")
406    }
407
408    fn markdown(blocks: Vec<Block>) -> String {
409        to_markdown(
410            &Document {
411                meta: Metadata::default(),
412                blocks,
413            },
414            &RenderOpts::default(),
415        )
416    }
417
418    const NUMBERING: &str = r#"<w:numbering xmlns:w="w">
419        <w:abstractNum w:abstractNumId="0">
420          <w:lvl w:ilvl="0"><w:numFmt w:val="bullet"/></w:lvl>
421          <w:lvl w:ilvl="1"><w:numFmt w:val="decimal"/></w:lvl>
422        </w:abstractNum>
423        <w:num w:numId="1"><w:abstractNumId w:val="0"/></w:num>
424      </w:numbering>"#;
425
426    #[test]
427    fn paragraph_styles_become_headings() {
428        assert_eq!(
429            blocks(
430                r#"<w:p><w:pPr><w:pStyle w:val="Heading2"/></w:pPr><w:r><w:t>Summary</w:t></w:r></w:p>
431                   <w:p><w:pPr><w:pStyle w:val="Title"/></w:pPr><w:r><w:t>Report</w:t></w:r></w:p>
432                   <w:p><w:r><w:t>Body text.</w:t></w:r></w:p>"#
433            ),
434            vec![
435                Block::Heading {
436                    level: 2,
437                    text: Inline::text("Summary")
438                },
439                Block::Heading {
440                    level: 1,
441                    text: Inline::text("Report")
442                },
443                Block::paragraph("Body text."),
444            ]
445        );
446    }
447
448    #[test]
449    fn outline_level_is_the_heading_fallback() {
450        assert_eq!(
451            blocks(
452                r#"<w:p><w:pPr><w:outlineLvl w:val="1"/></w:pPr><w:r><w:t>Deep</w:t></w:r></w:p>"#
453            ),
454            vec![Block::Heading {
455                level: 2,
456                text: Inline::text("Deep")
457            }]
458        );
459    }
460
461    #[test]
462    fn runs_carry_bold_and_italic() {
463        let Block::Paragraph { text } = &blocks(
464            r#"<w:p>
465                 <w:r><w:t xml:space="preserve">plain </w:t></w:r>
466                 <w:r><w:rPr><w:b/></w:rPr><w:t>bold</w:t></w:r>
467                 <w:r><w:rPr><w:i/><w:b w:val="0"/></w:rPr><w:t xml:space="preserve"> italic</w:t></w:r>
468               </w:p>"#,
469        )[0] else {
470            panic!("expected a paragraph");
471        };
472        assert_eq!(
473            text.spans,
474            vec![
475                Span::Text("plain ".into()),
476                Span::Bold(vec![Span::Text("bold".into())]),
477                Span::Italic(vec![Span::Text(" italic".into())]),
478            ]
479        );
480    }
481
482    #[test]
483    fn line_breaks_and_tabs_survive_a_run() {
484        let Block::Paragraph { text } =
485            &blocks(r#"<w:p><w:r><w:t>a</w:t><w:br/><w:tab/><w:t>b</w:t></w:r></w:p>"#)[0]
486        else {
487            panic!("expected a paragraph");
488        };
489        assert_eq!(
490            text.spans,
491            vec![
492                Span::Text("a".into()),
493                Span::LineBreak,
494                Span::Text("\t".into()),
495                Span::Text("b".into()),
496            ]
497        );
498    }
499
500    #[test]
501    fn hyperlinks_resolve_through_the_relationships_part() {
502        let rels = r#"<Relationships><Relationship Id="rId4" Target="https://example.com"/></Relationships>"#;
503        let parsed = parse(
504            &document(
505                r#"<w:p><w:hyperlink r:id="rId4"><w:r><w:t>site</w:t></w:r></w:hyperlink></w:p>"#,
506            ),
507            None,
508            Some(rels),
509        )
510        .unwrap();
511
512        let Block::Paragraph { text } = &parsed[0] else {
513            panic!("expected a paragraph");
514        };
515        assert_eq!(
516            text.spans,
517            vec![Span::Link {
518                href: "https://example.com".into(),
519                text: vec![Span::Text("site".into())],
520            }]
521        );
522    }
523
524    #[test]
525    fn an_unresolved_hyperlink_keeps_its_text() {
526        let Block::Paragraph { text } = &blocks(
527            r#"<w:p><w:hyperlink w:anchor="top"><w:r><w:t>jump</w:t></w:r></w:hyperlink></w:p>"#,
528        )[0] else {
529            panic!("expected a paragraph");
530        };
531        assert_eq!(text.spans, vec![Span::Text("jump".into())]);
532    }
533
534    #[test]
535    fn deleted_text_stays_deleted() {
536        assert_eq!(
537            blocks(
538                r#"<w:p><w:r><w:t>kept</w:t></w:r><w:del><w:r><w:delText>gone</w:delText></w:r></w:del></w:p>"#
539            ),
540            vec![Block::paragraph("kept")]
541        );
542    }
543
544    #[test]
545    fn numbered_paragraphs_become_nested_lists() {
546        let parsed = parse(
547            &document(
548                r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>one</w:t></w:r></w:p>
549                   <w:p><w:pPr><w:numPr><w:ilvl w:val="1"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>inner</w:t></w:r></w:p>
550                   <w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>two</w:t></w:r></w:p>
551                   <w:p><w:r><w:t>after</w:t></w:r></w:p>"#,
552            ),
553            Some(NUMBERING),
554            None,
555        )
556        .unwrap();
557
558        assert_eq!(
559            parsed,
560            vec![
561                Block::List {
562                    ordered: false,
563                    items: vec![
564                        vec![
565                            Block::paragraph("one"),
566                            // Level 1 of this numbering is decimal, not a bullet.
567                            Block::List {
568                                ordered: true,
569                                items: vec![vec![Block::paragraph("inner")]],
570                            },
571                        ],
572                        vec![Block::paragraph("two")],
573                    ],
574                },
575                Block::paragraph("after"),
576            ]
577        );
578    }
579
580    #[test]
581    fn lists_are_bulleted_without_a_numbering_part() {
582        let parsed = blocks(
583            r#"<w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="3"/></w:numPr></w:pPr><w:r><w:t>item</w:t></w:r></w:p>"#,
584        );
585        assert_eq!(
586            parsed,
587            vec![Block::List {
588                ordered: false,
589                items: vec![vec![Block::paragraph("item")]],
590            }]
591        );
592    }
593
594    #[test]
595    fn tables_use_the_first_row_as_the_header() {
596        assert_eq!(
597            blocks(
598                r#"<w:tbl>
599                     <w:tr><w:tc><w:p><w:r><w:t>Segment</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>Q1</w:t></w:r></w:p></w:tc></w:tr>
600                     <w:tr><w:tc><w:p><w:r><w:t>Cloud</w:t></w:r></w:p></w:tc><w:tc><w:p><w:r><w:t>4.1</w:t></w:r></w:p></w:tc></w:tr>
601                   </w:tbl>"#
602            ),
603            vec![Block::Table {
604                header: Some(Row::from_texts(["Segment", "Q1"])),
605                rows: vec![Row::from_texts(["Cloud", "4.1"])],
606            }]
607        );
608    }
609
610    #[test]
611    fn images_keep_their_alt_text() {
612        assert_eq!(
613            blocks(
614                r#"<w:p><w:r><w:drawing><wp:inline><wp:docPr id="1" name="Picture 1" descr="a chart"/></wp:inline></w:drawing></w:r></w:p>"#
615            ),
616            vec![Block::Image {
617                alt: Some("a chart".into())
618            }]
619        );
620    }
621
622    #[test]
623    fn renders_a_small_document() {
624        let parsed = parse(
625            &document(
626                r#"<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:t>Report</w:t></w:r></w:p>
627                   <w:p><w:r><w:t xml:space="preserve">Revenue grew </w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>12%</w:t></w:r><w:r><w:t>.</w:t></w:r></w:p>
628                   <w:p><w:pPr><w:numPr><w:ilvl w:val="0"/><w:numId w:val="1"/></w:numPr></w:pPr><w:r><w:t>Cloud</w:t></w:r></w:p>"#,
629            ),
630            Some(NUMBERING),
631            None,
632        )
633        .unwrap();
634
635        assert_eq!(
636            markdown(parsed),
637            "# Report\n\nRevenue grew **12%**.\n\n- Cloud\n"
638        );
639    }
640
641    #[test]
642    fn a_document_without_a_body_is_not_an_error() {
643        assert!(
644            parse(r#"<w:document xmlns:w="w"/>"#, None, None)
645                .unwrap()
646                .is_empty()
647        );
648    }
649}