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; `footnotes` its `footnote` text items (children of
85    /// the table, docling's `TableItem.footnotes`, docling-core#675).
86    Table {
87        table: Table,
88        rich_cells: Vec<(usize, usize, usize)>,
89        captions: Vec<usize>,
90        footnotes: Vec<usize>,
91    },
92    /// A `PictureItem`, its caption text items and optional payload.
93    /// `classification` is a `PictureClassificationLabel` value written as
94    /// the picture's `meta.classification` (an HTML `<stamp>` / `<signature>`).
95    Picture {
96        captions: Vec<usize>,
97        image: Option<PictureImage>,
98        classification: Option<String>,
99        /// Further predictions after `classification`, in order: the other
100        /// plot types of a PPTX combination chart (docling#4773).
101        extra_classes: Vec<String>,
102        /// The picture-OCR enrichment's text (#645), serialized like the flat
103        /// node's: `meta.description` + the `description` annotation.
104        description: Option<crate::PictureDescription>,
105        /// The prediction's `confidence`, when the backend writes one: the
106        /// DocLang deserializer stamps `1.0`; the office and HTML backends
107        /// leave it out (`None`).
108        confidence: Option<f64>,
109        /// A native chart's data grid (docling's `meta.tabular_chart.chart_data`,
110        /// the series reconstructed as a `TableData`), for a DOCX chart drawing.
111        chart: Option<Table>,
112        /// The `ImageRef.dpi` docling writes for `image` when the backend
113        /// read one from the file (python-pptx's `Image.dpi`: PIL's `dpi`
114        /// info, rounded, 72 when absent or out of 1–2048); `None` → 72,
115        /// which is what upstream's other office backends pass.
116        dpi: Option<u32>,
117    },
118    /// A form key-value region (`field_regions` / `field_items`).
119    FieldRegion { items: Vec<FieldItem> },
120    /// A `KeyValueItem` (`key_value_items`): docling's `GraphData` of key and
121    /// value cells and their links, written verbatim.
122    KeyValueGraph {
123        cells: Vec<crate::GraphCell>,
124        links: Vec<crate::GraphLink>,
125    },
126}
127
128/// docling's `ProvenanceItem` for a tree item, written verbatim: the
129/// backend's own geometry in the page's units — a PPTX shape's EMU box,
130/// whose `pages` entry is the slide size in EMU — rather than the 0–511
131/// DocLang grid the flat [`Node::Located`](crate::Node::Located) carries
132/// (which cannot round-trip those integers).
133#[derive(Debug, Clone, PartialEq)]
134pub struct TreeProv {
135    /// 1-based page (slide) number.
136    pub page_no: usize,
137    /// `[l, t, r, b]`, exactly as docling computed them.
138    pub bbox: [f64; 4],
139    /// docling's `coord_origin` tag. The office backends tag their
140    /// top-left-based boxes `TOPLEFT` (the PPTX backend since docling#4294 —
141    /// it used to tag them `BOTTOMLEFT`, which read the tuple as `(l, b, r,
142    /// t)` and swapped the vertical edges); a backend that really works in a
143    /// bottom-left space sets this.
144    pub bottom_left: bool,
145    /// `[0, len(text)]` in characters for a text item, `[0, 0]` for a table
146    /// or picture.
147    pub charspan: [usize; 2],
148}
149
150/// docling's `TrackSource` — where in a time-based track (a WebVTT cue) a
151/// text item came from. Written as the item's `source: [{"kind": "track", …}]`.
152#[derive(Debug, Clone, PartialEq)]
153pub struct TreeTrack {
154    /// The cue's start offset in seconds (docling's `WebVTTTimestamp.seconds`:
155    /// `h*3600 + m*60 + s + millis/1000.0`, so the float is bit-identical).
156    pub start_time: f64,
157    /// The cue's end offset in seconds.
158    pub end_time: f64,
159    /// The cue identifier line, when the cue has one.
160    pub identifier: Option<String>,
161    /// The `<v …>` voice annotation the text sits in, when any.
162    pub voice: Option<String>,
163}
164
165/// One item of an [`ItemTree`].
166#[derive(Debug, Clone, PartialEq)]
167pub struct TreeItem {
168    /// The parent item's index; `None` = the document body.
169    pub parent: Option<usize>,
170    /// Child item indices, in docling's `children` order.
171    pub children: Vec<usize>,
172    /// The content layer; `None` = `body`.
173    pub layer: Option<ContentLayer>,
174    pub kind: TreeKind,
175    /// The item's `prov` entry, when the backend has page geometry for it
176    /// (`None` → `prov: []`, what the HTML and DOCX backends write).
177    pub prov: Option<TreeProv>,
178    /// Further `prov` entries after [`Self::prov`], each with its
179    /// `charspan` into the text: docling's item over several boxes (a
180    /// paragraph joined across columns or pages), read back from a DocLang
181    /// thread (#1207).
182    pub more_prov: Vec<TreeProv>,
183    /// docling's `DocItem.comments`: the `comment_section` groups (or note
184    /// text items) annotating this item, as item indices — written after
185    /// `prov` when non-empty.
186    pub comments: Vec<usize>,
187    /// docling's `DocItem.source`: the track segment a text item was taken
188    /// from (WebVTT cues) — written after `prov` when set.
189    pub source: Option<TreeTrack>,
190    /// Removed by [`ItemTree::delete`] (docling's `delete_items`): the slot
191    /// stays so every other index keeps its meaning, but the item is not
192    /// numbered or written.
193    pub deleted: bool,
194    /// docling's `FloatingItem.footnotes` for a picture or code item (a
195    /// DocLang float group's `<footnote>`s), as item indices — written as the
196    /// item's `footnotes` refs; a table keeps its own in
197    /// [`TreeKind::Table`]'s `footnotes`. Unrelated to [`Self::notes`], which
198    /// are note calls in a text.
199    pub footnotes: Vec<usize>,
200    /// Footnotes / endnotes referenced from inside this text item (#538): the
201    /// note call's position (chars into the item's text) and the note's text.
202    /// docling keeps notes as unlinked furniture `footnote` items, so the
203    /// JSON never shows this; the Pandoc AST writes each as a `Note` there.
204    pub notes: Vec<TreeNote>,
205    /// This furniture `footnote` item is the body of a note some text item
206    /// calls (it travels in that item's [`Self::notes`]); the Pandoc AST then
207    /// leaves it out as a standalone block.
208    pub note_body: bool,
209    /// Link destinations at this item (#849): the identifiers a document's
210    /// internal links (`hyperlink: "#id"`) point at — a DOCX bookmark in
211    /// a heading, say. docling's model has no slot for them, so the JSON
212    /// shows them only on the Pandoc path (`_anchors`), where a heading's
213    /// first one is its `Header` id and the rest empty `Span .anchor`s.
214    pub anchors: Vec<String>,
215    /// The generated numbering `text` opens with, when the backend put one
216    /// there (#850: a DOCX heading numbered through `w:numPr` is docling's
217    /// `1.2 Title`): `"1.2"` — the authored text follows it after one
218    /// space. docling's JSON keeps the numbered text; the Pandoc AST writes
219    /// the authored text alone (`_number` on that path), since Pandoc
220    /// numbers sections itself (`--number-sections`) and its docx reader
221    /// never writes the number into the `Header`.
222    pub number: Option<String>,
223    /// The tracked change this run carries under
224    /// [`TrackChanges::All`](crate::TrackChanges::All) (#851): the Pandoc
225    /// AST wraps the run in `Span .insertion` / `.deletion` (`_revision`
226    /// on that path); docling's JSON has no field for it.
227    pub revision: Option<crate::Revision>,
228    /// A picture's `meta.code` — docling's `CodeMetaField` (`text`,
229    /// `language`): the LaTeX backend keeps a `tikzpicture`'s source there
230    /// when no engine renders it (`("…", "Tikz")`).
231    pub code_meta: Option<(String, String)>,
232    /// The source block this item was made from (#903): an index into
233    /// [`ItemTree::blocks`], set by a backend that enumerates its source's
234    /// blocks (HTML). `None` when the backend does not, or for an item no
235    /// single block produced.
236    pub block: Option<usize>,
237}
238
239/// A block of the source document (#903, #904): the original element an
240/// item was made from — or one that produced no item, with the reason —
241/// so a caller can tie converted items back to the source, tell two
242/// identical texts apart, and read a block's text on its own terms, free of
243/// any serializer's separators.
244///
245/// The HTML backend enumerates, in document order, every element that
246/// produced an item, every non-inline element with text of its own (text
247/// nodes reached through inline elements only — a `<span>`'s text belongs
248/// to the block around it), and every empty `<p>`, heading, `<li>`, `<dt>`,
249/// `<dd>`, `<td>`/`<th>`, `<pre>` or `<caption>`. Pure containers (a layout
250/// `<div>` with nothing but blocks inside) are not blocks. Every text node
251/// of the source thus belongs to exactly one block.
252#[derive(Debug, Clone, PartialEq, Eq)]
253pub struct SourceBlock {
254    /// The element's tag name (`p`, `div`, `li`, `table`, `img`, …).
255    pub tag: String,
256    /// Its `id` attribute, when it has one.
257    pub id: Option<String>,
258    /// Its `class` attribute, as written.
259    pub class: Option<String>,
260    /// Every attribute of the element, by name (#910): `id` and `class`
261    /// among them, and whatever else the source put there — `style`,
262    /// `aria-hidden`, a RIS element's `typ`.
263    pub attrs: Vec<(String, String)>,
264    /// The element's path from the document root — each step the tag and
265    /// the 1-based position among the parent's same-tag element children,
266    /// `html/body/div[3]/p[1]` — stable for the document and unique to the
267    /// element, with or without an `id`.
268    pub path: String,
269    /// The block's own text: its text nodes (and those of the inline
270    /// elements inside it, not of nested blocks) in source order, whitespace
271    /// runs collapsed to one space, trimmed. Independent of what the items
272    /// made of it hold — a hidden block's text is here too.
273    pub text: String,
274    /// The items made from this block, in creation order — the top-level
275    /// ones (an inline group, not the runs inside it; a list group, not
276    /// its items, which have their `<li>` blocks). Empty when it produced
277    /// none: see `omitted`.
278    pub items: Vec<usize>,
279    /// Why no item was made from this block; `None` when `items` is not
280    /// empty.
281    pub omitted: Option<BlockOmission>,
282    /// The inline elements inside the block (#911) — a `<span
283    /// class="sr-only">`, a `<b>`, an `<a>` — each with its range in `text`,
284    /// in document order, nested ones after the ones they sit in.
285    pub inlines: Vec<SourceInline>,
286}
287
288impl SourceBlock {
289    /// The block's text without the inline elements `exclude` selects
290    /// (#911): their ranges cut out, whitespace normalized again. A
291    /// screen-reader alternative (`.sr-only`) left out, say — the caller
292    /// chooses, nothing is inferred from a class.
293    pub fn text_excluding(&self, exclude: impl Fn(&SourceInline) -> bool) -> String {
294        let mut cut: Vec<(usize, usize)> = self
295            .inlines
296            .iter()
297            .filter(|i| exclude(i))
298            .map(|i| (i.start, i.end))
299            .collect();
300        if cut.is_empty() {
301            return self.text.clone();
302        }
303        cut.sort_unstable();
304        let mut out = String::with_capacity(self.text.len());
305        let mut pos = 0;
306        for (start, end) in cut {
307            if start > pos {
308                out.push_str(&self.text[pos..start]);
309                out.push(' ');
310            }
311            pos = pos.max(end);
312        }
313        out.push_str(&self.text[pos.min(self.text.len())..]);
314        out.split_whitespace().collect::<Vec<_>>().join(" ")
315    }
316}
317
318/// An inline element inside a [`SourceBlock`] (#911): where its text sits
319/// in the block's, so a caller can select or leave out the text of one
320/// element — not a whole block — by what the source says about it.
321#[derive(Debug, Clone, PartialEq, Eq)]
322pub struct SourceInline {
323    /// The element's tag name (`span`, `b`, `a`, …).
324    pub tag: String,
325    /// Every attribute, by name.
326    pub attrs: Vec<(String, String)>,
327    /// Its path from the document root, as [`SourceBlock::path`].
328    pub path: String,
329    /// The byte range of its text in [`SourceBlock::text`] — always on
330    /// char boundaries, so `&text[start..end]` is the element's normalized
331    /// text; empty for an element with no text.
332    pub start: usize,
333    pub end: usize,
334}
335
336impl SourceInline {
337    /// The value of attribute `name`.
338    pub fn attr(&self, name: &str) -> Option<&str> {
339        self.attrs
340            .iter()
341            .find(|(k, _)| k == name)
342            .map(|(_, v)| v.as_str())
343    }
344
345    /// Its `id` attribute.
346    pub fn id(&self) -> Option<&str> {
347        self.attr("id")
348    }
349
350    /// Its `class` attribute, as written.
351    pub fn class(&self) -> Option<&str> {
352        self.attr("class")
353    }
354
355    /// Whether `class` is one of the element's classes.
356    pub fn has_class(&self, class: &str) -> bool {
357        self.class()
358            .is_some_and(|c| c.split_whitespace().any(|x| x == class))
359    }
360}
361
362/// Builds a [`SourceBlock`]'s normalized text while recording the inline
363/// elements' ranges in it (#911) — for a backend walking its source: text
364/// nodes through [`push_text`](Self::push_text), a line break as
365/// whitespace, an inline element between [`open_inline`](Self::open_inline)
366/// and [`close_inline`](Self::close_inline). Whitespace runs collapse to one
367/// space, the text is trimmed, and a range never starts with the space
368/// that separates it from what precedes.
369#[derive(Debug, Default)]
370pub struct SourceTextBuilder {
371    text: String,
372    /// Whitespace seen since the last non-space char, not yet written.
373    pending: bool,
374    inlines: Vec<SourceInline>,
375    /// The inlines open right now, as indices into `inlines`.
376    open: Vec<usize>,
377}
378
379impl SourceTextBuilder {
380    pub fn new() -> Self {
381        Self::default()
382    }
383
384    /// A text node (or any text) of the block.
385    pub fn push_text(&mut self, raw: &str) {
386        for c in raw.chars() {
387            if c.is_whitespace() {
388                self.pending = true;
389            } else {
390                self.flush_space();
391                self.text.push(c);
392            }
393        }
394    }
395
396    fn flush_space(&mut self) {
397        if self.pending {
398            // One space, however many elements' whitespace fell between two
399            // words (an empty spacing `<span>` between two others).
400            if !self.text.is_empty() && !self.text.ends_with(' ') {
401                self.text.push(' ');
402            }
403            self.pending = false;
404        }
405    }
406
407    /// An inline element starts here.
408    pub fn open_inline(&mut self, tag: &str, attrs: Vec<(String, String)>, path: String) {
409        self.flush_space();
410        let at = self.text.len();
411        self.open.push(self.inlines.len());
412        self.inlines.push(SourceInline {
413            tag: tag.to_string(),
414            attrs,
415            path,
416            start: at,
417            end: at,
418        });
419    }
420
421    /// The innermost open inline element ends here.
422    pub fn close_inline(&mut self) {
423        if let Some(i) = self.open.pop() {
424            self.inlines[i].end = self.text.len();
425        }
426    }
427
428    /// The text and the inline ranges; the text has no trailing space.
429    pub fn finish(mut self) -> (String, Vec<SourceInline>) {
430        while let Some(i) = self.open.pop() {
431            self.inlines[i].end = self.text.len();
432        }
433        if self.text.ends_with(' ') {
434            self.text.pop();
435            let len = self.text.len();
436            for i in &mut self.inlines {
437                i.start = i.start.min(len);
438                i.end = i.end.min(len);
439            }
440        }
441        (self.text, self.inlines)
442    }
443}
444
445/// An element of the source that is not a block but carries an `id` or a
446/// `class` (#910): a container — the `<div id="art_23">` an article's
447/// paragraphs sit in — so an excerpt selected by a container's identity
448/// resolves to a path and, through [`ItemTree::blocks_under`], to the blocks
449/// inside it. A block's own identity is on the block.
450#[derive(Debug, Clone, PartialEq, Eq)]
451pub struct SourceElement {
452    /// The element's tag name.
453    pub tag: String,
454    /// Its `id` attribute, when it has one.
455    pub id: Option<String>,
456    /// Its `class` attribute, as written.
457    pub class: Option<String>,
458    /// Every attribute, by name.
459    pub attrs: Vec<(String, String)>,
460    /// Its path from the document root, as [`SourceBlock::path`].
461    pub path: String,
462}
463
464/// Why a [`SourceBlock`] produced no item.
465#[derive(Debug, Clone, Copy, PartialEq, Eq)]
466pub enum BlockOmission {
467    /// No text of its own once normalized (an empty `<p>`, a `<li>` whose
468    /// content is nested blocks).
469    Empty,
470    /// Hidden or non-content (`display: none`, `hidden`, `<script>`,
471    /// `<style>`, `<noscript>`), or inside such an element.
472    Hidden,
473    /// In a table whose cells were flattened: the text is in the grid of
474    /// the table item (the index) rather than an item of its own.
475    InTable(usize),
476    /// Its text went into the items of an enclosing block (the index into
477    /// [`ItemTree::blocks`]): a `<p>` inside a `<li>` is the list item's
478    /// text.
479    Merged(usize),
480    /// The walk produced nothing the backend can attribute.
481    Unmapped,
482}
483
484/// A note call inside a text item ([`TreeItem::notes`]).
485#[derive(Debug, Clone, PartialEq, Eq)]
486pub struct TreeNote {
487    /// The call's position, in chars into the item's `text`.
488    pub offset: usize,
489    /// The note's plain text.
490    pub text: String,
491}
492
493impl ItemTree {
494    /// Where each note call of one paragraph lands (#538): `full_text` is the
495    /// paragraph's text, `offsets` the calls' positions in it (chars), and
496    /// the paragraph's items are those created from `first_new` on. Each text
497    /// item is a trimmed slice of the paragraph (a formatting run, a link, or
498    /// the whole heading / list item), matched in order; a call inside an
499    /// item lands there, one between items ends the earlier (or starts the
500    /// first). When no item matches, the call ends the paragraph's last text
501    /// item; with no text item at all it is `None`.
502    pub fn place_note_calls(
503        &self,
504        first_new: usize,
505        full_text: &str,
506        offsets: &[usize],
507    ) -> Vec<Option<(usize, usize)>> {
508        let texts: Vec<(usize, &str)> = (first_new..self.items.len())
509            .filter(|&i| !self.items[i].deleted)
510            .filter_map(|i| match &self.items[i].kind {
511                TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => {
512                    Some((i, text.as_str()))
513                }
514                _ => None,
515            })
516            .collect();
517        // Each found item's (id, start, end) in chars of `full_text`.
518        let mut spans: Vec<(usize, usize, usize)> = Vec::new();
519        let mut cursor = 0usize; // bytes
520        for &(item, text) in &texts {
521            if text.is_empty() {
522                continue;
523            }
524            if let Some(pos) = full_text[cursor..].find(text) {
525                let start_b = cursor + pos;
526                let start = full_text[..start_b].chars().count();
527                spans.push((item, start, start + text.chars().count()));
528                cursor = start_b + text.len();
529            }
530        }
531        offsets
532            .iter()
533            .map(|&offset| {
534                spans
535                    .iter()
536                    .find(|&&(_, start, end)| offset >= start && offset <= end)
537                    .map(|&(item, start, _)| (item, offset - start))
538                    .or_else(
539                        || match spans.iter().rev().find(|&&(_, _, end)| end <= offset) {
540                            Some(&(item, start, end)) => Some((item, end - start)),
541                            None => spans.first().map(|&(item, _, _)| (item, 0)),
542                        },
543                    )
544                    .or_else(|| {
545                        texts
546                            .last()
547                            .map(|&(item, text)| (item, text.chars().count()))
548                    })
549            })
550            .collect()
551    }
552}
553
554/// docling's item tree in creation order (see the [module docs](self)).
555#[derive(Debug, Clone, PartialEq, Default)]
556pub struct ItemTree {
557    /// Every item, indexed by creation order — which is how docling numbers
558    /// `#/texts/N`, `#/groups/N`, … within each bucket.
559    pub items: Vec<TreeItem>,
560    /// The body's `children`, as item indices.
561    pub body: Vec<usize>,
562    /// The source's blocks (#903), in document order, when the backend
563    /// enumerates them (HTML); each item's [`TreeItem::block`] points into
564    /// this. Empty otherwise.
565    pub blocks: Vec<SourceBlock>,
566    /// The source's containers that carry an `id` or a `class` (#910), in
567    /// document order; see [`SourceElement`]. Empty when `blocks` is.
568    pub containers: Vec<SourceElement>,
569    /// The runs of this tree's `inline` groups carry their own boundary
570    /// whitespace — docling-core's inline whitespace contract (schema 1.11.0,
571    /// [`crate::inline`]): a backend that keeps each run's spaces, as
572    /// docling's do since docling#3891, sets it. Unset, the runs are the
573    /// trimmed runs the old `" "` join expected, and the export re-injects
574    /// that join into them ([`Self::separate_legacy_inline_runs`]) so the
575    /// output reads as it did.
576    pub inline_whitespace: bool,
577    /// The DocLang export serializes the flat nodes rather than this tree,
578    /// which every other tree gets its DocLang from: the tree reproduces a
579    /// loss of docling's the nodes avoid (USPTO's tables, emptied when
580    /// docling's table regex misses them), and the DocLang follows the
581    /// Markdown there.
582    pub doclang_nodes: bool,
583}
584
585impl ItemTree {
586    /// Append an item under `parent` (`None` = body) on `layer`, registering
587    /// it as its parent's last child — docling's `add_*` calls do exactly that.
588    pub fn add(
589        &mut self,
590        parent: Option<usize>,
591        layer: Option<ContentLayer>,
592        kind: TreeKind,
593    ) -> usize {
594        let id = self.items.len();
595        self.items.push(TreeItem {
596            parent,
597            children: Vec::new(),
598            layer,
599            kind,
600            prov: None,
601            more_prov: Vec::new(),
602            comments: Vec::new(),
603            source: None,
604            deleted: false,
605            footnotes: Vec::new(),
606            notes: Vec::new(),
607            note_body: false,
608            anchors: Vec::new(),
609            number: None,
610            revision: None,
611            code_meta: None,
612            block: None,
613        });
614        match parent {
615            Some(p) => self.items[p].children.push(id),
616            None => self.body.push(id),
617        }
618        id
619    }
620
621    /// [`add`](Self::add) with the item's provenance — docling's
622    /// `add_text(…, prov=prov)`.
623    pub fn add_with_prov(
624        &mut self,
625        parent: Option<usize>,
626        layer: Option<ContentLayer>,
627        kind: TreeKind,
628        prov: TreeProv,
629    ) -> usize {
630        let id = self.add(parent, layer, kind);
631        self.items[id].prov = Some(prov);
632        id
633    }
634
635    /// The text of the given source blocks (#904), one line each: each
636    /// block's own normalized [`SourceBlock::text`], joined with a single
637    /// `\n` — no serializer decoration, no trailing separator, nothing of
638    /// the blocks around them. Indices out of range are skipped.
639    pub fn source_text(&self, blocks: impl IntoIterator<Item = usize>) -> String {
640        let mut out = String::new();
641        for b in blocks {
642            let Some(block) = self.blocks.get(b) else {
643                continue;
644            };
645            if !out.is_empty() {
646                out.push('\n');
647            }
648            out.push_str(&block.text);
649        }
650        out
651    }
652
653    /// [`source_text`](Self::source_text) without the inline elements
654    /// `exclude` selects in each block ([`SourceBlock::text_excluding`]).
655    pub fn source_text_excluding(
656        &self,
657        blocks: impl IntoIterator<Item = usize>,
658        exclude: impl Fn(&SourceInline) -> bool,
659    ) -> String {
660        let mut out = String::new();
661        for b in blocks {
662            let Some(block) = self.blocks.get(b) else {
663                continue;
664            };
665            if !out.is_empty() {
666                out.push('\n');
667            }
668            out.push_str(&block.text_excluding(&exclude));
669        }
670        out
671    }
672
673    /// The blocks under `path` (#910), in document order: those whose
674    /// [`SourceBlock::path`] is `path` or starts with `path/` — the block
675    /// itself, or everything inside a container.
676    pub fn blocks_under(&self, path: &str) -> Vec<usize> {
677        let prefix = format!("{path}/");
678        self.blocks
679            .iter()
680            .enumerate()
681            .filter(|(_, b)| b.path == path || b.path.starts_with(&prefix))
682            .map(|(i, _)| i)
683            .collect()
684    }
685
686    /// The path of the element with `id` (#910): a block's or a container's,
687    /// the first in document order when the source repeats an id.
688    pub fn path_of_id(&self, id: &str) -> Option<&str> {
689        let block = self
690            .blocks
691            .iter()
692            .find(|b| b.id.as_deref() == Some(id))
693            .map(|b| b.path.as_str());
694        let container = self
695            .containers
696            .iter()
697            .find(|c| c.id.as_deref() == Some(id))
698            .map(|c| c.path.as_str());
699        match (block, container) {
700            (Some(b), Some(c)) => Some(if b.len() <= c.len() && b < c { b } else { c }),
701            (b, c) => b.or(c),
702        }
703    }
704
705    /// Append every item of `other` after this tree's, renumbering its
706    /// indices (parents, children, comments, table/picture caption and
707    /// rich-cell refs) and adding its body children to this body — so a
708    /// backend can build independent fragments in parallel (one per PPTX
709    /// slide) and still hand the export one tree in creation order, exactly
710    /// as if it had been built sequentially.
711    pub fn append(&mut self, other: ItemTree) {
712        let off = self.items.len();
713        let shift = |i: usize| i + off;
714        for mut item in other.items {
715            item.parent = item.parent.map(shift);
716            for c in item
717                .children
718                .iter_mut()
719                .chain(item.comments.iter_mut())
720                .chain(item.footnotes.iter_mut())
721            {
722                *c = shift(*c);
723            }
724            match &mut item.kind {
725                TreeKind::Table {
726                    rich_cells,
727                    captions,
728                    footnotes,
729                    ..
730                } => {
731                    for (_, _, g) in rich_cells.iter_mut() {
732                        *g = shift(*g);
733                    }
734                    for c in captions.iter_mut().chain(footnotes.iter_mut()) {
735                        *c = shift(*c);
736                    }
737                }
738                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
739                    for c in captions.iter_mut() {
740                        *c = shift(*c);
741                    }
742                }
743                _ => {}
744            }
745            self.items.push(item);
746        }
747        self.body.extend(other.body.into_iter().map(shift));
748        let block_off = self.blocks.len();
749        for mut b in other.blocks {
750            for i in b.items.iter_mut() {
751                *i = shift(*i);
752            }
753            if let Some(BlockOmission::InTable(t)) = b.omitted.as_mut() {
754                *t = shift(*t);
755            }
756            if let Some(BlockOmission::Merged(m)) = b.omitted.as_mut() {
757                *m += block_off;
758            }
759            self.blocks.push(b);
760        }
761        for item in &mut self.items[off..] {
762            if let Some(b) = item.block.as_mut() {
763                *b += block_off;
764            }
765        }
766        self.containers.extend(other.containers);
767    }
768
769    /// Move `id` under `new_parent`, dropping it from its current parent's
770    /// children and appending it to the new one's — docling's
771    /// `group_cell_elements` re-parenting of a rich cell's items.
772    pub fn reparent(&mut self, id: usize, new_parent: Option<usize>) {
773        let old = self.items[id].parent;
774        let siblings = match old {
775            Some(p) => &mut self.items[p].children,
776            None => &mut self.body,
777        };
778        siblings.retain(|&c| c != id);
779        self.items[id].parent = new_parent;
780        match new_parent {
781            Some(p) => self.items[p].children.push(id),
782            None => self.body.push(id),
783        }
784    }
785
786    /// Re-number the items in traversal order — a pre-order walk of the body
787    /// through every layer, which is how docling's
788    /// `DoclingDocument.concatenate` (and `_normalize_references`) re-creates
789    /// a document's items: a group created after the content it was later
790    /// wrapped around comes before that content afterwards. Items the walk
791    /// does not reach (deleted ones) are dropped. Returns each old id's new
792    /// id.
793    pub fn renumber_in_traversal_order(&mut self) -> Vec<Option<usize>> {
794        let mut order = Vec::with_capacity(self.items.len());
795        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
796        while let Some(id) = stack.pop() {
797            if self.items[id].deleted {
798                continue;
799            }
800            order.push(id);
801            stack.extend(self.items[id].children.iter().rev());
802        }
803        let mut new_of: Vec<Option<usize>> = vec![None; self.items.len()];
804        for (new, &old) in order.iter().enumerate() {
805            new_of[old] = Some(new);
806        }
807        let remap = |ids: &mut Vec<usize>| {
808            *ids = ids.iter().filter_map(|&i| new_of[i]).collect();
809        };
810        let mut old_items: Vec<Option<TreeItem>> = std::mem::take(&mut self.items)
811            .into_iter()
812            .map(Some)
813            .collect();
814        for &old in &order {
815            let mut item = old_items[old].take().expect("each item visited once");
816            item.parent = item.parent.and_then(|p| new_of[p]);
817            remap(&mut item.children);
818            remap(&mut item.comments);
819            remap(&mut item.footnotes);
820            match &mut item.kind {
821                TreeKind::Table {
822                    rich_cells,
823                    captions,
824                    footnotes,
825                    ..
826                } => {
827                    remap(footnotes);
828                    rich_cells.retain_mut(|(_, _, g)| match new_of[*g] {
829                        Some(n) => {
830                            *g = n;
831                            true
832                        }
833                        None => false,
834                    });
835                    remap(captions);
836                }
837                TreeKind::Picture { captions, .. } | TreeKind::Code { captions, .. } => {
838                    remap(captions)
839                }
840                _ => {}
841            }
842            self.items.push(item);
843        }
844        remap(&mut self.body);
845        for b in &mut self.blocks {
846            remap(&mut b.items);
847            if let Some(BlockOmission::InTable(t)) = b.omitted {
848                b.omitted = Some(match new_of[t] {
849                    Some(n) => BlockOmission::InTable(n),
850                    None => BlockOmission::Unmapped,
851                });
852            }
853        }
854        new_of
855    }
856
857    /// Remove `id` from the tree — docling's `delete_items`, which the DOCX
858    /// backend uses to drop the empty text item a blank spacer paragraph left
859    /// between two items of a resumed list. The item leaves its parent's
860    /// children and is neither numbered nor written; its slot stays so the
861    /// indices held elsewhere stay valid.
862    pub fn delete(&mut self, id: usize) {
863        match self.items[id].parent {
864            Some(p) => self.items[p].children.retain(|&c| c != id),
865            None => self.body.retain(|&c| c != id),
866        }
867        self.items[id].deleted = true;
868    }
869
870    /// docling-core's `_migrate_legacy_inline_separators` (#997) over the
871    /// tree: every `inline` group's runs get the `" "` the pre-1.11 join put
872    /// between them ([`crate::inline::separate_legacy_runs`]) — on a plain
873    /// neighbour, never inside a code or formula run, a standalone `" "` text
874    /// run when both neighbours are delimited. The JSON export applies it to
875    /// a tree whose backend has not set [`Self::inline_whitespace`], so a
876    /// trimmed-run backend still reads `left bold right` under the faithful
877    /// join, as docling-core reads a document saved before the contract.
878    /// `text` changes, `orig` keeps the run's own text.
879    pub fn separate_legacy_inline_runs(&mut self) {
880        fn renders_text(t: &ItemTree, id: usize, depth: usize) -> bool {
881            let item = &t.items[id];
882            if item.deleted || depth > 64 {
883                return false;
884            }
885            let own = match &item.kind {
886                TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => !text.is_empty(),
887                TreeKind::Group { .. } => false,
888                // docling-core resolves only `#/texts/` and `#/groups/`.
889                _ => return false,
890            };
891            own || item.children.iter().any(|&c| renders_text(t, c, depth + 1))
892        }
893        let groups: Vec<usize> = (0..self.items.len())
894            .filter(|&g| {
895                !self.items[g].deleted
896                    && matches!(&self.items[g].kind, TreeKind::Group { label, .. } if label == "inline")
897            })
898            .collect();
899        for g in groups {
900            let children: Vec<usize> = self.items[g]
901                .children
902                .iter()
903                .copied()
904                .filter(|&c| !self.items[c].deleted)
905                .collect();
906            let flags: Vec<(bool, bool, bool)> = children
907                .iter()
908                .map(|&c| {
909                    let item = &self.items[c];
910                    let (plain, empty_plain) = match &item.kind {
911                        TreeKind::Text { label, text, .. } => (
912                            label != "formula" && label != "code",
913                            label == "text" && text.is_empty() && item.children.is_empty(),
914                        ),
915                        _ => (false, false),
916                    };
917                    (renders_text(self, c, 0), plain, empty_plain)
918                })
919                .collect();
920            // Detach the texts so each run can be borrowed mutably at once.
921            let mut texts: Vec<String> = children
922                .iter()
923                .map(|&c| match &self.items[c].kind {
924                    TreeKind::Text { text, .. } | TreeKind::Code { text, .. } => text.clone(),
925                    _ => String::new(),
926                })
927                .collect();
928            let originals = texts.clone();
929            let standalone = {
930                let mut runs: Vec<crate::inline::LegacyRun<'_>> = texts
931                    .iter_mut()
932                    .zip(&flags)
933                    .map(
934                        |(text, &(renders_text, plain, empty_plain))| crate::inline::LegacyRun {
935                            text,
936                            renders_text,
937                            plain,
938                            empty_plain,
939                        },
940                    )
941                    .collect();
942                crate::inline::separate_legacy_runs(&mut runs)
943            };
944            for ((&c, new), old) in children.iter().zip(texts).zip(originals) {
945                if new == old {
946                    continue;
947                }
948                // docling-core rewrites `text` and leaves `orig` as it was.
949                if let TreeKind::Text { text, orig, .. } | TreeKind::Code { text, orig, .. } =
950                    &mut self.items[c].kind
951                {
952                    orig.get_or_insert(old);
953                    *text = new;
954                }
955            }
956            for at in standalone.into_iter().rev() {
957                let (left, right) = (children[at - 1], children[at]);
958                // The left run's location when both sit on one page, so a
959                // page filter keeps the separator exactly when it keeps both.
960                let prov = match (&self.items[left].prov, &self.items[right].prov) {
961                    (Some(l), Some(r)) if l.page_no == r.page_no => Some(TreeProv {
962                        charspan: [0, 1],
963                        ..l.clone()
964                    }),
965                    _ => None,
966                };
967                let layer = self.items[g].layer;
968                let id = self.add(
969                    Some(g),
970                    layer,
971                    TreeKind::Text {
972                        label: "text".into(),
973                        text: " ".into(),
974                        orig: None,
975                        formatting: None,
976                        hyperlink: None,
977                        level: None,
978                        list: None,
979                    },
980                );
981                self.items[id].prov = prov;
982                let kids = &mut self.items[g].children;
983                kids.pop();
984                let pos = kids.iter().position(|&k| k == right).unwrap_or(kids.len());
985                kids.insert(pos, id);
986            }
987        }
988    }
989
990    /// docling-core's `DoclingDocument.validate_misplaced_list_items` (a
991    /// model validator, so it runs whenever docling-core serializes or loads
992    /// a document): every `list_item` whose parent is not a `list` group is
993    /// re-homed into a new one. A pre-order walk of the body (groups
994    /// included) collects them; consecutive misplaced items directly on the
995    /// body share one group, any other misplaced item gets its own. Working
996    /// from the last run back, each run gets a `ListGroup` (name `group`)
997    /// inserted where its first item stood, the items are deleted and
998    /// re-added under the group as fresh items, so they move to the end of
999    /// the text numbering (#527: the DOCX backend leaves such items in rich
1000    /// table cells). A no-op for a well-formed tree.
1001    ///
1002    /// One deliberate divergence (#586): docling-core deletes each item *with
1003    /// its children* and re-adds it from its text alone, so a mixed-format
1004    /// item — an empty `list_item` over an `inline` group of text runs —
1005    /// comes back empty and its text is gone from the JSON (and from the
1006    /// Markdown/HTML docling serializes after that validator ran; the JSON
1007    /// docling saves *before* exporting still has it). Here the children
1008    /// follow the item into the group: the structure docling-core requires,
1009    /// the content the document had.
1010    pub fn wrap_misplaced_list_items(&mut self) {
1011        let is_list_item = |t: &Self, id: usize| matches!(&t.items[id].kind, TreeKind::Text { label, .. } if label == "list_item");
1012        let in_list_group = |t: &Self, id: usize| {
1013            t.items[id].parent.is_some_and(
1014                |p| matches!(&t.items[p].kind, TreeKind::Group { label, .. } if label == "list"),
1015            )
1016        };
1017        let mut runs: Vec<Vec<usize>> = Vec::new();
1018        // `None` = the body itself, which the walk yields first.
1019        let mut prev: Option<usize> = None;
1020        let mut stack: Vec<usize> = self.body.iter().rev().copied().collect();
1021        while let Some(id) = stack.pop() {
1022            if self.items[id].deleted {
1023                continue;
1024            }
1025            if is_list_item(self, id) && !in_list_group(self, id) {
1026                let continues =
1027                    prev.is_some_and(|p| is_list_item(self, p) && self.items[p].parent.is_none());
1028                match runs.last_mut() {
1029                    Some(run) if continues => run.push(id),
1030                    _ => runs.push(vec![id]),
1031                }
1032            }
1033            prev = Some(id);
1034            stack.extend(self.items[id].children.iter().rev().copied());
1035        }
1036        for run in runs.into_iter().rev() {
1037            let parent = self.items[run[0]].parent;
1038            let group = self.add(
1039                parent,
1040                None,
1041                TreeKind::Group {
1042                    label: "list".into(),
1043                    name: "group".into(),
1044                },
1045            );
1046            let siblings = match parent {
1047                Some(p) => &mut self.items[p].children,
1048                None => &mut self.body,
1049            };
1050            siblings.pop();
1051            let at = siblings
1052                .iter()
1053                .position(|&c| c == run[0])
1054                .unwrap_or(siblings.len());
1055            siblings.insert(at, group);
1056            for &li in &run {
1057                // Not `delete_subtree`: the children move to the copy (#586).
1058                self.delete(li);
1059            }
1060            // `add_list_item` keeps the text, marker, formatting, hyperlink
1061            // and first provenance — not comments or a source. The children
1062            // (the inline group of a mixed-format item) are carried over.
1063            for &li in &run {
1064                let children = std::mem::take(&mut self.items[li].children);
1065                let copy = TreeItem {
1066                    parent: Some(group),
1067                    children: children.clone(),
1068                    comments: Vec::new(),
1069                    source: None,
1070                    deleted: false,
1071                    ..self.items[li].clone()
1072                };
1073                let id = self.items.len();
1074                self.items.push(copy);
1075                for c in children {
1076                    self.items[c].parent = Some(id);
1077                }
1078                self.items[group].children.push(id);
1079            }
1080        }
1081    }
1082
1083    /// The last live text-bucket item (docling's `doc.texts[-1]`).
1084    pub fn last_text(&self) -> Option<usize> {
1085        self.items.iter().rposition(|it| {
1086            !it.deleted && matches!(it.kind, TreeKind::Text { .. } | TreeKind::Code { .. })
1087        })
1088    }
1089
1090    /// How many items of a bucket precede `id` — its `#/{bucket}/N` index.
1091    pub fn bucket_index(&self, id: usize) -> usize {
1092        let same = |k: &TreeKind| {
1093            std::mem::discriminant(k) == std::mem::discriminant(&self.items[id].kind)
1094                || matches!(
1095                    (k, &self.items[id].kind),
1096                    (TreeKind::Text { .. }, TreeKind::Code { .. })
1097                        | (TreeKind::Code { .. }, TreeKind::Text { .. })
1098                )
1099        };
1100        self.items[..id]
1101            .iter()
1102            .filter(|it| !it.deleted && same(&it.kind))
1103            .count()
1104    }
1105
1106    /// The number of tables created so far (docling's `len(doc.tables)`).
1107    pub fn table_count(&self) -> usize {
1108        self.items
1109            .iter()
1110            .filter(|it| !it.deleted && matches!(it.kind, TreeKind::Table { .. }))
1111            .count()
1112    }
1113}
1114
1115#[cfg(test)]
1116mod tests {
1117    use super::*;
1118
1119    fn text(t: &str) -> TreeKind {
1120        TreeKind::Text {
1121            label: "text".into(),
1122            text: t.into(),
1123            orig: None,
1124            formatting: None,
1125            hyperlink: None,
1126            level: None,
1127            list: None,
1128        }
1129    }
1130
1131    /// `add` registers the item as its parent's (or the body's) last child;
1132    /// `reparent` moves it — a rich cell's items leave the heading they were
1133    /// created under for the table's group.
1134    #[test]
1135    fn add_and_reparent_keep_docling_children_order() {
1136        let mut t = ItemTree::default();
1137        let title = t.add(None, None, text("Title"));
1138        let a = t.add(Some(title), None, text("a"));
1139        let b = t.add(Some(title), None, text("b"));
1140        let table = t.add(
1141            Some(title),
1142            None,
1143            TreeKind::Table {
1144                footnotes: Vec::new(),
1145                table: Table::default(),
1146                rich_cells: Vec::new(),
1147                captions: Vec::new(),
1148            },
1149        );
1150        let group = t.add(
1151            Some(table),
1152            None,
1153            TreeKind::Group {
1154                label: "unspecified".into(),
1155                name: "rich_cell_group_1_0_0".into(),
1156            },
1157        );
1158        assert_eq!(t.body, vec![title]);
1159        assert_eq!(t.items[title].children, vec![a, b, table]);
1160        t.reparent(a, Some(group));
1161        assert_eq!(t.items[title].children, vec![b, table]);
1162        assert_eq!(t.items[group].children, vec![a]);
1163        assert_eq!(t.items[a].parent, Some(group));
1164        assert_eq!(t.table_count(), 1);
1165        // Text and code share the `texts` bucket.
1166        let code = t.add(
1167            None,
1168            None,
1169            TreeKind::Code {
1170                text: "x".into(),
1171                orig: None,
1172                language: None,
1173                formatting: None,
1174                hyperlink: None,
1175                captions: Vec::new(),
1176            },
1177        );
1178        assert_eq!(t.bucket_index(code), 3, "title, a, b precede it in `texts`");
1179        assert_eq!(t.bucket_index(group), 0);
1180        assert_eq!(t.body, vec![title, code]);
1181    }
1182
1183    /// `append` renumbers a fragment built on its own (a slide converted in
1184    /// parallel) so the merged tree reads as if built in one pass: parents,
1185    /// children, comment back-refs and caption refs all shift together.
1186    #[test]
1187    fn append_renumbers_a_fragment_into_creation_order() {
1188        let mut whole = ItemTree::default();
1189        let slide0 = whole.add(
1190            None,
1191            None,
1192            TreeKind::Group {
1193                label: "chapter".into(),
1194                name: "slide-0".into(),
1195            },
1196        );
1197        whole.add(Some(slide0), None, text("first"));
1198
1199        let mut frag = ItemTree::default();
1200        let slide1 = frag.add(
1201            None,
1202            None,
1203            TreeKind::Group {
1204                label: "chapter".into(),
1205                name: "slide-1".into(),
1206            },
1207        );
1208        let cap = frag.add_with_prov(
1209            Some(slide1),
1210            None,
1211            TreeKind::Text {
1212                label: "caption".into(),
1213                text: "Title".into(),
1214                orig: None,
1215                formatting: None,
1216                hyperlink: None,
1217                level: None,
1218                list: None,
1219            },
1220            TreeProv {
1221                page_no: 2,
1222                bbox: [1.0, 2.0, 3.0, 4.0],
1223                bottom_left: true,
1224                charspan: [0, 5],
1225            },
1226        );
1227        let pic = frag.add(
1228            Some(slide1),
1229            None,
1230            TreeKind::Picture {
1231                captions: vec![cap],
1232                image: None,
1233                extra_classes: Vec::new(),
1234                classification: Some("bar_chart".into()),
1235                description: None,
1236                confidence: None,
1237                chart: None,
1238                dpi: None,
1239            },
1240        );
1241        let note = frag.add(
1242            None,
1243            Some(ContentLayer::Notes),
1244            TreeKind::Group {
1245                label: "comment_section".into(),
1246                name: "comment-slide2-1".into(),
1247            },
1248        );
1249        frag.items[pic].comments.push(note);
1250
1251        whole.append(frag);
1252        assert_eq!(whole.body, vec![slide0, 2, 5]);
1253        assert_eq!(whole.items[2].children, vec![3, 4]);
1254        assert_eq!(whole.items[3].parent, Some(2));
1255        assert_eq!(whole.items[3].prov.as_ref().map(|p| p.page_no), Some(2));
1256        assert!(
1257            matches!(&whole.items[4].kind, TreeKind::Picture { captions, .. } if captions == &[3])
1258        );
1259        assert_eq!(whole.items[4].comments, vec![5]);
1260        assert_eq!(whole.items[5].parent, None);
1261        assert_eq!(
1262            whole.bucket_index(4),
1263            0,
1264            "the fragment's picture is #/pictures/0"
1265        );
1266        assert_eq!(
1267            whole.bucket_index(5),
1268            2,
1269            "slide-0, slide-1 precede it in `groups`"
1270        );
1271    }
1272
1273    /// `renumber_in_traversal_order`: docling's `concatenate` re-creates the
1274    /// items as a pre-order walk meets them, so a group created after the
1275    /// content it was wrapped around (a rich cell's group) comes first, and a
1276    /// deleted item disappears; every cross-reference follows.
1277    #[test]
1278    fn renumbering_follows_the_traversal() {
1279        let mut t = ItemTree::default();
1280        let a = t.add(None, None, text("a"));
1281        let table = t.add(
1282            None,
1283            None,
1284            TreeKind::Table {
1285                footnotes: Vec::new(),
1286                table: Table::default(),
1287                rich_cells: Vec::new(),
1288                captions: Vec::new(),
1289            },
1290        );
1291        let cell_text = t.add(None, None, text("cell"));
1292        let group = t.add(
1293            Some(table),
1294            None,
1295            TreeKind::Group {
1296                label: "unspecified".into(),
1297                name: "rich_cell_group_1_0_0".into(),
1298            },
1299        );
1300        t.reparent(cell_text, Some(group));
1301        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
1302            rich_cells.push((0, 0, group));
1303        }
1304        let gone = t.add(None, None, text("gone"));
1305        t.delete(gone);
1306        let z = t.add(None, None, text("z"));
1307
1308        let new_of = t.renumber_in_traversal_order();
1309        assert_eq!(
1310            new_of,
1311            vec![Some(0), Some(1), Some(3), Some(2), None, Some(4)]
1312        );
1313        assert_eq!(t.items.len(), 5);
1314        assert_eq!(t.body, vec![0, 1, 4]);
1315        assert_eq!(t.items[1].children, vec![2], "the group follows its table");
1316        assert_eq!(t.items[2].parent, Some(1));
1317        assert_eq!(
1318            t.items[3].parent,
1319            Some(2),
1320            "the cell text follows its group"
1321        );
1322        assert!(matches!(&t.items[3].kind, TreeKind::Text { text, .. } if text == "cell"));
1323        assert!(
1324            matches!(&t.items[1].kind, TreeKind::Table { rich_cells, .. } if rich_cells == &[(0, 0, 2)])
1325        );
1326        let _ = (a, z);
1327    }
1328
1329    /// #586: a misplaced `list_item` keeps its children when it is re-homed.
1330    /// docling-core's `validate_misplaced_list_items` re-adds the item from
1331    /// its text alone, so a mixed-format item (empty `list_item` over an
1332    /// `inline` group of runs) lost every run — a DOCX table cell whose list
1333    /// paragraph followed a `numId 0` spacer came out as an empty bullet in
1334    /// the JSON and the HTML. The group goes where the item stood, the copy
1335    /// is numbered last, the inline group and its texts move under it.
1336    #[test]
1337    fn wrapping_a_misplaced_list_item_keeps_its_runs() {
1338        let mut t = ItemTree::default();
1339        let cell = t.add(
1340            None,
1341            None,
1342            TreeKind::Group {
1343                label: "unspecified".into(),
1344                name: "rich_cell_group_1_0_1".into(),
1345            },
1346        );
1347        let before = t.add(Some(cell), None, text("before"));
1348        let item = t.add(
1349            Some(cell),
1350            None,
1351            TreeKind::Text {
1352                label: "list_item".into(),
1353                text: String::new(),
1354                orig: None,
1355                formatting: None,
1356                hyperlink: None,
1357                level: None,
1358                list: Some(ListMeta {
1359                    enumerated: false,
1360                    marker: String::new(),
1361                }),
1362            },
1363        );
1364        let inline = t.add(
1365            Some(item),
1366            None,
1367            TreeKind::Group {
1368                label: "inline".into(),
1369                name: "group".into(),
1370            },
1371        );
1372        let run_a = t.add(Some(inline), None, text("Second item text"));
1373        let run_b = t.add(Some(inline), None, text("[Optional]"));
1374        let after = t.add(Some(cell), None, text("after"));
1375
1376        t.wrap_misplaced_list_items();
1377
1378        let group = t.items[cell].children[1];
1379        assert_eq!(t.items[cell].children, vec![before, group, after]);
1380        assert!(
1381            matches!(&t.items[group].kind, TreeKind::Group { label, name } if label == "list" && name == "group")
1382        );
1383        assert!(t.items[item].deleted, "the original item is deleted");
1384        let copy = t.items[group].children[0];
1385        assert_ne!(copy, item);
1386        assert!(
1387            copy > after,
1388            "the copy is numbered after every existing item"
1389        );
1390        assert_eq!(t.items[copy].children, vec![inline]);
1391        assert_eq!(t.items[inline].parent, Some(copy));
1392        assert_eq!(t.items[inline].children, vec![run_a, run_b]);
1393        for id in [inline, run_a, run_b] {
1394            assert!(!t.items[id].deleted, "item {id} must survive the re-homing");
1395        }
1396    }
1397}