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}
197
198/// A note call inside a text item ([`TreeItem::notes`]).
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct TreeNote {
201    /// The call's position, in chars into the item's `text`.
202    pub offset: usize,
203    /// The note's plain text.
204    pub text: String,
205}
206
207impl ItemTree {
208    /// Where each note call of one paragraph lands (#538): `full_text` is the
209    /// paragraph's text, `offsets` the calls' positions in it (chars), and
210    /// the paragraph's items are those created from `first_new` on. Each text
211    /// item is a trimmed slice of the paragraph (a formatting run, a link, or
212    /// the whole heading / list item), matched in order; a call inside an
213    /// item lands there, one between items ends the earlier (or starts the
214    /// first). When no item matches, the call ends the paragraph's last text
215    /// item; with no text item at all it is `None`.
216    pub fn place_note_calls(
217        &self,
218        first_new: usize,
219        full_text: &str,
220        offsets: &[usize],
221    ) -> Vec<Option<(usize, usize)>> {
222        let texts: Vec<(usize, &str)> = (first_new..self.items.len())
223            .filter(|&i| !self.items[i].deleted)
224            .filter_map(|i| match &self.items[i].kind {
225                TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => {
226                    Some((i, text.as_str()))
227                }
228                _ => None,
229            })
230            .collect();
231        // Each found item's (id, start, end) in chars of `full_text`.
232        let mut spans: Vec<(usize, usize, usize)> = Vec::new();
233        let mut cursor = 0usize; // bytes
234        for &(item, text) in &texts {
235            if text.is_empty() {
236                continue;
237            }
238            if let Some(pos) = full_text[cursor..].find(text) {
239                let start_b = cursor + pos;
240                let start = full_text[..start_b].chars().count();
241                spans.push((item, start, start + text.chars().count()));
242                cursor = start_b + text.len();
243            }
244        }
245        offsets
246            .iter()
247            .map(|&offset| {
248                spans
249                    .iter()
250                    .find(|&&(_, start, end)| offset >= start && offset <= end)
251                    .map(|&(item, start, _)| (item, offset - start))
252                    .or_else(
253                        || match spans.iter().rev().find(|&&(_, _, end)| end <= offset) {
254                            Some(&(item, start, end)) => Some((item, end - start)),
255                            None => spans.first().map(|&(item, _, _)| (item, 0)),
256                        },
257                    )
258                    .or_else(|| {
259                        texts
260                            .last()
261                            .map(|&(item, text)| (item, text.chars().count()))
262                    })
263            })
264            .collect()
265    }
266}
267
268/// docling's item tree in creation order (see the [module docs](self)).
269#[derive(Debug, Clone, PartialEq, Default)]
270pub struct ItemTree {
271    /// Every item, indexed by creation order — which is how docling numbers
272    /// `#/texts/N`, `#/groups/N`, … within each bucket.
273    pub items: Vec<TreeItem>,
274    /// The body's `children`, as item indices.
275    pub body: Vec<usize>,
276}
277
278impl ItemTree {
279    /// Append an item under `parent` (`None` = body) on `layer`, registering
280    /// it as its parent's last child — docling's `add_*` calls do exactly that.
281    pub fn add(
282        &mut self,
283        parent: Option<usize>,
284        layer: Option<ContentLayer>,
285        kind: TreeKind,
286    ) -> usize {
287        let id = self.items.len();
288        self.items.push(TreeItem {
289            parent,
290            children: Vec::new(),
291            layer,
292            kind,
293            prov: None,
294            comments: Vec::new(),
295            source: None,
296            deleted: false,
297            notes: Vec::new(),
298            note_body: false,
299        });
300        match parent {
301            Some(p) => self.items[p].children.push(id),
302            None => self.body.push(id),
303        }
304        id
305    }
306
307    /// [`add`](Self::add) with the item's provenance — docling's
308    /// `add_text(…, prov=prov)`.
309    pub fn add_with_prov(
310        &mut self,
311        parent: Option<usize>,
312        layer: Option<ContentLayer>,
313        kind: TreeKind,
314        prov: TreeProv,
315    ) -> usize {
316        let id = self.add(parent, layer, kind);
317        self.items[id].prov = Some(prov);
318        id
319    }
320
321    /// Append every item of `other` after this tree's, renumbering its
322    /// indices (parents, children, comments, table/picture caption and
323    /// rich-cell refs) and adding its body children to this body — so a
324    /// backend can build independent fragments in parallel (one per PPTX
325    /// slide) and still hand the export one tree in creation order, exactly
326    /// as if it had been built sequentially.
327    pub fn append(&mut self, other: ItemTree) {
328        let off = self.items.len();
329        let shift = |i: usize| i + off;
330        for mut item in other.items {
331            item.parent = item.parent.map(shift);
332            for c in item.children.iter_mut().chain(item.comments.iter_mut()) {
333                *c = shift(*c);
334            }
335            match &mut item.kind {
336                TreeKind::Table {
337                    rich_cells,
338                    captions,
339                    ..
340                } => {
341                    for (_, _, g) in rich_cells.iter_mut() {
342                        *g = shift(*g);
343                    }
344                    for c in captions.iter_mut() {
345                        *c = shift(*c);
346                    }
347                }
348                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
349                    for c in captions.iter_mut() {
350                        *c = shift(*c);
351                    }
352                }
353                _ => {}
354            }
355            self.items.push(item);
356        }
357        self.body.extend(other.body.into_iter().map(shift));
358    }
359
360    /// Move `id` under `new_parent`, dropping it from its current parent's
361    /// children and appending it to the new one's — docling's
362    /// `group_cell_elements` re-parenting of a rich cell's items.
363    pub fn reparent(&mut self, id: usize, new_parent: Option<usize>) {
364        let old = self.items[id].parent;
365        let siblings = match old {
366            Some(p) => &mut self.items[p].children,
367            None => &mut self.body,
368        };
369        siblings.retain(|&c| c != id);
370        self.items[id].parent = new_parent;
371        match new_parent {
372            Some(p) => self.items[p].children.push(id),
373            None => self.body.push(id),
374        }
375    }
376
377    /// Re-number the items in traversal order — a pre-order walk of the body
378    /// through every layer, which is how docling's
379    /// `DoclingDocument.concatenate` (and `_normalize_references`) re-creates
380    /// a document's items: a group created after the content it was later
381    /// wrapped around comes before that content afterwards. Items the walk
382    /// does not reach (deleted ones) are dropped. Returns each old id's new
383    /// id.
384    pub fn renumber_in_traversal_order(&mut self) -> Vec<Option<usize>> {
385        let mut order = Vec::with_capacity(self.items.len());
386        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
387        while let Some(id) = stack.pop() {
388            if self.items[id].deleted {
389                continue;
390            }
391            order.push(id);
392            stack.extend(self.items[id].children.iter().rev());
393        }
394        let mut new_of: Vec<Option<usize>> = vec![None; self.items.len()];
395        for (new, &old) in order.iter().enumerate() {
396            new_of[old] = Some(new);
397        }
398        let remap = |ids: &mut Vec<usize>| {
399            *ids = ids.iter().filter_map(|&i| new_of[i]).collect();
400        };
401        let mut old_items: Vec<Option<TreeItem>> = std::mem::take(&mut self.items)
402            .into_iter()
403            .map(Some)
404            .collect();
405        for &old in &order {
406            let mut item = old_items[old].take().expect("each item visited once");
407            item.parent = item.parent.and_then(|p| new_of[p]);
408            remap(&mut item.children);
409            remap(&mut item.comments);
410            match &mut item.kind {
411                TreeKind::Table {
412                    rich_cells,
413                    captions,
414                    ..
415                } => {
416                    rich_cells.retain_mut(|(_, _, g)| match new_of[*g] {
417                        Some(n) => {
418                            *g = n;
419                            true
420                        }
421                        None => false,
422                    });
423                    remap(captions);
424                }
425                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
426                    remap(captions)
427                }
428                _ => {}
429            }
430            self.items.push(item);
431        }
432        remap(&mut self.body);
433        new_of
434    }
435
436    /// Remove `id` from the tree — docling's `delete_items`, which the DOCX
437    /// backend uses to drop the empty text item a blank spacer paragraph left
438    /// between two items of a resumed list. The item leaves its parent's
439    /// children and is neither numbered nor written; its slot stays so the
440    /// indices held elsewhere stay valid.
441    pub fn delete(&mut self, id: usize) {
442        match self.items[id].parent {
443            Some(p) => self.items[p].children.retain(|&c| c != id),
444            None => self.body.retain(|&c| c != id),
445        }
446        self.items[id].deleted = true;
447    }
448
449    /// docling-core's `DoclingDocument.validate_misplaced_list_items` (a
450    /// model validator, so it runs whenever docling-core serializes or loads
451    /// a document): every `list_item` whose parent is not a `list` group is
452    /// re-homed into a new one. A pre-order walk of the body (groups
453    /// included) collects them; consecutive misplaced items directly on the
454    /// body share one group, any other misplaced item gets its own. Working
455    /// from the last run back, each run gets a `ListGroup` (name `group`)
456    /// inserted where its first item stood, the items are deleted and
457    /// re-added under the group as fresh items, so they move to the end of
458    /// the text numbering (#527: the DOCX backend leaves such items in rich
459    /// table cells). A no-op for a well-formed tree.
460    ///
461    /// One deliberate divergence (#586): docling-core deletes each item *with
462    /// its children* and re-adds it from its text alone, so a mixed-format
463    /// item — an empty `list_item` over an `inline` group of text runs —
464    /// comes back empty and its text is gone from the JSON (and from the
465    /// Markdown/HTML docling serializes after that validator ran; the JSON
466    /// docling saves *before* exporting still has it). Here the children
467    /// follow the item into the group: the structure docling-core requires,
468    /// the content the document had.
469    pub fn wrap_misplaced_list_items(&mut self) {
470        let is_list_item = |t: &Self, id: usize| matches!(&t.items[id].kind, TreeKind::Text { label, .. } if label == "list_item");
471        let in_list_group = |t: &Self, id: usize| {
472            t.items[id].parent.is_some_and(
473                |p| matches!(&t.items[p].kind, TreeKind::Group { label, .. } if label == "list"),
474            )
475        };
476        let mut runs: Vec<Vec<usize>> = Vec::new();
477        // `None` = the body itself, which the walk yields first.
478        let mut prev: Option<usize> = None;
479        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
480        while let Some(id) = stack.pop() {
481            if self.items[id].deleted {
482                continue;
483            }
484            if is_list_item(self, id) && !in_list_group(self, id) {
485                let continues =
486                    prev.is_some_and(|p| is_list_item(self, p) && self.items[p].parent.is_none());
487                match runs.last_mut() {
488                    Some(run) if continues => run.push(id),
489                    _ => runs.push(vec![id]),
490                }
491            }
492            prev = Some(id);
493            stack.extend(self.items[id].children.iter().rev().copied());
494        }
495        for run in runs.into_iter().rev() {
496            let parent = self.items[run[0]].parent;
497            let group = self.add(
498                parent,
499                None,
500                TreeKind::Group {
501                    label: "list".into(),
502                    name: "group".into(),
503                },
504            );
505            let siblings = match parent {
506                Some(p) => &mut self.items[p].children,
507                None => &mut self.body,
508            };
509            siblings.pop();
510            let at = siblings
511                .iter()
512                .position(|&c| c == run[0])
513                .unwrap_or(siblings.len());
514            siblings.insert(at, group);
515            for &li in &run {
516                // Not `delete_subtree`: the children move to the copy (#586).
517                self.delete(li);
518            }
519            // `add_list_item` keeps the text, marker, formatting, hyperlink
520            // and first provenance — not comments or a source. The children
521            // (the inline group of a mixed-format item) are carried over.
522            for &li in &run {
523                let children = std::mem::take(&mut self.items[li].children);
524                let copy = TreeItem {
525                    parent: Some(group),
526                    children: children.clone(),
527                    comments: Vec::new(),
528                    source: None,
529                    deleted: false,
530                    ..self.items[li].clone()
531                };
532                let id = self.items.len();
533                self.items.push(copy);
534                for c in children {
535                    self.items[c].parent = Some(id);
536                }
537                self.items[group].children.push(id);
538            }
539        }
540    }
541
542    /// The last live text-bucket item (docling's `doc.texts[-1]`).
543    pub fn last_text(&self) -> Option<usize> {
544        self.items.iter().rposition(|it| {
545            !it.deleted && matches!(it.kind, TreeKind::Text { .. } | TreeKind::Code { .. })
546        })
547    }
548
549    /// How many items of a bucket precede `id` — its `#/{bucket}/N` index.
550    pub fn bucket_index(&self, id: usize) -> usize {
551        let same = |k: &TreeKind| {
552            std::mem::discriminant(k) == std::mem::discriminant(&self.items[id].kind)
553                || matches!(
554                    (k, &self.items[id].kind),
555                    (TreeKind::Text { .. }, TreeKind::Code { .. })
556                        | (TreeKind::Code { .. }, TreeKind::Text { .. })
557                )
558        };
559        self.items[..id]
560            .iter()
561            .filter(|it| !it.deleted && same(&it.kind))
562            .count()
563    }
564
565    /// The number of tables created so far (docling's `len(doc.tables)`).
566    pub fn table_count(&self) -> usize {
567        self.items
568            .iter()
569            .filter(|it| !it.deleted && matches!(it.kind, TreeKind::Table { .. }))
570            .count()
571    }
572}
573
574#[cfg(test)]
575mod tests {
576    use super::*;
577
578    fn text(t: &str) -> TreeKind {
579        TreeKind::Text {
580            label: "text".into(),
581            text: t.into(),
582            orig: None,
583            formatting: None,
584            hyperlink: None,
585            level: None,
586            list: None,
587        }
588    }
589
590    /// `add` registers the item as its parent's (or the body's) last child;
591    /// `reparent` moves it — a rich cell's items leave the heading they were
592    /// created under for the table's group.
593    #[test]
594    fn add_and_reparent_keep_docling_children_order() {
595        let mut t = ItemTree::default();
596        let title = t.add(None, None, text("Title"));
597        let a = t.add(Some(title), None, text("a"));
598        let b = t.add(Some(title), None, text("b"));
599        let table = t.add(
600            Some(title),
601            None,
602            TreeKind::Table {
603                table: Table::default(),
604                rich_cells: Vec::new(),
605                captions: Vec::new(),
606            },
607        );
608        let group = t.add(
609            Some(table),
610            None,
611            TreeKind::Group {
612                label: "unspecified".into(),
613                name: "rich_cell_group_1_0_0".into(),
614            },
615        );
616        assert_eq!(t.body, vec![title]);
617        assert_eq!(t.items[title].children, vec![a, b, table]);
618        t.reparent(a, Some(group));
619        assert_eq!(t.items[title].children, vec![b, table]);
620        assert_eq!(t.items[group].children, vec![a]);
621        assert_eq!(t.items[a].parent, Some(group));
622        assert_eq!(t.table_count(), 1);
623        // Text and code share the `texts` bucket.
624        let code = t.add(
625            None,
626            None,
627            TreeKind::Code {
628                text: "x".into(),
629                orig: None,
630                language: None,
631                formatting: None,
632                hyperlink: None,
633                captions: Vec::new(),
634            },
635        );
636        assert_eq!(t.bucket_index(code), 3, "title, a, b precede it in `texts`");
637        assert_eq!(t.bucket_index(group), 0);
638        assert_eq!(t.body, vec![title, code]);
639    }
640
641    /// `append` renumbers a fragment built on its own (a slide converted in
642    /// parallel) so the merged tree reads as if built in one pass: parents,
643    /// children, comment back-refs and caption refs all shift together.
644    #[test]
645    fn append_renumbers_a_fragment_into_creation_order() {
646        let mut whole = ItemTree::default();
647        let slide0 = whole.add(
648            None,
649            None,
650            TreeKind::Group {
651                label: "chapter".into(),
652                name: "slide-0".into(),
653            },
654        );
655        whole.add(Some(slide0), None, text("first"));
656
657        let mut frag = ItemTree::default();
658        let slide1 = frag.add(
659            None,
660            None,
661            TreeKind::Group {
662                label: "chapter".into(),
663                name: "slide-1".into(),
664            },
665        );
666        let cap = frag.add_with_prov(
667            Some(slide1),
668            None,
669            TreeKind::Text {
670                label: "caption".into(),
671                text: "Title".into(),
672                orig: None,
673                formatting: None,
674                hyperlink: None,
675                level: None,
676                list: None,
677            },
678            TreeProv {
679                page_no: 2,
680                bbox: [1.0, 2.0, 3.0, 4.0],
681                bottom_left: true,
682                charspan: [0, 5],
683            },
684        );
685        let pic = frag.add(
686            Some(slide1),
687            None,
688            TreeKind::Picture {
689                captions: vec![cap],
690                image: None,
691                extra_classes: Vec::new(),
692                classification: Some("bar_chart".into()),
693                description: None,
694                confidence: None,
695                chart: None,
696                dpi: None,
697            },
698        );
699        let note = frag.add(
700            None,
701            Some(ContentLayer::Notes),
702            TreeKind::Group {
703                label: "comment_section".into(),
704                name: "comment-slide2-1".into(),
705            },
706        );
707        frag.items[pic].comments.push(note);
708
709        whole.append(frag);
710        assert_eq!(whole.body, vec![slide0, 2, 5]);
711        assert_eq!(whole.items[2].children, vec![3, 4]);
712        assert_eq!(whole.items[3].parent, Some(2));
713        assert_eq!(whole.items[3].prov.as_ref().map(|p| p.page_no), Some(2));
714        assert!(
715            matches!(&whole.items[4].kind, TreeKind::Picture { captions, .. } if captions == &[3])
716        );
717        assert_eq!(whole.items[4].comments, vec![5]);
718        assert_eq!(whole.items[5].parent, None);
719        assert_eq!(
720            whole.bucket_index(4),
721            0,
722            "the fragment's picture is #/pictures/0"
723        );
724        assert_eq!(
725            whole.bucket_index(5),
726            2,
727            "slide-0, slide-1 precede it in `groups`"
728        );
729    }
730
731    /// `renumber_in_traversal_order`: docling's `concatenate` re-creates the
732    /// items as a pre-order walk meets them, so a group created after the
733    /// content it was wrapped around (a rich cell's group) comes first, and a
734    /// deleted item disappears; every cross-reference follows.
735    #[test]
736    fn renumbering_follows_the_traversal() {
737        let mut t = ItemTree::default();
738        let a = t.add(None, None, text("a"));
739        let table = t.add(
740            None,
741            None,
742            TreeKind::Table {
743                table: Table::default(),
744                rich_cells: Vec::new(),
745                captions: Vec::new(),
746            },
747        );
748        let cell_text = t.add(None, None, text("cell"));
749        let group = t.add(
750            Some(table),
751            None,
752            TreeKind::Group {
753                label: "unspecified".into(),
754                name: "rich_cell_group_1_0_0".into(),
755            },
756        );
757        t.reparent(cell_text, Some(group));
758        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
759            rich_cells.push((0, 0, group));
760        }
761        let gone = t.add(None, None, text("gone"));
762        t.delete(gone);
763        let z = t.add(None, None, text("z"));
764
765        let new_of = t.renumber_in_traversal_order();
766        assert_eq!(
767            new_of,
768            vec![Some(0), Some(1), Some(3), Some(2), None, Some(4)]
769        );
770        assert_eq!(t.items.len(), 5);
771        assert_eq!(t.body, vec![0, 1, 4]);
772        assert_eq!(t.items[1].children, vec![2], "the group follows its table");
773        assert_eq!(t.items[2].parent, Some(1));
774        assert_eq!(
775            t.items[3].parent,
776            Some(2),
777            "the cell text follows its group"
778        );
779        assert!(matches!(&t.items[3].kind, TreeKind::Text { text, .. } if text == "cell"));
780        assert!(
781            matches!(&t.items[1].kind, TreeKind::Table { rich_cells, .. } if rich_cells == &[(0, 0, 2)])
782        );
783        let _ = (a, z);
784    }
785
786    /// #586: a misplaced `list_item` keeps its children when it is re-homed.
787    /// docling-core's `validate_misplaced_list_items` re-adds the item from
788    /// its text alone, so a mixed-format item (empty `list_item` over an
789    /// `inline` group of runs) lost every run — a DOCX table cell whose list
790    /// paragraph followed a `numId 0` spacer came out as an empty bullet in
791    /// the JSON and the HTML. The group goes where the item stood, the copy
792    /// is numbered last, the inline group and its texts move under it.
793    #[test]
794    fn wrapping_a_misplaced_list_item_keeps_its_runs() {
795        let mut t = ItemTree::default();
796        let cell = t.add(
797            None,
798            None,
799            TreeKind::Group {
800                label: "unspecified".into(),
801                name: "rich_cell_group_1_0_1".into(),
802            },
803        );
804        let before = t.add(Some(cell), None, text("before"));
805        let item = t.add(
806            Some(cell),
807            None,
808            TreeKind::Text {
809                label: "list_item".into(),
810                text: String::new(),
811                orig: None,
812                formatting: None,
813                hyperlink: None,
814                level: None,
815                list: Some(ListMeta {
816                    enumerated: false,
817                    marker: String::new(),
818                }),
819            },
820        );
821        let inline = t.add(
822            Some(item),
823            None,
824            TreeKind::Group {
825                label: "inline".into(),
826                name: "group".into(),
827            },
828        );
829        let run_a = t.add(Some(inline), None, text("Second item text"));
830        let run_b = t.add(Some(inline), None, text("[Optional]"));
831        let after = t.add(Some(cell), None, text("after"));
832
833        t.wrap_misplaced_list_items();
834
835        let group = t.items[cell].children[1];
836        assert_eq!(t.items[cell].children, vec![before, group, after]);
837        assert!(
838            matches!(&t.items[group].kind, TreeKind::Group { label, name } if label == "list" && name == "group")
839        );
840        assert!(t.items[item].deleted, "the original item is deleted");
841        let copy = t.items[group].children[0];
842        assert_ne!(copy, item);
843        assert!(
844            copy > after,
845            "the copy is numbered after every existing item"
846        );
847        assert_eq!(t.items[copy].children, vec![inline]);
848        assert_eq!(t.items[inline].parent, Some(copy));
849        assert_eq!(t.items[inline].children, vec![run_a, run_b]);
850        for id in [inline, run_a, run_b] {
851            assert!(!t.items[id].deleted, "item {id} must survive the re-homing");
852        }
853    }
854}