Skip to main content

docling_core/
tree.rs

1//! docling's **item tree**, for a backend that knows the exact shape upstream
2//! gives a document and wants the JSON export to reproduce it.
3//!
4//! [`DoclingDocument::nodes`](crate::DoclingDocument::nodes) is a flat,
5//! reading-order stream tuned for Markdown / DocLang / LaTeX; the JSON export
6//! rebuilds docling's parent/child structure from it with generic rules (runs
7//! of list items become list groups, a heading is a flat sibling of the text
8//! that follows it). Upstream's backends do not all agree on that structure:
9//! the HTML backend nests everything after a heading *under* the heading,
10//! splits a paragraph of mixed formatting into an `inline` group of one text
11//! item per formatting run, parents a rich table cell's content to a group
12//! under the table, keeps site chrome on the `furniture` layer… and numbers
13//! every item in the order it *creates* them. A backend that ports those
14//! rules call-for-call (HTML's `html_tree.rs`, DOCX's `docx_tree.rs`) records
15//! the result here — an arena of items in
16//! creation order, each with its parent and children — and the JSON export
17//! ([`DoclingDocument::export_to_json`](crate::DoclingDocument::export_to_json))
18//! serializes this tree instead of deriving one from the nodes. Every other
19//! serializer keeps reading the flat nodes, so their output is unaffected.
20
21use crate::{ContentLayer, FieldItem, PictureImage, Script, Table};
22
23/// docling-core's `Formatting`: the inline styles an item carries in JSON.
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
25pub struct Formatting {
26    pub bold: bool,
27    pub italic: bool,
28    pub underline: bool,
29    pub strikethrough: bool,
30    pub script: Script,
31}
32
33/// A `list_item`'s docling fields.
34#[derive(Debug, Clone, PartialEq, Eq, Default)]
35pub struct ListMeta {
36    pub enumerated: bool,
37    /// docling's `marker` — the HTML backend writes `""` unless an ordered
38    /// list carries an explicit `start`, then `"{n}."`.
39    pub marker: String,
40}
41
42/// What an item in the tree is. Mirrors the docling-core item classes the
43/// JSON `texts` / `groups` / `tables` / `pictures` / `field_regions` buckets
44/// hold.
45#[derive(Debug, Clone, PartialEq)]
46pub enum TreeKind {
47    /// A `TextItem` / `TitleItem` / `SectionHeaderItem` / `ListItem`, told
48    /// apart by `label` (`text`, `title`, `section_header`, `list_item`,
49    /// `caption`, `checkbox_selected`, `checkbox_unselected`, …).
50    Text {
51        label: String,
52        text: String,
53        /// docling's `orig` when it differs from `text` (the heading text
54        /// before unicode cleanup, say); `None` = same as `text`.
55        orig: Option<String>,
56        formatting: Option<Formatting>,
57        hyperlink: Option<String>,
58        /// `section_header` only: docling's heading level.
59        level: Option<u8>,
60        /// `list_item` only.
61        list: Option<ListMeta>,
62    },
63    /// A `CodeItem`.
64    Code {
65        text: String,
66        orig: Option<String>,
67        /// The language hint (a highlighter class token such as `python`),
68        /// mapped onto docling's `CodeLanguageLabel` at export; `None` →
69        /// `unknown`.
70        language: Option<String>,
71        formatting: Option<Formatting>,
72        hyperlink: Option<String>,
73        /// Caption text items in the tree — docling's `add_code(caption=…)`
74        /// (an AsciiDoc block title in front of a literal block).
75        captions: Vec<usize>,
76    },
77    /// A `GroupItem`: `label` is docling's `GroupLabel` value (`inline`,
78    /// `list`, `section`, `unspecified`, …), `name` its name (`group`, `list`,
79    /// `ordered list`, `header-2`, `rich_cell_group_1_0_3`, …).
80    Group { label: String, name: String },
81    /// A `TableItem`. `rich_cells` marks the cells docling serialized as a
82    /// `RichTableCell`: `(row, col)` grid anchor → the group item (a child of
83    /// the table) that holds the cell's content. `captions` are caption text
84    /// items in the tree.
85    Table {
86        table: Table,
87        rich_cells: Vec<(usize, usize, usize)>,
88        captions: Vec<usize>,
89    },
90    /// A `PictureItem`, its caption text items and optional payload.
91    /// `classification` is a `PictureClassificationLabel` value written as
92    /// the picture's `meta.classification` (an HTML `<stamp>` / `<signature>`).
93    Picture {
94        captions: Vec<usize>,
95        image: Option<PictureImage>,
96        classification: Option<String>,
97        /// Further predictions after `classification`, in order: the other
98        /// plot types of a PPTX combination chart (docling#4773).
99        extra_classes: Vec<String>,
100        /// The picture-OCR enrichment's text (#645), serialized like the flat
101        /// node's: `meta.description` + the `description` annotation.
102        description: Option<crate::PictureDescription>,
103        /// The prediction's `confidence`, when the backend writes one: the
104        /// DocLang deserializer stamps `1.0`; the office and HTML backends
105        /// leave it out (`None`).
106        confidence: Option<f64>,
107        /// A native chart's data grid (docling's `meta.tabular_chart.chart_data`,
108        /// the series reconstructed as a `TableData`), for a DOCX chart drawing.
109        chart: Option<Table>,
110        /// The `ImageRef.dpi` docling writes for `image` when the backend
111        /// read one from the file (python-pptx's `Image.dpi`: PIL's `dpi`
112        /// info, rounded, 72 when absent or out of 1–2048); `None` → 72,
113        /// which is what upstream's other office backends pass.
114        dpi: Option<u32>,
115    },
116    /// A form key-value region (`field_regions` / `field_items`).
117    FieldRegion { items: Vec<FieldItem> },
118    /// A `KeyValueItem` (`key_value_items`): docling's `GraphData` of key and
119    /// value cells and their links, written verbatim.
120    KeyValueGraph {
121        cells: Vec<crate::GraphCell>,
122        links: Vec<crate::GraphLink>,
123    },
124}
125
126/// docling's `ProvenanceItem` for a tree item, written verbatim: the
127/// backend's own geometry in the page's units — a PPTX shape's EMU box,
128/// whose `pages` entry is the slide size in EMU — rather than the 0–511
129/// DocLang grid the flat [`Node::Located`](crate::Node::Located) carries
130/// (which cannot round-trip those integers).
131#[derive(Debug, Clone, PartialEq)]
132pub struct TreeProv {
133    /// 1-based page (slide) number.
134    pub page_no: usize,
135    /// `[l, t, r, b]`, exactly as docling computed them.
136    pub bbox: [f64; 4],
137    /// docling's `coord_origin` tag. The office backends tag their
138    /// top-left-based boxes `TOPLEFT` (the PPTX backend since docling#4294 —
139    /// it used to tag them `BOTTOMLEFT`, which read the tuple as `(l, b, r,
140    /// t)` and swapped the vertical edges); a backend that really works in a
141    /// bottom-left space sets this.
142    pub bottom_left: bool,
143    /// `[0, len(text)]` in characters for a text item, `[0, 0]` for a table
144    /// or picture.
145    pub charspan: [usize; 2],
146}
147
148/// docling's `TrackSource` — where in a time-based track (a WebVTT cue) a
149/// text item came from. Written as the item's `source: [{"kind": "track", …}]`.
150#[derive(Debug, Clone, PartialEq)]
151pub struct TreeTrack {
152    /// The cue's start offset in seconds (docling's `WebVTTTimestamp.seconds`:
153    /// `h*3600 + m*60 + s + millis/1000.0`, so the float is bit-identical).
154    pub start_time: f64,
155    /// The cue's end offset in seconds.
156    pub end_time: f64,
157    /// The cue identifier line, when the cue has one.
158    pub identifier: Option<String>,
159    /// The `<v …>` voice annotation the text sits in, when any.
160    pub voice: Option<String>,
161}
162
163/// One item of an [`ItemTree`].
164#[derive(Debug, Clone, PartialEq)]
165pub struct TreeItem {
166    /// The parent item's index; `None` = the document body.
167    pub parent: Option<usize>,
168    /// Child item indices, in docling's `children` order.
169    pub children: Vec<usize>,
170    /// The content layer; `None` = `body`.
171    pub layer: Option<ContentLayer>,
172    pub kind: TreeKind,
173    /// The item's `prov` entry, when the backend has page geometry for it
174    /// (`None` → `prov: []`, what the HTML and DOCX backends write).
175    pub prov: Option<TreeProv>,
176    /// docling's `DocItem.comments`: the `comment_section` groups (or note
177    /// text items) annotating this item, as item indices — written after
178    /// `prov` when non-empty.
179    pub comments: Vec<usize>,
180    /// docling's `DocItem.source`: the track segment a text item was taken
181    /// from (WebVTT cues) — written after `prov` when set.
182    pub source: Option<TreeTrack>,
183    /// Removed by [`ItemTree::delete`] (docling's `delete_items`): the slot
184    /// stays so every other index keeps its meaning, but the item is not
185    /// numbered or written.
186    pub deleted: bool,
187    /// Footnotes / endnotes referenced from inside this text item (#538): the
188    /// note call's position (chars into the item's text) and the note's text.
189    /// docling keeps notes as unlinked furniture `footnote` items, so the
190    /// JSON never shows this; the Pandoc AST writes each as a `Note` there.
191    pub notes: Vec<TreeNote>,
192    /// This furniture `footnote` item is the body of a note some text item
193    /// calls (it travels in that item's [`Self::notes`]); the Pandoc AST then
194    /// leaves it out as a standalone block.
195    pub note_body: bool,
196    /// Link destinations at this item (#849): the identifiers a document's
197    /// internal links (`hyperlink: "#id"`) point at — a DOCX bookmark in
198    /// a heading, say. docling's model has no slot for them, so the JSON
199    /// shows them only on the Pandoc path (`_anchors`), where a heading's
200    /// first one is its `Header` id and the rest empty `Span .anchor`s.
201    pub anchors: Vec<String>,
202    /// The generated numbering `text` opens with, when the backend put one
203    /// there (#850: a DOCX heading numbered through `w:numPr` is docling's
204    /// `1.2 Title`): `"1.2"` — the authored text follows it after one
205    /// space. docling's JSON keeps the numbered text; the Pandoc AST writes
206    /// the authored text alone (`_number` on that path), since Pandoc
207    /// numbers sections itself (`--number-sections`) and its docx reader
208    /// never writes the number into the `Header`.
209    pub number: Option<String>,
210    /// The tracked change this run carries under
211    /// [`TrackChanges::All`](crate::TrackChanges::All) (#851): the Pandoc
212    /// AST wraps the run in `Span .insertion` / `.deletion` (`_revision`
213    /// on that path); docling's JSON has no field for it.
214    pub revision: Option<crate::Revision>,
215}
216
217/// A note call inside a text item ([`TreeItem::notes`]).
218#[derive(Debug, Clone, PartialEq, Eq)]
219pub struct TreeNote {
220    /// The call's position, in chars into the item's `text`.
221    pub offset: usize,
222    /// The note's plain text.
223    pub text: String,
224}
225
226impl ItemTree {
227    /// Where each note call of one paragraph lands (#538): `full_text` is the
228    /// paragraph's text, `offsets` the calls' positions in it (chars), and
229    /// the paragraph's items are those created from `first_new` on. Each text
230    /// item is a trimmed slice of the paragraph (a formatting run, a link, or
231    /// the whole heading / list item), matched in order; a call inside an
232    /// item lands there, one between items ends the earlier (or starts the
233    /// first). When no item matches, the call ends the paragraph's last text
234    /// item; with no text item at all it is `None`.
235    pub fn place_note_calls(
236        &self,
237        first_new: usize,
238        full_text: &str,
239        offsets: &[usize],
240    ) -> Vec<Option<(usize, usize)>> {
241        let texts: Vec<(usize, &str)> = (first_new..self.items.len())
242            .filter(|&i| !self.items[i].deleted)
243            .filter_map(|i| match &self.items[i].kind {
244                TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => {
245                    Some((i, text.as_str()))
246                }
247                _ => None,
248            })
249            .collect();
250        // Each found item's (id, start, end) in chars of `full_text`.
251        let mut spans: Vec<(usize, usize, usize)> = Vec::new();
252        let mut cursor = 0usize; // bytes
253        for &(item, text) in &texts {
254            if text.is_empty() {
255                continue;
256            }
257            if let Some(pos) = full_text[cursor..].find(text) {
258                let start_b = cursor + pos;
259                let start = full_text[..start_b].chars().count();
260                spans.push((item, start, start + text.chars().count()));
261                cursor = start_b + text.len();
262            }
263        }
264        offsets
265            .iter()
266            .map(|&offset| {
267                spans
268                    .iter()
269                    .find(|&&(_, start, end)| offset >= start && offset <= end)
270                    .map(|&(item, start, _)| (item, offset - start))
271                    .or_else(
272                        || match spans.iter().rev().find(|&&(_, _, end)| end <= offset) {
273                            Some(&(item, start, end)) => Some((item, end - start)),
274                            None => spans.first().map(|&(item, _, _)| (item, 0)),
275                        },
276                    )
277                    .or_else(|| {
278                        texts
279                            .last()
280                            .map(|&(item, text)| (item, text.chars().count()))
281                    })
282            })
283            .collect()
284    }
285}
286
287/// docling's item tree in creation order (see the [module docs](self)).
288#[derive(Debug, Clone, PartialEq, Default)]
289pub struct ItemTree {
290    /// Every item, indexed by creation order — which is how docling numbers
291    /// `#/texts/N`, `#/groups/N`, … within each bucket.
292    pub items: Vec<TreeItem>,
293    /// The body's `children`, as item indices.
294    pub body: Vec<usize>,
295}
296
297impl ItemTree {
298    /// Append an item under `parent` (`None` = body) on `layer`, registering
299    /// it as its parent's last child — docling's `add_*` calls do exactly that.
300    pub fn add(
301        &mut self,
302        parent: Option<usize>,
303        layer: Option<ContentLayer>,
304        kind: TreeKind,
305    ) -> usize {
306        let id = self.items.len();
307        self.items.push(TreeItem {
308            parent,
309            children: Vec::new(),
310            layer,
311            kind,
312            prov: None,
313            comments: Vec::new(),
314            source: None,
315            deleted: false,
316            notes: Vec::new(),
317            note_body: false,
318            anchors: Vec::new(),
319            number: None,
320            revision: None,
321        });
322        match parent {
323            Some(p) => self.items[p].children.push(id),
324            None => self.body.push(id),
325        }
326        id
327    }
328
329    /// [`add`](Self::add) with the item's provenance — docling's
330    /// `add_text(…, prov=prov)`.
331    pub fn add_with_prov(
332        &mut self,
333        parent: Option<usize>,
334        layer: Option<ContentLayer>,
335        kind: TreeKind,
336        prov: TreeProv,
337    ) -> usize {
338        let id = self.add(parent, layer, kind);
339        self.items[id].prov = Some(prov);
340        id
341    }
342
343    /// Append every item of `other` after this tree's, renumbering its
344    /// indices (parents, children, comments, table/picture caption and
345    /// rich-cell refs) and adding its body children to this body — so a
346    /// backend can build independent fragments in parallel (one per PPTX
347    /// slide) and still hand the export one tree in creation order, exactly
348    /// as if it had been built sequentially.
349    pub fn append(&mut self, other: ItemTree) {
350        let off = self.items.len();
351        let shift = |i: usize| i + off;
352        for mut item in other.items {
353            item.parent = item.parent.map(shift);
354            for c in item.children.iter_mut().chain(item.comments.iter_mut()) {
355                *c = shift(*c);
356            }
357            match &mut item.kind {
358                TreeKind::Table {
359                    rich_cells,
360                    captions,
361                    ..
362                } => {
363                    for (_, _, g) in rich_cells.iter_mut() {
364                        *g = shift(*g);
365                    }
366                    for c in captions.iter_mut() {
367                        *c = shift(*c);
368                    }
369                }
370                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
371                    for c in captions.iter_mut() {
372                        *c = shift(*c);
373                    }
374                }
375                _ => {}
376            }
377            self.items.push(item);
378        }
379        self.body.extend(other.body.into_iter().map(shift));
380    }
381
382    /// Move `id` under `new_parent`, dropping it from its current parent's
383    /// children and appending it to the new one's — docling's
384    /// `group_cell_elements` re-parenting of a rich cell's items.
385    pub fn reparent(&mut self, id: usize, new_parent: Option<usize>) {
386        let old = self.items[id].parent;
387        let siblings = match old {
388            Some(p) => &mut self.items[p].children,
389            None => &mut self.body,
390        };
391        siblings.retain(|&c| c != id);
392        self.items[id].parent = new_parent;
393        match new_parent {
394            Some(p) => self.items[p].children.push(id),
395            None => self.body.push(id),
396        }
397    }
398
399    /// Re-number the items in traversal order — a pre-order walk of the body
400    /// through every layer, which is how docling's
401    /// `DoclingDocument.concatenate` (and `_normalize_references`) re-creates
402    /// a document's items: a group created after the content it was later
403    /// wrapped around comes before that content afterwards. Items the walk
404    /// does not reach (deleted ones) are dropped. Returns each old id's new
405    /// id.
406    pub fn renumber_in_traversal_order(&mut self) -> Vec<Option<usize>> {
407        let mut order = Vec::with_capacity(self.items.len());
408        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
409        while let Some(id) = stack.pop() {
410            if self.items[id].deleted {
411                continue;
412            }
413            order.push(id);
414            stack.extend(self.items[id].children.iter().rev());
415        }
416        let mut new_of: Vec<Option<usize>> = vec![None; self.items.len()];
417        for (new, &old) in order.iter().enumerate() {
418            new_of[old] = Some(new);
419        }
420        let remap = |ids: &mut Vec<usize>| {
421            *ids = ids.iter().filter_map(|&i| new_of[i]).collect();
422        };
423        let mut old_items: Vec<Option<TreeItem>> = std::mem::take(&mut self.items)
424            .into_iter()
425            .map(Some)
426            .collect();
427        for &old in &order {
428            let mut item = old_items[old].take().expect("each item visited once");
429            item.parent = item.parent.and_then(|p| new_of[p]);
430            remap(&mut item.children);
431            remap(&mut item.comments);
432            match &mut item.kind {
433                TreeKind::Table {
434                    rich_cells,
435                    captions,
436                    ..
437                } => {
438                    rich_cells.retain_mut(|(_, _, g)| match new_of[*g] {
439                        Some(n) => {
440                            *g = n;
441                            true
442                        }
443                        None => false,
444                    });
445                    remap(captions);
446                }
447                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
448                    remap(captions)
449                }
450                _ => {}
451            }
452            self.items.push(item);
453        }
454        remap(&mut self.body);
455        new_of
456    }
457
458    /// Remove `id` from the tree — docling's `delete_items`, which the DOCX
459    /// backend uses to drop the empty text item a blank spacer paragraph left
460    /// between two items of a resumed list. The item leaves its parent's
461    /// children and is neither numbered nor written; its slot stays so the
462    /// indices held elsewhere stay valid.
463    pub fn delete(&mut self, id: usize) {
464        match self.items[id].parent {
465            Some(p) => self.items[p].children.retain(|&c| c != id),
466            None => self.body.retain(|&c| c != id),
467        }
468        self.items[id].deleted = true;
469    }
470
471    /// docling-core's `DoclingDocument.validate_misplaced_list_items` (a
472    /// model validator, so it runs whenever docling-core serializes or loads
473    /// a document): every `list_item` whose parent is not a `list` group is
474    /// re-homed into a new one. A pre-order walk of the body (groups
475    /// included) collects them; consecutive misplaced items directly on the
476    /// body share one group, any other misplaced item gets its own. Working
477    /// from the last run back, each run gets a `ListGroup` (name `group`)
478    /// inserted where its first item stood, the items are deleted and
479    /// re-added under the group as fresh items, so they move to the end of
480    /// the text numbering (#527: the DOCX backend leaves such items in rich
481    /// table cells). A no-op for a well-formed tree.
482    ///
483    /// One deliberate divergence (#586): docling-core deletes each item *with
484    /// its children* and re-adds it from its text alone, so a mixed-format
485    /// item — an empty `list_item` over an `inline` group of text runs —
486    /// comes back empty and its text is gone from the JSON (and from the
487    /// Markdown/HTML docling serializes after that validator ran; the JSON
488    /// docling saves *before* exporting still has it). Here the children
489    /// follow the item into the group: the structure docling-core requires,
490    /// the content the document had.
491    pub fn wrap_misplaced_list_items(&mut self) {
492        let is_list_item = |t: &Self, id: usize| matches!(&t.items[id].kind, TreeKind::Text { label, .. } if label == "list_item");
493        let in_list_group = |t: &Self, id: usize| {
494            t.items[id].parent.is_some_and(
495                |p| matches!(&t.items[p].kind, TreeKind::Group { label, .. } if label == "list"),
496            )
497        };
498        let mut runs: Vec<Vec<usize>> = Vec::new();
499        // `None` = the body itself, which the walk yields first.
500        let mut prev: Option<usize> = None;
501        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
502        while let Some(id) = stack.pop() {
503            if self.items[id].deleted {
504                continue;
505            }
506            if is_list_item(self, id) && !in_list_group(self, id) {
507                let continues =
508                    prev.is_some_and(|p| is_list_item(self, p) && self.items[p].parent.is_none());
509                match runs.last_mut() {
510                    Some(run) if continues => run.push(id),
511                    _ => runs.push(vec![id]),
512                }
513            }
514            prev = Some(id);
515            stack.extend(self.items[id].children.iter().rev().copied());
516        }
517        for run in runs.into_iter().rev() {
518            let parent = self.items[run[0]].parent;
519            let group = self.add(
520                parent,
521                None,
522                TreeKind::Group {
523                    label: "list".into(),
524                    name: "group".into(),
525                },
526            );
527            let siblings = match parent {
528                Some(p) => &mut self.items[p].children,
529                None => &mut self.body,
530            };
531            siblings.pop();
532            let at = siblings
533                .iter()
534                .position(|&c| c == run[0])
535                .unwrap_or(siblings.len());
536            siblings.insert(at, group);
537            for &li in &run {
538                // Not `delete_subtree`: the children move to the copy (#586).
539                self.delete(li);
540            }
541            // `add_list_item` keeps the text, marker, formatting, hyperlink
542            // and first provenance — not comments or a source. The children
543            // (the inline group of a mixed-format item) are carried over.
544            for &li in &run {
545                let children = std::mem::take(&mut self.items[li].children);
546                let copy = TreeItem {
547                    parent: Some(group),
548                    children: children.clone(),
549                    comments: Vec::new(),
550                    source: None,
551                    deleted: false,
552                    ..self.items[li].clone()
553                };
554                let id = self.items.len();
555                self.items.push(copy);
556                for c in children {
557                    self.items[c].parent = Some(id);
558                }
559                self.items[group].children.push(id);
560            }
561        }
562    }
563
564    /// The last live text-bucket item (docling's `doc.texts[-1]`).
565    pub fn last_text(&self) -> Option<usize> {
566        self.items.iter().rposition(|it| {
567            !it.deleted && matches!(it.kind, TreeKind::Text { .. } | TreeKind::Code { .. })
568        })
569    }
570
571    /// How many items of a bucket precede `id` — its `#/{bucket}/N` index.
572    pub fn bucket_index(&self, id: usize) -> usize {
573        let same = |k: &TreeKind| {
574            std::mem::discriminant(k) == std::mem::discriminant(&self.items[id].kind)
575                || matches!(
576                    (k, &self.items[id].kind),
577                    (TreeKind::Text { .. }, TreeKind::Code { .. })
578                        | (TreeKind::Code { .. }, TreeKind::Text { .. })
579                )
580        };
581        self.items[..id]
582            .iter()
583            .filter(|it| !it.deleted && same(&it.kind))
584            .count()
585    }
586
587    /// The number of tables created so far (docling's `len(doc.tables)`).
588    pub fn table_count(&self) -> usize {
589        self.items
590            .iter()
591            .filter(|it| !it.deleted && matches!(it.kind, TreeKind::Table { .. }))
592            .count()
593    }
594}
595
596#[cfg(test)]
597mod tests {
598    use super::*;
599
600    fn text(t: &str) -> TreeKind {
601        TreeKind::Text {
602            label: "text".into(),
603            text: t.into(),
604            orig: None,
605            formatting: None,
606            hyperlink: None,
607            level: None,
608            list: None,
609        }
610    }
611
612    /// `add` registers the item as its parent's (or the body's) last child;
613    /// `reparent` moves it — a rich cell's items leave the heading they were
614    /// created under for the table's group.
615    #[test]
616    fn add_and_reparent_keep_docling_children_order() {
617        let mut t = ItemTree::default();
618        let title = t.add(None, None, text("Title"));
619        let a = t.add(Some(title), None, text("a"));
620        let b = t.add(Some(title), None, text("b"));
621        let table = t.add(
622            Some(title),
623            None,
624            TreeKind::Table {
625                table: Table::default(),
626                rich_cells: Vec::new(),
627                captions: Vec::new(),
628            },
629        );
630        let group = t.add(
631            Some(table),
632            None,
633            TreeKind::Group {
634                label: "unspecified".into(),
635                name: "rich_cell_group_1_0_0".into(),
636            },
637        );
638        assert_eq!(t.body, vec![title]);
639        assert_eq!(t.items[title].children, vec![a, b, table]);
640        t.reparent(a, Some(group));
641        assert_eq!(t.items[title].children, vec![b, table]);
642        assert_eq!(t.items[group].children, vec![a]);
643        assert_eq!(t.items[a].parent, Some(group));
644        assert_eq!(t.table_count(), 1);
645        // Text and code share the `texts` bucket.
646        let code = t.add(
647            None,
648            None,
649            TreeKind::Code {
650                text: "x".into(),
651                orig: None,
652                language: None,
653                formatting: None,
654                hyperlink: None,
655                captions: Vec::new(),
656            },
657        );
658        assert_eq!(t.bucket_index(code), 3, "title, a, b precede it in `texts`");
659        assert_eq!(t.bucket_index(group), 0);
660        assert_eq!(t.body, vec![title, code]);
661    }
662
663    /// `append` renumbers a fragment built on its own (a slide converted in
664    /// parallel) so the merged tree reads as if built in one pass: parents,
665    /// children, comment back-refs and caption refs all shift together.
666    #[test]
667    fn append_renumbers_a_fragment_into_creation_order() {
668        let mut whole = ItemTree::default();
669        let slide0 = whole.add(
670            None,
671            None,
672            TreeKind::Group {
673                label: "chapter".into(),
674                name: "slide-0".into(),
675            },
676        );
677        whole.add(Some(slide0), None, text("first"));
678
679        let mut frag = ItemTree::default();
680        let slide1 = frag.add(
681            None,
682            None,
683            TreeKind::Group {
684                label: "chapter".into(),
685                name: "slide-1".into(),
686            },
687        );
688        let cap = frag.add_with_prov(
689            Some(slide1),
690            None,
691            TreeKind::Text {
692                label: "caption".into(),
693                text: "Title".into(),
694                orig: None,
695                formatting: None,
696                hyperlink: None,
697                level: None,
698                list: None,
699            },
700            TreeProv {
701                page_no: 2,
702                bbox: [1.0, 2.0, 3.0, 4.0],
703                bottom_left: true,
704                charspan: [0, 5],
705            },
706        );
707        let pic = frag.add(
708            Some(slide1),
709            None,
710            TreeKind::Picture {
711                captions: vec![cap],
712                image: None,
713                extra_classes: Vec::new(),
714                classification: Some("bar_chart".into()),
715                description: None,
716                confidence: None,
717                chart: None,
718                dpi: None,
719            },
720        );
721        let note = frag.add(
722            None,
723            Some(ContentLayer::Notes),
724            TreeKind::Group {
725                label: "comment_section".into(),
726                name: "comment-slide2-1".into(),
727            },
728        );
729        frag.items[pic].comments.push(note);
730
731        whole.append(frag);
732        assert_eq!(whole.body, vec![slide0, 2, 5]);
733        assert_eq!(whole.items[2].children, vec![3, 4]);
734        assert_eq!(whole.items[3].parent, Some(2));
735        assert_eq!(whole.items[3].prov.as_ref().map(|p| p.page_no), Some(2));
736        assert!(
737            matches!(&whole.items[4].kind, TreeKind::Picture { captions, .. } if captions == &[3])
738        );
739        assert_eq!(whole.items[4].comments, vec![5]);
740        assert_eq!(whole.items[5].parent, None);
741        assert_eq!(
742            whole.bucket_index(4),
743            0,
744            "the fragment's picture is #/pictures/0"
745        );
746        assert_eq!(
747            whole.bucket_index(5),
748            2,
749            "slide-0, slide-1 precede it in `groups`"
750        );
751    }
752
753    /// `renumber_in_traversal_order`: docling's `concatenate` re-creates the
754    /// items as a pre-order walk meets them, so a group created after the
755    /// content it was wrapped around (a rich cell's group) comes first, and a
756    /// deleted item disappears; every cross-reference follows.
757    #[test]
758    fn renumbering_follows_the_traversal() {
759        let mut t = ItemTree::default();
760        let a = t.add(None, None, text("a"));
761        let table = t.add(
762            None,
763            None,
764            TreeKind::Table {
765                table: Table::default(),
766                rich_cells: Vec::new(),
767                captions: Vec::new(),
768            },
769        );
770        let cell_text = t.add(None, None, text("cell"));
771        let group = t.add(
772            Some(table),
773            None,
774            TreeKind::Group {
775                label: "unspecified".into(),
776                name: "rich_cell_group_1_0_0".into(),
777            },
778        );
779        t.reparent(cell_text, Some(group));
780        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
781            rich_cells.push((0, 0, group));
782        }
783        let gone = t.add(None, None, text("gone"));
784        t.delete(gone);
785        let z = t.add(None, None, text("z"));
786
787        let new_of = t.renumber_in_traversal_order();
788        assert_eq!(
789            new_of,
790            vec![Some(0), Some(1), Some(3), Some(2), None, Some(4)]
791        );
792        assert_eq!(t.items.len(), 5);
793        assert_eq!(t.body, vec![0, 1, 4]);
794        assert_eq!(t.items[1].children, vec![2], "the group follows its table");
795        assert_eq!(t.items[2].parent, Some(1));
796        assert_eq!(
797            t.items[3].parent,
798            Some(2),
799            "the cell text follows its group"
800        );
801        assert!(matches!(&t.items[3].kind, TreeKind::Text { text, .. } if text == "cell"));
802        assert!(
803            matches!(&t.items[1].kind, TreeKind::Table { rich_cells, .. } if rich_cells == &[(0, 0, 2)])
804        );
805        let _ = (a, z);
806    }
807
808    /// #586: a misplaced `list_item` keeps its children when it is re-homed.
809    /// docling-core's `validate_misplaced_list_items` re-adds the item from
810    /// its text alone, so a mixed-format item (empty `list_item` over an
811    /// `inline` group of runs) lost every run — a DOCX table cell whose list
812    /// paragraph followed a `numId 0` spacer came out as an empty bullet in
813    /// the JSON and the HTML. The group goes where the item stood, the copy
814    /// is numbered last, the inline group and its texts move under it.
815    #[test]
816    fn wrapping_a_misplaced_list_item_keeps_its_runs() {
817        let mut t = ItemTree::default();
818        let cell = t.add(
819            None,
820            None,
821            TreeKind::Group {
822                label: "unspecified".into(),
823                name: "rich_cell_group_1_0_1".into(),
824            },
825        );
826        let before = t.add(Some(cell), None, text("before"));
827        let item = t.add(
828            Some(cell),
829            None,
830            TreeKind::Text {
831                label: "list_item".into(),
832                text: String::new(),
833                orig: None,
834                formatting: None,
835                hyperlink: None,
836                level: None,
837                list: Some(ListMeta {
838                    enumerated: false,
839                    marker: String::new(),
840                }),
841            },
842        );
843        let inline = t.add(
844            Some(item),
845            None,
846            TreeKind::Group {
847                label: "inline".into(),
848                name: "group".into(),
849            },
850        );
851        let run_a = t.add(Some(inline), None, text("Second item text"));
852        let run_b = t.add(Some(inline), None, text("[Optional]"));
853        let after = t.add(Some(cell), None, text("after"));
854
855        t.wrap_misplaced_list_items();
856
857        let group = t.items[cell].children[1];
858        assert_eq!(t.items[cell].children, vec![before, group, after]);
859        assert!(
860            matches!(&t.items[group].kind, TreeKind::Group { label, name } if label == "list" && name == "group")
861        );
862        assert!(t.items[item].deleted, "the original item is deleted");
863        let copy = t.items[group].children[0];
864        assert_ne!(copy, item);
865        assert!(
866            copy > after,
867            "the copy is numbered after every existing item"
868        );
869        assert_eq!(t.items[copy].children, vec![inline]);
870        assert_eq!(t.items[inline].parent, Some(copy));
871        assert_eq!(t.items[inline].children, vec![run_a, run_b]);
872        for id in [inline, run_a, run_b] {
873            assert!(!t.items[id].deleted, "item {id} must survive the re-homing");
874        }
875    }
876}