Skip to main content

docling_core/
json.rs

1//! Export a [`DoclingDocument`] to docling-core's native JSON wire format
2//! (`DoclingDocument` schema v1.11.0) — the same shape `export_to_dict()` /
3//! `save_as_json()` produce in Python docling, and the inverse of the
4//! JSON-docling reader.
5//!
6//! The crate's [`Node`] model bakes Markdown escaping (and inline markers) into
7//! its text, whereas docling stores raw text and escapes at render time. We
8//! therefore *un-escape* on the way out so a docling-core round-trip
9//! (`load_from_json().export_to_markdown()`) reproduces the same Markdown.
10
11use serde_json::{json, Map, Value};
12
13use crate::document::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
14
15const SCHEMA_VERSION: &str = "1.11.0";
16
17/// docling-core's `CodeLanguageLabel` values (anything else serializes as
18/// `unknown`, which the model requires for code items).
19const CODE_LANGUAGES: &[&str] = &[
20    "Ada",
21    "Awk",
22    "Bash",
23    "bc",
24    "C",
25    "C#",
26    "C++",
27    "CMake",
28    "COBOL",
29    "CSS",
30    "Ceylon",
31    "Clojure",
32    "Crystal",
33    "Cuda",
34    "Cython",
35    "D",
36    "Dart",
37    "dc",
38    "Dockerfile",
39    "DocLang",
40    "Elixir",
41    "Erlang",
42    "FORTRAN",
43    "Forth",
44    "Go",
45    "HTML",
46    "Haskell",
47    "Haxe",
48    "Java",
49    "JavaScript",
50    "JSON",
51    "Julia",
52    "Kotlin",
53    "Latex",
54    "Lisp",
55    "Lua",
56    "Matlab",
57    "MoonScript",
58    "Nim",
59    "OCaml",
60    "ObjectiveC",
61    "Octave",
62    "PHP",
63    "Pascal",
64    "Perl",
65    "Prolog",
66    "Python",
67    "Racket",
68    "Ruby",
69    "Rust",
70    "SML",
71    "SQL",
72    "Scala",
73    "Scheme",
74    "Swift",
75    "Tikz",
76    "TypeScript",
77    "VisualBasic",
78    "XML",
79    "YAML",
80];
81
82/// Map a fence language to docling's `CodeLanguageLabel` (case-insensitive), else
83/// `unknown`.
84/// docling's `CodeLanguageLabel` for a language name (`unknown` when it is
85/// not one docling knows) — the mapping the JSON `code_language` field uses,
86/// for a backend that wants to test a hint before storing it.
87/// The length in characters of a node's Markdown-escaped `text` as the JSON
88/// export writes it (unescaped): the unit of docling's `charspan`. The PDF
89/// assembler counts a joined paragraph's fragments with it (#1127).
90pub fn text_char_len(md: &str) -> usize {
91    unescape_text(md).chars().count()
92}
93
94pub fn code_language_label(lang: &str) -> &'static str {
95    code_language(Some(lang))
96}
97
98pub(crate) fn code_language(lang: Option<&str>) -> &'static str {
99    match lang {
100        Some(l) => CODE_LANGUAGES
101            .iter()
102            .find(|c| c.eq_ignore_ascii_case(l))
103            .copied()
104            .unwrap_or("unknown"),
105        None => "unknown",
106    }
107}
108
109/// An item's exact provenance, written verbatim (see [`Builder::prov_json`]):
110/// a [`Node::Prov`] wrapper's top-left page box, or a tree item's
111/// [`TreeProv`](crate::tree::TreeProv).
112#[derive(Clone, Copy)]
113struct ExactProv {
114    page_no: usize,
115    bbox: [f64; 4],
116    bottom_left: bool,
117    charspan: [usize; 2],
118}
119
120impl From<&crate::tree::TreeProv> for ExactProv {
121    fn from(p: &crate::tree::TreeProv) -> Self {
122        ExactProv {
123            page_no: p.page_no,
124            bbox: p.bbox,
125            bottom_left: p.bottom_left,
126            charspan: p.charspan,
127        }
128    }
129}
130
131/// Page sizes by page number; the first entry per page wins.
132type PageSizes = std::collections::HashMap<usize, (f64, f64)>;
133
134fn page_sizes(pages: &[(usize, f64, f64)]) -> PageSizes {
135    let mut sizes = PageSizes::with_capacity(pages.len());
136    for &(p, w, h) in pages {
137        sizes.entry(p).or_insert((w, h));
138    }
139    sizes
140}
141
142/// docling-core's `_clamp_provenance_bboxes_to_pages`: each `prov` box of
143/// every item on a known page is clamped to `[0, width] × [0, height]`
144/// (whatever its `coord_origin` — docling clamps the stored numbers), and a
145/// table whose provenance sits on one page has its cell boxes clamped too.
146/// Runs over the finished `texts`, `pictures`, `tables` and
147/// `key_value_items` (the form-field buckets are left as built).
148fn clamp_boxes_to_pages(b: &mut Builder) {
149    if b.pages.is_empty() {
150        return;
151    }
152    // A map, not a scan per box: that was items × pages on long documents.
153    let sizes = page_sizes(&b.pages);
154    for item in &mut b.texts {
155        match item {
156            Item::Text(t) => t.prov.clamp(&sizes),
157            Item::Json(v) => {
158                clamp_item(v, &sizes);
159            }
160        }
161    }
162    for item in b.pictures.iter_mut().chain(b.key_value_items.iter_mut()) {
163        clamp_item(item, &sizes);
164    }
165    for t in &mut b.tables {
166        if let Some(size) = clamp_item(&mut t.item, &sizes) {
167            t.data.clamp(size);
168        }
169    }
170}
171
172/// Clamp `item`'s `prov` boxes; returns the size of the page when the item
173/// sits on exactly one known page — a table's cells are clamped to it.
174fn clamp_item(item: &mut Value, sizes: &PageSizes) -> Option<(f64, f64)> {
175    let size = |page_no: &Value| -> Option<(f64, f64)> {
176        let n = page_no.as_u64()? as usize;
177        sizes.get(&n).copied()
178    };
179    let clamp_bbox = |bbox: &mut Value, (w, h): (f64, f64)| {
180        for (key, hi) in [("l", w), ("r", w), ("t", h), ("b", h)] {
181            if let Some(v) = bbox.get(key).and_then(Value::as_f64) {
182                bbox[key] = json!(round2(v.clamp(0.0, hi.max(0.0))));
183            }
184        }
185    };
186    let mut table_page: Option<Option<(f64, f64)>> = None;
187    if let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) {
188        let mut page_nos: Vec<u64> = Vec::new();
189        for prov in provs.iter_mut() {
190            if let Some(n) = prov.get("page_no").and_then(Value::as_u64) {
191                page_nos.push(n);
192            }
193            let Some(sz) = prov.get("page_no").and_then(size) else {
194                continue;
195            };
196            if let Some(bbox) = prov.get_mut("bbox") {
197                clamp_bbox(bbox, sz);
198            }
199        }
200        page_nos.sort_unstable();
201        page_nos.dedup();
202        if let [only] = page_nos[..] {
203            table_page = Some(size(&json!(only)));
204        }
205    }
206    table_page.flatten()
207}
208
209/// docling-core's `Formatting` model, every field written.
210fn formatting_json(f: &crate::tree::Formatting) -> Value {
211    json!({
212        "bold": f.bold,
213        "italic": f.italic,
214        "underline": f.underline,
215        "strikethrough": f.strikethrough,
216        "script": match f.script {
217            crate::Script::Baseline => "baseline",
218            crate::Script::Sub => "sub",
219            crate::Script::Super => "super",
220        },
221    })
222}
223
224/// docling's `TrackSource` entry: `kind`, the two offsets, then the optional
225/// `identifier` / `voice` (dropped when `None`, as `exclude_none` does).
226fn track_json(t: &crate::tree::TreeTrack) -> Value {
227    let mut m = serde_json::Map::new();
228    m.insert("kind".into(), json!("track"));
229    m.insert("start_time".into(), json!(t.start_time));
230    m.insert("end_time".into(), json!(t.end_time));
231    if let Some(id) = &t.identifier {
232        m.insert("identifier".into(), json!(id));
233    }
234    if let Some(v) = &t.voice {
235        m.insert("voice".into(), json!(v));
236    }
237    Value::Object(m)
238}
239
240/// docling-core's `ImageRef` (pydantic field order: mimetype, dpi, size —
241/// as floats — uri), with the bytes inlined as a `data:` URI — a PNG, like
242/// `ImageRef.from_pil`'s (`pixel_digest::docling_data_uri`).
243fn image_ref_json(img: &crate::PictureImage) -> Value {
244    let (mimetype, uri) = crate::pixel_digest::docling_data_uri(img);
245    json!({
246        "mimetype": mimetype,
247        "dpi": img.dpi,
248        "size": { "width": img.width as f64, "height": img.height as f64 },
249        "uri": uri,
250    })
251}
252
253/// Build the docling-core JSON object for `doc`.
254pub fn to_json(doc: &DoclingDocument) -> Value {
255    build_parts(doc, false).into_value(None)
256}
257
258/// The key a table's `data` is replaced by in [`to_json_typed_tables`]'s
259/// `Value`: the index of its [`TableData`] beside it.
260pub(crate) const TYPED_TABLE: &str = "_typed_table";
261
262/// [`to_json`] for the serializers that walk the `Value` (HTML, Pandoc,
263/// WebVTT), with each table's `data` left typed (#875): the item carries
264/// `{"_typed_table": i}` and the cells are `tables[i]`, read through
265/// [`table_view`]. As a `Value` a table cost two maps of eleven owned keys
266/// per cell (its `table_cells` record and its `grid` copy) — 2.6 GB of an
267/// HTML export's peak on a 640,000-cell CSV. `note_keys` adds the Pandoc
268/// writer's keys ([`to_json_with_notes`]).
269pub(crate) fn to_json_typed_tables(
270    doc: &DoclingDocument,
271    note_keys: bool,
272) -> (Value, Vec<TableData>) {
273    let mut tables = Vec::new();
274    let value = build_parts(doc, note_keys).into_value(Some(&mut tables));
275    (value, tables)
276}
277
278/// [`to_json`] plus the note calls docling's model cannot express: a text
279/// item calling footnotes carries `"_notes": [[offset, text], …]`, a
280/// footnote item that is such a note's body `"_note_body": true` (#538),
281/// a text item that is a link destination `"_anchors": ["id", …]` (#849),
282/// a heading whose text opens with generated numbering `"_number": "1.2"`
283/// (#850), a run kept as a tracked change `"_revision": {"kind":
284/// "insertion" | "deletion", "author", "date"}` (#851),
285/// a picture's image its displayed size `"_display": [width, height]` in
286/// inches (#834), and the document's `metadata` whether or not the JSON
287/// export was asked for it (#836). The Pandoc writer reads these; nothing
288/// is ever exported with them. The tables stay typed, as in
289/// [`to_json_typed_tables`].
290pub(crate) fn to_json_with_notes(doc: &DoclingDocument) -> (Value, Vec<TableData>) {
291    to_json_typed_tables(doc, true)
292}
293
294fn build_parts(doc: &DoclingDocument, note_keys: bool) -> Parts {
295    let mut b = Builder {
296        note_keys,
297        ..Builder::default()
298    };
299    // A backend that built docling's item tree ([`crate::tree`]) has already
300    // decided every parent, child and creation index; serialize that. The
301    // flat nodes are for the other serializers.
302    let body = match &doc.tree {
303        Some(tree) => {
304            // The page map still comes from the flat stream's markers (a
305            // PPTX slide's EMU size): the tree holds items, not pages.
306            for n in &doc.nodes {
307                if let Node::PageInfo {
308                    page_no,
309                    width,
310                    height,
311                } = n
312                {
313                    if *page_no > 0 {
314                        b.pages.push((*page_no, *width as f64, *height as f64));
315                    }
316                }
317            }
318            // docling-core's `validate_misplaced_list_items` runs on every
319            // document it serializes; apply it the same way (keeping the
320            // items' children, which docling-core drops — #586).
321            let mut tree = tree.clone();
322            // Schema 1.11.0's inline runs own their whitespace (#997); a
323            // backend still building trimmed runs gets the old join back in
324            // the runs, as docling-core migrates a pre-1.11 document on load.
325            if !tree.inline_whitespace {
326                tree.separate_legacy_inline_runs();
327            }
328            tree.wrap_misplaced_list_items();
329            b.write_tree(&tree).into_iter().map(Child::json).collect()
330        }
331        None => b.walk_into(&doc.nodes, "#/body"),
332    };
333    b.link_comments();
334    b.link_script_runs();
335
336    // docling-core's `validate_document` — a pydantic `model_validator` every
337    // `DoclingDocument` passes through when a `ConversionResult` (or a
338    // serializer) is built around it — clamps every provenance box, and a
339    // table's cell boxes, into its page's bounds in place
340    // (`_clamp_provenance_bboxes_to_pages`). The JSON docling writes therefore
341    // carries the clamped boxes: a spreadsheet region whose page was sized
342    // `right − left` × `bottom − top` loses its offset, a slide shape hanging
343    // off the slide edge is cut at it. Reproduce that on the finished items.
344    clamp_boxes_to_pages(&mut b);
345
346    let pages = b
347        .pages
348        .iter()
349        .map(|(n, w, h)| {
350            let r2 = |v: f64| (v * 100.0).round() / 100.0;
351            // docling-core's `PageItem` field order: size, image, page_no
352            // (#520 — the image only when page images were generated).
353            let mut page = serde_json::Map::new();
354            page.insert("size".into(), json!({ "width": r2(*w), "height": r2(*h) }));
355            if let Some(img) = doc.page_images.get(n) {
356                page.insert("image".into(), image_ref_json(img));
357            }
358            page.insert("page_no".into(), json!(n));
359            (n.to_string(), Value::Object(page))
360        })
361        .collect::<serde_json::Map<String, Value>>();
362    // docling only emits `field_regions` / `field_items` when a document has
363    // form fields, and places them just before `pages`.
364    let fields = (!b.field_regions.is_empty()).then_some((b.field_regions, b.field_items));
365    Parts {
366        name: doc.name.clone(),
367        // The Pandoc writer (`note_keys`) always gets the metadata, for
368        // its `meta` (#836); the JSON export only when asked.
369        metadata: (doc.metadata_output.in_json() || note_keys)
370            .then(|| doc.metadata.to_json())
371            .filter(|m| m.as_object().is_some_and(|o| !o.is_empty())),
372        origin: json!({
373            "mimetype": "text/plain",
374            "binary_hash": fnv1a(&doc.name),
375            "filename": doc.name,
376        }),
377        furniture: json!({
378            "self_ref": "#/furniture",
379            "children": [],
380            "content_layer": "furniture",
381            "name": "_root_",
382            "label": "unspecified",
383        }),
384        body,
385        groups: b.groups,
386        texts: b.texts,
387        pictures: b.pictures,
388        tables: b.tables,
389        key_value_items: b.key_value_items,
390        fields,
391        pages,
392    }
393}
394
395/// The finished document, before it is a `Value`: one representation
396/// behind both [`to_json`] (a `Value`) and [`write_json`] (bytes, with no
397/// `Value` ever built — the text items stay compact [`Item`]s throughout).
398/// Both produce the same keys in the same order.
399struct Parts {
400    name: String,
401    /// The document's metadata (#679), after `origin`, only when the
402    /// document's output mode asks for it and there is any.
403    metadata: Option<Value>,
404    origin: Value,
405    furniture: Value,
406    /// The body's `children`; the rest of the body object is fixed.
407    body: Vec<Child>,
408    groups: Vec<Value>,
409    texts: Vec<Item>,
410    pictures: Vec<Value>,
411    tables: Vec<TableItem>,
412    key_value_items: Vec<Value>,
413    /// `field_regions` and `field_items`, present only for a document with
414    /// form fields (non-form documents' JSON has neither key).
415    fields: Option<(Vec<Value>, Vec<Value>)>,
416    pages: serde_json::Map<String, Value>,
417}
418
419impl Parts {
420    /// The document `Value`; with `typed`, the tables' `data` goes there
421    /// instead (see [`to_json_typed_tables`]).
422    fn into_value(self, mut typed: Option<&mut Vec<TableData>>) -> Value {
423        // Moved in, never through `json!`, which would deep-copy each array.
424        let mut out = serde_json::Map::with_capacity(15);
425        out.insert("schema_name".into(), "DoclingDocument".into());
426        out.insert("version".into(), SCHEMA_VERSION.into());
427        out.insert("name".into(), Value::String(self.name));
428        out.insert("origin".into(), self.origin);
429        if let Some(m) = self.metadata {
430            out.insert("metadata".into(), m);
431        }
432        out.insert("furniture".into(), self.furniture);
433        out.insert(
434            "body".into(),
435            object([
436                ("self_ref", "#/body".into()),
437                (
438                    "children",
439                    Value::Array(self.body.into_iter().map(Child::into_value).collect()),
440                ),
441                ("content_layer", "body".into()),
442                ("name", "_root_".into()),
443                ("label", "unspecified".into()),
444            ]),
445        );
446        out.insert("groups".into(), Value::Array(self.groups));
447        out.insert(
448            "texts".into(),
449            Value::Array(
450                self.texts
451                    .into_iter()
452                    .enumerate()
453                    .map(|(i, item)| item.into_value(i))
454                    .collect(),
455            ),
456        );
457        out.insert("pictures".into(), Value::Array(self.pictures));
458        out.insert(
459            "tables".into(),
460            Value::Array(
461                self.tables
462                    .into_iter()
463                    .map(|t| match typed.as_deref_mut() {
464                        Some(store) => {
465                            let TableItem { mut item, data } = t;
466                            if let Some(slot) = item.get_mut("data") {
467                                *slot = object([(TYPED_TABLE, store.len().into())]);
468                            }
469                            store.push(data);
470                            item
471                        }
472                        None => t.into_value(),
473                    })
474                    .collect(),
475            ),
476        );
477        out.insert("key_value_items".into(), Value::Array(self.key_value_items));
478        out.insert("form_items".into(), Value::Array(Vec::new()));
479        if let Some((regions, items)) = self.fields {
480            out.insert("field_regions".into(), Value::Array(regions));
481            out.insert("field_items".into(), Value::Array(items));
482        }
483        out.insert("pages".into(), Value::Object(self.pages));
484        Value::Object(out)
485    }
486}
487
488/// [`Parts`] with `extras` — top-level keys a caller appends after
489/// `pages`, as inserting them into [`to_json`]'s `Value` would.
490struct PartsWith<'a>(&'a Parts, &'a [(&'a str, &'a Value)]);
491
492impl serde::Serialize for PartsWith<'_> {
493    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
494        use serde::ser::SerializeMap;
495        let PartsWith(parts, extras) = *self;
496        let mut m = s.serialize_map(Some(
497            13 + 2 * usize::from(parts.fields.is_some())
498                + usize::from(parts.metadata.is_some())
499                + extras.len(),
500        ))?;
501        m.serialize_entry("schema_name", "DoclingDocument")?;
502        m.serialize_entry("version", SCHEMA_VERSION)?;
503        m.serialize_entry("name", &parts.name)?;
504        m.serialize_entry("origin", &parts.origin)?;
505        if let Some(meta) = &parts.metadata {
506            m.serialize_entry("metadata", meta)?;
507        }
508        m.serialize_entry("furniture", &parts.furniture)?;
509        m.serialize_entry("body", &Body(&parts.body))?;
510        m.serialize_entry("groups", &parts.groups)?;
511        m.serialize_entry("texts", &Texts(&parts.texts))?;
512        m.serialize_entry("pictures", &parts.pictures)?;
513        m.serialize_entry("tables", &parts.tables)?;
514        m.serialize_entry("key_value_items", &parts.key_value_items)?;
515        m.serialize_entry("form_items", &[(); 0])?;
516        if let Some((regions, items)) = &parts.fields {
517            m.serialize_entry("field_regions", regions)?;
518            m.serialize_entry("field_items", items)?;
519        }
520        m.serialize_entry("pages", &parts.pages)?;
521        for (k, v) in extras {
522            m.serialize_entry(k, v)?;
523        }
524        m.end()
525    }
526}
527
528/// The body object: fixed keys around its `children`.
529struct Body<'a>(&'a [Child]);
530
531impl serde::Serialize for Body<'_> {
532    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
533        use serde::ser::SerializeMap;
534        let mut m = s.serialize_map(Some(5))?;
535        m.serialize_entry("self_ref", "#/body")?;
536        m.serialize_entry("children", self.0)?;
537        m.serialize_entry("content_layer", "body")?;
538        m.serialize_entry("name", "_root_")?;
539        m.serialize_entry("label", "unspecified")?;
540        m.end()
541    }
542}
543
544/// Write `doc`'s docling JSON to `w` — byte for byte what serializing
545/// [`to_json`]'s `Value` writes (compact, or `pretty` as
546/// `serde_json::to_writer_pretty` indents it), without building that
547/// `Value`. On a long PDF the `Value` is most of the export's memory: ~2.7 KB
548/// per text item (an owned-key map per JSON object) against a few hundred
549/// bytes here.
550pub fn write_json<W: std::io::Write>(
551    doc: &DoclingDocument,
552    w: W,
553    pretty: bool,
554) -> serde_json::Result<()> {
555    write_json_with(doc, w, pretty, &[])
556}
557
558/// [`write_json`] with `extras` appended after `pages` — byte for byte
559/// serializing [`to_json`]'s `Value` with each `value[k] = v` inserted (the
560/// keys must be new to it, as docling-serve's `confidence` is).
561pub fn write_json_with<W: std::io::Write>(
562    doc: &DoclingDocument,
563    w: W,
564    pretty: bool,
565    extras: &[(&str, &Value)],
566) -> serde_json::Result<()> {
567    write_json_with_pictures(doc, w, pretty, extras, true)
568}
569
570/// [`write_json_with`] that, without `picture_images`, leaves every
571/// picture item's `image` out (#1258) — docling-serve's
572/// `image_export_mode=placeholder`, whose PDF pipeline never crops the
573/// pictures (`generate_picture_images` stays off), so its items keep their
574/// `prov`, captions and meta but carry no `ImageRef`. Page images
575/// (`pages[n].image`) are an explicit opt-in of their own and stay.
576pub(crate) fn write_json_with_pictures<W: std::io::Write>(
577    doc: &DoclingDocument,
578    w: W,
579    pretty: bool,
580    extras: &[(&str, &Value)],
581    picture_images: bool,
582) -> serde_json::Result<()> {
583    use serde::Serialize;
584    let mut parts = build_parts(doc, false);
585    if !picture_images {
586        omit_picture_images_in(&mut parts.pictures);
587    }
588    let parts = PartsWith(&parts, extras);
589    if pretty {
590        parts.serialize(&mut serde_json::Serializer::pretty(w))
591    } else {
592        parts.serialize(&mut serde_json::Serializer::new(w))
593    }
594}
595
596/// Drop each picture item's `image` (#1258, see [`write_json_with_pictures`]).
597fn omit_picture_images_in(pictures: &mut [Value]) {
598    for p in pictures {
599        if let Some(obj) = p.as_object_mut() {
600            obj.remove("image");
601        }
602    }
603}
604
605/// [`write_json_with_pictures`]'s rule on an exported document `Value`.
606pub(crate) fn omit_picture_images(doc: &mut Value) {
607    if let Some(pictures) = doc.get_mut("pictures").and_then(Value::as_array_mut) {
608        omit_picture_images_in(pictures);
609    }
610}
611
612/// A DocumentPictureClassifier's predictions as the picture's `meta` — they
613/// land twice, exactly like docling 2.x writes them: the newer
614/// `meta.classification` field (pydantic field order: confidence, created_by,
615/// class_name) and the deprecated-but-still-emitted `classification`
616/// annotation, carried here under an `annotations` key that `add_picture`
617/// lifts onto the item.
618fn classification_meta(classes: &[crate::PictureClass]) -> Value {
619    json!({
620        "classification": {
621            "predictions": classes.iter().map(|c| json!({
622                "confidence": c.confidence as f64,
623                "created_by": "DocumentPictureClassifier",
624                "class_name": c.class_name,
625            })).collect::<Vec<_>>(),
626        },
627        "annotations": [{
628            "kind": "classification",
629            "provenance": "DocumentPictureClassifier",
630            "predicted_classes": classes.iter().map(|c| json!({
631                "class_name": c.class_name,
632                "confidence": c.confidence as f64,
633            })).collect::<Vec<_>>(),
634        }],
635    })
636}
637
638/// The picture-OCR enrichment's text (#645) as docling writes a picture
639/// description: `meta.description` — a `DescriptionMetaField`, pydantic
640/// field order `created_by` (the model, here the OCR engine) then `text` —
641/// plus the deprecated-but-still-emitted `PictureDescriptionData`
642/// annotation (`kind`, `text`, `provenance`), both exactly what
643/// `PictureDescriptionBaseModel` attaches. Carried like
644/// [`classification_meta`]'s: `annotations` is lifted onto the item.
645fn description_meta(desc: &crate::PictureDescription) -> Value {
646    json!({
647        "description": {
648            "created_by": desc.provenance,
649            "text": desc.text,
650        },
651        "annotations": [{
652            "kind": "description",
653            "text": desc.text,
654            "provenance": desc.provenance,
655        }],
656    })
657}
658
659/// A flat picture node's `meta`: the classifier's predictions and/or the
660/// OCR description, merged — `description` precedes `classification` in
661/// `PictureMeta`'s field order (it is inherited from the floating-item
662/// base), the annotations run in the order docling's enrichment pipeline
663/// appends them (classification, then description).
664fn picture_meta(
665    classes: Option<&[crate::PictureClass]>,
666    desc: Option<&crate::PictureDescription>,
667) -> Option<Value> {
668    let mut meta = Map::new();
669    let mut annotations = Vec::new();
670    if let Some(desc) = desc {
671        if desc.is_docling_meta() {
672            // docling's backend-written description: `text` alone, and no
673            // legacy annotation mirrors it (docling#5015).
674            meta.insert("description".into(), json!({ "text": desc.text }));
675        } else {
676            let mut m = description_meta(desc);
677            annotations.push(m["annotations"][0].take());
678            meta.insert("description".into(), m["description"].take());
679        }
680    }
681    if let Some(classes) = classes {
682        let mut m = classification_meta(classes);
683        annotations.insert(0, m["annotations"][0].take());
684        meta.insert("classification".into(), m["classification"].take());
685    }
686    if meta.is_empty() {
687        return None;
688    }
689    meta.insert("annotations".into(), Value::Array(annotations));
690    Some(Value::Object(meta))
691}
692
693/// One table cell of docling's `TableCell`, typed (#875): the table's cells
694/// stay these until the export writes them, rather than a `serde_json` map
695/// of eleven owned keys each — and a second copy of that map in every grid
696/// slot the cell covers. As maps a short numeric CSV cell cost ~7.5 KB of
697/// export peak; typed it is this struct plus its text.
698#[derive(Clone)]
699pub(crate) struct GridCell {
700    row_span: usize,
701    col_span: usize,
702    start_row: usize,
703    end_row: usize,
704    start_col: usize,
705    end_col: usize,
706    text: Box<str>,
707    column_header: bool,
708    row_header: bool,
709    row_section: bool,
710    /// `l t r b`, top-left origin — the backend's `f32` box widened to the
711    /// `f64` a `Value` would hold it as, so both paths print the same digits.
712    bbox: Option<[f64; 4]>,
713    /// A `RichTableCell`'s `ref` to the group holding its content — written
714    /// on `table_cells` only; the `grid` shows the plain cell.
715    cell_ref: Option<Box<Value>>,
716}
717
718impl GridCell {
719    /// docling's empty filler for a grid position no cell covers.
720    fn filler(r: usize, c: usize) -> Self {
721        GridCell {
722            row_span: 1,
723            col_span: 1,
724            start_row: r,
725            end_row: r + 1,
726            start_col: c,
727            end_col: c + 1,
728            text: "".into(),
729            column_header: false,
730            row_header: false,
731            row_section: false,
732            bbox: None,
733            cell_ref: None,
734        }
735    }
736
737    /// The cell as a `Value`: the eleven fields in pydantic order, `bbox`
738    /// appended when the cell carries one, then the rich cell's `ref`
739    /// (`with_ref`, the `table_cells` copy). Built straight into a `Map`
740    /// sized for its entries rather than through `json!`'s doubling map.
741    fn to_value(&self, with_ref: bool) -> Value {
742        let mut m = serde_json::Map::with_capacity(13);
743        m.insert("row_span".into(), self.row_span.into());
744        m.insert("col_span".into(), self.col_span.into());
745        m.insert("start_row_offset_idx".into(), self.start_row.into());
746        m.insert("end_row_offset_idx".into(), self.end_row.into());
747        m.insert("start_col_offset_idx".into(), self.start_col.into());
748        m.insert("end_col_offset_idx".into(), self.end_col.into());
749        m.insert("text".into(), Value::String(self.text.to_string()));
750        m.insert("column_header".into(), self.column_header.into());
751        m.insert("row_header".into(), self.row_header.into());
752        m.insert("row_section".into(), self.row_section.into());
753        m.insert("fillable".into(), false.into());
754        if let Some([l, t, r, b]) = self.bbox {
755            m.insert(
756                "bbox".into(),
757                object([
758                    ("l", l.into()),
759                    ("t", t.into()),
760                    ("r", r.into()),
761                    ("b", b.into()),
762                    ("coord_origin", "TOPLEFT".into()),
763                ]),
764            );
765        }
766        if let Some(r) = self.cell_ref.as_deref().filter(|_| with_ref) {
767            m.insert("ref".into(), r.clone());
768        }
769        Value::Object(m)
770    }
771}
772
773/// [`GridCell::to_value`] written in place: the same keys in the same order.
774struct CellOut<'a>(&'a GridCell, bool);
775
776impl serde::Serialize for CellOut<'_> {
777    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
778        use serde::ser::SerializeMap;
779        let CellOut(c, with_ref) = *self;
780        let cell_ref = c.cell_ref.as_deref().filter(|_| with_ref);
781        let mut m = s.serialize_map(Some(
782            11 + usize::from(c.bbox.is_some()) + usize::from(cell_ref.is_some()),
783        ))?;
784        m.serialize_entry("row_span", &c.row_span)?;
785        m.serialize_entry("col_span", &c.col_span)?;
786        m.serialize_entry("start_row_offset_idx", &c.start_row)?;
787        m.serialize_entry("end_row_offset_idx", &c.end_row)?;
788        m.serialize_entry("start_col_offset_idx", &c.start_col)?;
789        m.serialize_entry("end_col_offset_idx", &c.end_col)?;
790        m.serialize_entry("text", &c.text)?;
791        m.serialize_entry("column_header", &c.column_header)?;
792        m.serialize_entry("row_header", &c.row_header)?;
793        m.serialize_entry("row_section", &c.row_section)?;
794        m.serialize_entry("fillable", &false)?;
795        if let Some(b) = c.bbox {
796            struct Bbox([f64; 4]);
797            impl serde::Serialize for Bbox {
798                fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
799                    let mut m = s.serialize_map(Some(5))?;
800                    for (k, v) in ["l", "t", "r", "b"].iter().zip(self.0) {
801                        m.serialize_entry(k, &v)?;
802                    }
803                    m.serialize_entry("coord_origin", "TOPLEFT")?;
804                    m.end()
805                }
806            }
807            m.serialize_entry("bbox", &Bbox(b))?;
808        }
809        if let Some(r) = cell_ref {
810            m.serialize_entry("ref", r)?;
811        }
812        m.end()
813    }
814}
815
816/// What a `grid` position shows: the cell covering it (an index into
817/// [`TableData::cells`] — docling repeats the whole cell at every position
818/// it spans), docling's empty filler cell, or `null`.
819#[derive(Clone, Copy)]
820enum GridSlot {
821    Cell(usize),
822    Filler,
823    Null,
824}
825
826/// docling's `TableData` for a table: `table_cells`, `num_rows`/`num_cols`
827/// and the `grid` that repeats each cell at every position it covers —
828/// typed (#875), each cell stored once and the grid as slots pointing at
829/// it, so a table costs its cells rather than a map per cell and per slot.
830/// Shared by table items and a chart picture's `meta.tabular_chart.chart_data`.
831pub(crate) struct TableData {
832    cells: Vec<GridCell>,
833    num_rows: usize,
834    num_cols: usize,
835    /// Row-major, `num_rows × num_cols`.
836    grid: Vec<GridSlot>,
837}
838
839/// One position of docling's `TableData.grid`, as the DocLang tree
840/// serializer reads it (`doclang_tree.rs`): the covering cell's anchor,
841/// text and header roles — an empty filler where no cell covers the
842/// position, which is what docling's computed `grid` holds there.
843pub(crate) struct GridPos<'a> {
844    pub(crate) start_row: usize,
845    pub(crate) start_col: usize,
846    pub(crate) text: &'a str,
847    pub(crate) column_header: bool,
848    pub(crate) row_header: bool,
849    pub(crate) row_section: bool,
850}
851
852/// [`TableData`] of a backend-built tree's table (raw cell text).
853pub(crate) fn raw_table_data(t: &Table) -> TableData {
854    table_data_with(t, true)
855}
856
857impl TableData {
858    /// `(num_rows, num_cols)`.
859    pub(crate) fn dims(&self) -> (usize, usize) {
860        (self.num_rows, self.num_cols)
861    }
862
863    /// Whether `table_cells` holds any cell.
864    pub(crate) fn has_cells(&self) -> bool {
865        !self.cells.is_empty()
866    }
867
868    /// The grid position `(r, c)`.
869    pub(crate) fn at(&self, r: usize, c: usize) -> GridPos<'_> {
870        match self.grid[r * self.num_cols + c] {
871            GridSlot::Cell(i) => {
872                let cell = &self.cells[i];
873                GridPos {
874                    start_row: cell.start_row,
875                    start_col: cell.start_col,
876                    text: &cell.text,
877                    column_header: cell.column_header,
878                    row_header: cell.row_header,
879                    row_section: cell.row_section,
880                }
881            }
882            GridSlot::Filler | GridSlot::Null => GridPos {
883                start_row: r,
884                start_col: c,
885                text: "",
886                column_header: false,
887                row_header: false,
888                row_section: false,
889            },
890        }
891    }
892}
893
894impl TableData {
895    fn slot_cell(
896        &self,
897        slot: GridSlot,
898        r: usize,
899        c: usize,
900    ) -> Option<std::borrow::Cow<'_, GridCell>> {
901        match slot {
902            GridSlot::Cell(i) => Some(std::borrow::Cow::Borrowed(&self.cells[i])),
903            GridSlot::Filler => Some(std::borrow::Cow::Owned(GridCell::filler(r, c))),
904            GridSlot::Null => None,
905        }
906    }
907
908    fn into_value(self) -> Value {
909        let cells = Value::Array(self.cells.iter().map(|c| c.to_value(true)).collect());
910        let mut data = serde_json::Map::with_capacity(5);
911        data.insert("table_cells".into(), cells);
912        data.insert("num_rows".into(), self.num_rows.into());
913        data.insert("num_cols".into(), self.num_cols.into());
914        data.insert("orientation".into(), "rot_0".into());
915        let mut rows = Vec::with_capacity(self.num_rows);
916        for r in 0..self.num_rows {
917            let mut row = Vec::with_capacity(self.num_cols);
918            for c in 0..self.num_cols {
919                let slot = self.grid[r * self.num_cols + c];
920                row.push(match self.slot_cell(slot, r, c) {
921                    Some(cell) => cell.to_value(false),
922                    None => Value::Null,
923                });
924            }
925            rows.push(Value::Array(row));
926        }
927        data.insert("grid".into(), Value::Array(rows));
928        Value::Object(data)
929    }
930
931    /// docling's page clamp ([`clamp_boxes_to_pages`]) on every cell box —
932    /// once per cell: the grid's copies are the same cells.
933    fn clamp(&mut self, (w, h): (f64, f64)) {
934        for bbox in self.cells.iter_mut().filter_map(|c| c.bbox.as_mut()) {
935            for (v, hi) in bbox.iter_mut().zip([w, h, w, h]) {
936                // A non-finite coordinate is `null` in the JSON, which the
937                // clamp leaves alone.
938                if v.is_finite() {
939                    *v = round2(v.clamp(0.0, hi.max(0.0)));
940                }
941            }
942        }
943    }
944}
945
946impl serde::Serialize for TableData {
947    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
948        use serde::ser::{SerializeMap, SerializeSeq};
949        struct Cells<'a>(&'a [GridCell]);
950        impl serde::Serialize for Cells<'_> {
951            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
952                let mut seq = s.serialize_seq(Some(self.0.len()))?;
953                for c in self.0 {
954                    seq.serialize_element(&CellOut(c, true))?;
955                }
956                seq.end()
957            }
958        }
959        struct Row<'a>(&'a TableData, usize);
960        impl serde::Serialize for Row<'_> {
961            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
962                let Row(t, r) = *self;
963                let mut seq = s.serialize_seq(Some(t.num_cols))?;
964                for c in 0..t.num_cols {
965                    match t.slot_cell(t.grid[r * t.num_cols + c], r, c) {
966                        Some(cell) => seq.serialize_element(&CellOut(&cell, false))?,
967                        None => seq.serialize_element(&())?,
968                    }
969                }
970                seq.end()
971            }
972        }
973        struct Grid<'a>(&'a TableData);
974        impl serde::Serialize for Grid<'_> {
975            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
976                let mut seq = s.serialize_seq(Some(self.0.num_rows))?;
977                for r in 0..self.0.num_rows {
978                    seq.serialize_element(&Row(self.0, r))?;
979                }
980                seq.end()
981            }
982        }
983        let mut m = s.serialize_map(Some(5))?;
984        m.serialize_entry("table_cells", &Cells(&self.cells))?;
985        m.serialize_entry("num_rows", &self.num_rows)?;
986        m.serialize_entry("num_cols", &self.num_cols)?;
987        m.serialize_entry("orientation", "rot_0")?;
988        m.serialize_entry("grid", &Grid(self))?;
989        m.end()
990    }
991}
992
993/// A table cell as the `Value`-walking serializers read it — from a typed
994/// [`GridCell`] or from a `table_cells` entry of docling JSON (a document
995/// Python docling wrote, read by [`crate::pandoc::from_docling_json`]): a
996/// missing field reads as `0` / `""` / `false`, like the `Value` getters
997/// those serializers used.
998pub(crate) struct CellView<'a> {
999    pub start_row: usize,
1000    pub end_row: usize,
1001    pub start_col: usize,
1002    pub end_col: usize,
1003    pub row_span: usize,
1004    pub col_span: usize,
1005    pub text: &'a str,
1006    pub column_header: bool,
1007    pub row_header: bool,
1008    pub row_section: bool,
1009    /// A rich cell's `ref.$ref`.
1010    pub cell_ref: Option<&'a str>,
1011}
1012
1013/// A table's `data` as [`CellView`]s: `num_rows`, `num_cols` and the
1014/// `table_cells` (the derived `grid` is not read).
1015pub(crate) struct TableView<'a> {
1016    pub num_rows: usize,
1017    pub num_cols: usize,
1018    pub cells: Vec<CellView<'a>>,
1019}
1020
1021/// The [`TableView`] of a table item's `data`: the typed table it names
1022/// ([`TYPED_TABLE`], an index into `typed`), or the JSON's own fields.
1023pub(crate) fn table_view<'a>(data: &'a Value, typed: &'a [TableData]) -> TableView<'a> {
1024    let ref_of = |r: Option<&'a Value>| r.and_then(|r| r.get("$ref")).and_then(Value::as_str);
1025    if let Some(t) = data
1026        .get(TYPED_TABLE)
1027        .and_then(Value::as_u64)
1028        .and_then(|i| typed.get(i as usize))
1029    {
1030        return TableView {
1031            num_rows: t.num_rows,
1032            num_cols: t.num_cols,
1033            cells: t
1034                .cells
1035                .iter()
1036                .map(|c| CellView {
1037                    start_row: c.start_row,
1038                    end_row: c.end_row,
1039                    start_col: c.start_col,
1040                    end_col: c.end_col,
1041                    row_span: c.row_span,
1042                    col_span: c.col_span,
1043                    text: &c.text,
1044                    column_header: c.column_header,
1045                    row_header: c.row_header,
1046                    row_section: c.row_section,
1047                    cell_ref: ref_of(c.cell_ref.as_deref()),
1048                })
1049                .collect(),
1050        };
1051    }
1052    let num = |v: &Value, k: &str| v.get(k).and_then(Value::as_u64).unwrap_or(0) as usize;
1053    let flag = |v: &Value, k: &str| v.get(k).and_then(Value::as_bool).unwrap_or(false);
1054    TableView {
1055        num_rows: num(data, "num_rows"),
1056        num_cols: num(data, "num_cols"),
1057        cells: data
1058            .get("table_cells")
1059            .and_then(Value::as_array)
1060            .into_iter()
1061            .flatten()
1062            .map(|c| CellView {
1063                start_row: num(c, "start_row_offset_idx"),
1064                end_row: num(c, "end_row_offset_idx"),
1065                start_col: num(c, "start_col_offset_idx"),
1066                end_col: num(c, "end_col_offset_idx"),
1067                row_span: num(c, "row_span"),
1068                col_span: num(c, "col_span"),
1069                text: c.get("text").and_then(Value::as_str).unwrap_or(""),
1070                column_header: flag(c, "column_header"),
1071                row_header: flag(c, "row_header"),
1072                row_section: flag(c, "row_section"),
1073                cell_ref: ref_of(c.get("ref")),
1074            })
1075            .collect(),
1076    }
1077}
1078
1079/// A `tables` entry: the item's JSON with a `null` stand-in under `data`
1080/// — so every edit of the item (children, content layer, comment
1081/// back-refs) works on the `Value` as before and keeps its key order —
1082/// and the typed [`TableData`] that takes the stand-in's place when the
1083/// item is written or turned into a `Value`.
1084struct TableItem {
1085    item: Value,
1086    data: TableData,
1087}
1088
1089impl TableItem {
1090    fn into_value(self) -> Value {
1091        let TableItem { mut item, data } = self;
1092        if let Some(slot) = item.get_mut("data") {
1093            *slot = data.into_value();
1094        }
1095        item
1096    }
1097}
1098
1099impl serde::Serialize for TableItem {
1100    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1101        use serde::ser::SerializeMap;
1102        let Value::Object(obj) = &self.item else {
1103            return self.item.serialize(s);
1104        };
1105        let mut m = s.serialize_map(Some(obj.len()))?;
1106        for (k, v) in obj {
1107            if k == "data" {
1108                m.serialize_entry(k, &self.data)?;
1109            } else {
1110                m.serialize_entry(k, v)?;
1111            }
1112        }
1113        m.end()
1114    }
1115}
1116
1117/// `TableData` from a table whose cell text is Markdown-flavoured (the flat
1118/// nodes: escapes to undo, GFM hard-break markers to strip).
1119fn table_data(t: &Table) -> TableData {
1120    table_data_with(t, false)
1121}
1122
1123/// `TableData`; with `raw` the cell text is docling's own raw cell text (a
1124/// backend-built tree) and is written verbatim.
1125fn table_data_with(t: &Table, raw: bool) -> TableData {
1126    let cell_text = |s: &str| -> Box<str> {
1127        if raw {
1128            s.into()
1129        } else {
1130            unescape_text(&crate::markdown::strip_hard_breaks(s)).into()
1131        }
1132    };
1133    let widen = |b: [f32; 4]| b.map(f64::from);
1134    let mut num_rows = t.rows.len();
1135    let mut num_cols = t.rows.iter().map(Vec::len).max().unwrap_or(0);
1136    // Rectangular `rows` are the grid, and cells reaching past it are
1137    // clipped — docling's own `TableData.grid` on a USPTO table whose
1138    // replicated cells outrun `num_cols`, or an HTML rowspan past the last
1139    // row. Ragged rows are no grid at all: a backend that compacts them
1140    // (xlsx `skip_empty_cells`, #271) keeps the true offsets in first-class
1141    // cells, so there the grid spans every cell's extent and the omitted
1142    // positions come back as docling's empty filler cells.
1143    let ragged = t.rows.iter().any(|r| r.len() != num_cols);
1144    if let Some(first_class) = t.cells.as_ref().filter(|c| ragged && !c.is_empty()) {
1145        let (mut rows, mut cols) = (num_rows, num_cols);
1146        for c in first_class {
1147            rows = rows.max(c.start_row.saturating_add(c.row_span));
1148            cols = cols.max(c.start_col.saturating_add(c.col_span));
1149        }
1150        // A cell whose declared extent reaches past the cell budget (#861)
1151        // does not size the slot map; the grid stays the rows' own and the
1152        // cell is clipped to it, like any other cell reaching past the grid.
1153        if rows.saturating_mul(cols) <= crate::limits::max_table_cells() {
1154            num_rows = rows;
1155            num_cols = cols;
1156        }
1157    }
1158    let mut cells = Vec::new();
1159    // Grid slot → the cell covering it, row-major — no per-slot copy and
1160    // nothing hashed.
1161    let mut grid: Vec<GridSlot>;
1162    if let Some(first_class) = t.cells.as_ref().filter(|c| !c.is_empty()) {
1163        // A position no cell covers is docling's empty filler cell.
1164        grid = vec![GridSlot::Filler; num_rows * num_cols];
1165        cells.reserve(first_class.len());
1166        for c in first_class {
1167            let idx = cells.len();
1168            cells.push(GridCell {
1169                row_span: c.row_span,
1170                col_span: c.col_span,
1171                start_row: c.start_row,
1172                end_row: c.start_row + c.row_span,
1173                start_col: c.start_col,
1174                end_col: c.start_col + c.col_span,
1175                text: cell_text(&c.text),
1176                column_header: c.column_header,
1177                row_header: c.row_header,
1178                row_section: c.row_section,
1179                bbox: c.bbox.map(widen),
1180                cell_ref: None,
1181            });
1182            for r in c.start_row..(c.start_row + c.row_span).min(num_rows) {
1183                for k in c.start_col..(c.start_col + c.col_span).min(num_cols) {
1184                    grid[r * num_cols + k] = GridSlot::Cell(idx);
1185                }
1186            }
1187        }
1188    } else {
1189        grid = vec![GridSlot::Null; num_rows * num_cols];
1190        let s = t.structure.as_ref();
1191        let flag = |grid: Option<&Vec<Vec<bool>>>, r: usize, c: usize| -> bool {
1192            grid.and_then(|g| g.get(r))
1193                .and_then(|row| row.get(c))
1194                .copied()
1195                .unwrap_or(false)
1196        };
1197        let anchor_of = |r: usize, c: usize| -> (usize, usize) {
1198            let (mut r0, mut c0) = (r, c);
1199            while c0 > 0 && flag(s.map(|s| &s.col_continuation), r, c0) {
1200                c0 -= 1;
1201            }
1202            while r0 > 0 && flag(s.map(|s| &s.row_continuation), r0, c0) {
1203                r0 -= 1;
1204            }
1205            (r0, c0)
1206        };
1207        // Each slot's anchor, computed once; the anchor's extent is the
1208        // farthest slot that resolves to it.
1209        let anchors: Vec<(usize, usize)> = (0..num_rows)
1210            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1211            .map(|(r, c)| anchor_of(r, c))
1212            .collect();
1213        let mut extent: Vec<(usize, usize)> = (0..num_rows)
1214            .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1215            .collect();
1216        for (i, &(ar, ac)) in anchors.iter().enumerate() {
1217            let (r, c) = (i / num_cols.max(1), i % num_cols.max(1));
1218            let e = &mut extent[ar * num_cols + ac];
1219            e.0 = e.0.max(r);
1220            e.1 = e.1.max(c);
1221        }
1222        // An anchor's cell, by slot, once it is created (anchors precede
1223        // the slots they cover in row-major order).
1224        let mut anchor_cell: Vec<Option<usize>> = vec![None; num_rows * num_cols];
1225        for (r, row) in t.rows.iter().enumerate() {
1226            for c in 0..num_cols {
1227                let (ar, ac) = anchors[r * num_cols + c];
1228                if (ar, ac) == (r, c) {
1229                    let (er, ec) = extent[r * num_cols + c];
1230                    let text = row.get(c).map(|s| cell_text(s)).unwrap_or_default();
1231                    let column_header = match s.filter(|s| !s.col_header.is_empty()) {
1232                        Some(s) => flag(Some(&s.col_header), r, c),
1233                        None => r == 0,
1234                    };
1235                    anchor_cell[r * num_cols + c] = Some(cells.len());
1236                    cells.push(GridCell {
1237                        row_span: er - r + 1,
1238                        col_span: ec - c + 1,
1239                        start_row: r,
1240                        end_row: er + 1,
1241                        start_col: c,
1242                        end_col: ec + 1,
1243                        text,
1244                        column_header,
1245                        row_header: flag(s.map(|s| &s.row_header), r, c),
1246                        row_section: false,
1247                        bbox: None,
1248                        cell_ref: None,
1249                    });
1250                }
1251                if let Some(i) = anchor_cell[ar * num_cols + ac] {
1252                    grid[r * num_cols + c] = GridSlot::Cell(i);
1253                }
1254            }
1255        }
1256    }
1257    TableData {
1258        cells,
1259        num_rows,
1260        num_cols,
1261        grid,
1262    }
1263}
1264
1265/// An item's `prov` array as the builder holds it: empty, or docling's one
1266/// `ProvenanceItem` — kept typed so a text item need not be a `Value` until
1267/// it is written (see [`Item`]).
1268#[derive(Clone, Copy)]
1269enum ProvSlot {
1270    None,
1271    One {
1272        page_no: usize,
1273        /// `l t r b`, already rounded to 2 decimals.
1274        bbox: [f64; 4],
1275        bottom_left: bool,
1276        charspan: [usize; 2],
1277    },
1278}
1279
1280impl ProvSlot {
1281    fn origin(bottom_left: bool) -> &'static str {
1282        if bottom_left {
1283            "BOTTOMLEFT"
1284        } else {
1285            "TOPLEFT"
1286        }
1287    }
1288
1289    /// The `prov` array: `page_no`, `bbox` (`l t r b` + `coord_origin`) and
1290    /// `charspan`, in pydantic field order.
1291    fn to_value(self) -> Value {
1292        let ProvSlot::One {
1293            page_no,
1294            bbox: [l, t, r, b],
1295            bottom_left,
1296            charspan,
1297        } = self
1298        else {
1299            return Value::Array(Vec::new());
1300        };
1301        let bbox = object([
1302            ("l", l.into()),
1303            ("t", t.into()),
1304            ("r", r.into()),
1305            ("b", b.into()),
1306            ("coord_origin", Self::origin(bottom_left).into()),
1307        ]);
1308        let span = Value::Array(vec![charspan[0].into(), charspan[1].into()]);
1309        Value::Array(vec![object([
1310            ("page_no", page_no.into()),
1311            ("bbox", bbox),
1312            ("charspan", span),
1313        ])])
1314    }
1315
1316    /// docling's page clamp ([`clamp_boxes_to_pages`]) on the typed box.
1317    fn clamp(&mut self, sizes: &PageSizes) {
1318        if let ProvSlot::One { page_no, bbox, .. } = self {
1319            if let Some(&(w, h)) = sizes.get(page_no) {
1320                for (v, hi) in bbox.iter_mut().zip([w, h, w, h]) {
1321                    // A non-finite coordinate is `null` in the JSON, which the
1322                    // clamp leaves alone.
1323                    if v.is_finite() {
1324                        *v = round2(v.clamp(0.0, hi.max(0.0)));
1325                    }
1326                }
1327            }
1328        }
1329    }
1330}
1331
1332impl serde::Serialize for ProvSlot {
1333    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1334        use serde::ser::{SerializeMap, SerializeSeq};
1335        let ProvSlot::One {
1336            page_no,
1337            bbox: [l, t, r, b],
1338            bottom_left,
1339            charspan,
1340        } = *self
1341        else {
1342            return s.serialize_seq(Some(0))?.end();
1343        };
1344        struct Bbox([f64; 4], &'static str);
1345        impl serde::Serialize for Bbox {
1346            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1347                let mut m = s.serialize_map(Some(5))?;
1348                for (k, v) in ["l", "t", "r", "b"].iter().zip(self.0) {
1349                    m.serialize_entry(k, &v)?;
1350                }
1351                m.serialize_entry("coord_origin", self.1)?;
1352                m.end()
1353            }
1354        }
1355        struct Entry(usize, Bbox, [usize; 2]);
1356        impl serde::Serialize for Entry {
1357            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1358                let mut m = s.serialize_map(Some(3))?;
1359                m.serialize_entry("page_no", &self.0)?;
1360                m.serialize_entry("bbox", &self.1)?;
1361                m.serialize_entry("charspan", &self.2)?;
1362                m.end()
1363            }
1364        }
1365        let mut seq = s.serialize_seq(Some(1))?;
1366        seq.serialize_element(&Entry(
1367            page_no,
1368            Bbox([l, t, r, b], Self::origin(bottom_left)),
1369            charspan,
1370        ))?;
1371        seq.end()
1372    }
1373}
1374
1375/// The plain text item — docling's `TextItem` with no children, on the body
1376/// layer, `orig` equal to `text` and no extra fields: what a PDF's text layer
1377/// is made of, millions of times over on a long document. As a `Value` each
1378/// cost ~2.7 KB (a map of owned keys per object); typed it is ~150 bytes, and
1379/// it serializes to exactly the same JSON. Its `self_ref` is its position
1380/// (`#/texts/{i}`), so it is not stored.
1381struct TextItem {
1382    parent: Box<str>,
1383    label: Box<str>,
1384    prov: ProvSlot,
1385    text: Box<str>,
1386}
1387
1388impl TextItem {
1389    fn into_value(self, index: usize) -> Value {
1390        let text = String::from(self.text);
1391        object([
1392            ("self_ref", Value::String(format!("#/texts/{index}"))),
1393            ("parent", ref_value(self.parent)),
1394            ("children", Value::Array(Vec::new())),
1395            ("content_layer", "body".into()),
1396            ("label", Value::String(self.label.into())),
1397            ("prov", self.prov.to_value()),
1398            ("orig", Value::String(text.clone())),
1399            ("text", Value::String(text)),
1400        ])
1401    }
1402}
1403
1404/// A `texts` entry: the compact [`TextItem`] until something needs to edit
1405/// it as JSON (a nested list's children, a content-layer move, a comment
1406/// back-ref), then the `Value` it stands for. Both boxed: a slot is 16 bytes.
1407enum Item {
1408    Text(Box<TextItem>),
1409    Json(Box<Value>),
1410}
1411
1412impl Item {
1413    fn json(v: Value) -> Self {
1414        Item::Json(Box::new(v))
1415    }
1416
1417    /// The item at `texts[index]` as an editable `Value`, converting a
1418    /// [`TextItem`] in place.
1419    fn value_mut(&mut self, index: usize) -> &mut Value {
1420        if let Item::Text(t) = self {
1421            let t = std::mem::replace(
1422                t,
1423                Box::new(TextItem {
1424                    parent: "".into(),
1425                    label: "".into(),
1426                    prov: ProvSlot::None,
1427                    text: "".into(),
1428                }),
1429            );
1430            *self = Item::json(t.into_value(index));
1431        }
1432        match self {
1433            Item::Json(v) => v,
1434            Item::Text(_) => unreachable!("converted above"),
1435        }
1436    }
1437
1438    fn into_value(self, index: usize) -> Value {
1439        match self {
1440            Item::Text(t) => t.into_value(index),
1441            Item::Json(v) => *v,
1442        }
1443    }
1444}
1445
1446/// The `texts` array, serialized in place.
1447struct Texts<'a>(&'a [Item]);
1448
1449impl serde::Serialize for Texts<'_> {
1450    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1451        use serde::ser::{SerializeMap, SerializeSeq};
1452        struct Text<'a>(usize, &'a TextItem);
1453        impl serde::Serialize for Text<'_> {
1454            fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1455                let Text(i, t) = *self;
1456                let mut m = s.serialize_map(Some(8))?;
1457                m.serialize_entry("self_ref", &format_args!("#/texts/{i}"))?;
1458                m.serialize_entry("parent", &Child::Ref(t.parent.clone()))?;
1459                m.serialize_entry("children", &[(); 0])?;
1460                m.serialize_entry("content_layer", "body")?;
1461                m.serialize_entry("label", &t.label)?;
1462                m.serialize_entry("prov", &t.prov)?;
1463                m.serialize_entry("orig", &t.text)?;
1464                m.serialize_entry("text", &t.text)?;
1465                m.end()
1466            }
1467        }
1468        let mut seq = s.serialize_seq(Some(self.0.len()))?;
1469        for (i, item) in self.0.iter().enumerate() {
1470            match item {
1471                Item::Text(t) => seq.serialize_element(&Text(i, t))?,
1472                Item::Json(v) => seq.serialize_element(v)?,
1473            }
1474        }
1475        seq.end()
1476    }
1477}
1478
1479/// An entry of a `children` list as the walk collects it: a `{"$ref": …}`
1480/// held as its target string (a body of millions of refs costs ~40 bytes
1481/// each, not a ~270-byte `Value` map), or any other JSON.
1482enum Child {
1483    Ref(Box<str>),
1484    Json(Box<Value>),
1485}
1486
1487impl Child {
1488    fn json(v: Value) -> Self {
1489        Child::Json(Box::new(v))
1490    }
1491
1492    fn into_value(self) -> Value {
1493        match self {
1494            Child::Ref(r) => ref_value(r),
1495            Child::Json(v) => *v,
1496        }
1497    }
1498}
1499
1500impl serde::Serialize for Child {
1501    fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
1502        use serde::ser::SerializeMap;
1503        match self {
1504            Child::Ref(r) => {
1505                let mut m = s.serialize_map(Some(1))?;
1506                m.serialize_entry("$ref", r)?;
1507                m.end()
1508            }
1509            Child::Json(v) => v.serialize(s),
1510        }
1511    }
1512}
1513
1514fn round2(v: f64) -> f64 {
1515    (v * 100.0).round() / 100.0
1516}
1517
1518#[derive(Default)]
1519struct Builder {
1520    /// Write the internal `_notes` / `_note_body` keys of tree text items
1521    /// ([`crate::tree::TreeItem::notes`]) — for the Pandoc writer only
1522    /// ([`to_json_with_notes`]); docling's JSON has no such fields.
1523    note_keys: bool,
1524    texts: Vec<Item>,
1525    groups: Vec<Value>,
1526    tables: Vec<TableItem>,
1527    pictures: Vec<Value>,
1528    field_regions: Vec<Value>,
1529    field_items: Vec<Value>,
1530    key_value_items: Vec<Value>,
1531    /// Pages seen so far (`page_no`, width, height in points) — from the
1532    /// [`Node::PageInfo`] markers the PDF paths emit; empty for every other
1533    /// backend, which keeps their JSON byte-identical (`"pages": {}`, no prov).
1534    pages: Vec<(usize, f64, f64)>,
1535    /// The page the walk is currently on (0 before the first marker).
1536    cur_page: usize,
1537    cur_w: f64,
1538    cur_h: f64,
1539    /// The enclosing [`Node::Located`] wrapper's 0–511 grid box, waiting to be
1540    /// consumed as the next item's provenance.
1541    pending_loc: Option<[u16; 4]>,
1542    /// The enclosing [`Node::Prov`] wrapper's (or the tree item's) exact
1543    /// provenance, which takes precedence over the grid box.
1544    pending_exact: Option<ExactProv>,
1545    /// The enclosing [`Node::Track`]'s timing, for the text item it wraps
1546    /// (#614).
1547    pending_track: Option<(crate::tree::TreeTrack, String)>,
1548    /// [`Node::Anchor`]s met since the last text item (#852): that item's
1549    /// `_anchors` on the Pandoc path.
1550    pending_anchors: Vec<String>,
1551    /// `$ref`s an item wants placed in its parent's `children` *before* its
1552    /// own — a chart's caption item, which docling's office backends add to
1553    /// the container ahead of the picture that references it.
1554    pending_siblings: Vec<Value>,
1555    /// `$ref`s an item wants placed in its parent's `children` right *after*
1556    /// its own — an HTML `<figure>`-wrapped table's caption
1557    /// ([`CaptionParent::ContainerAfter`]).
1558    pending_after: Vec<Value>,
1559    /// Caption `$ref`s that hang off `#/body` while their item sits deeper
1560    /// ([`CaptionParent::Body`]): docling appends them to the body's children
1561    /// as they are created, so they follow the top-level item being walked.
1562    pending_body: Vec<Value>,
1563    /// What each [`Node::CommentSection`] is referenced by, in document order —
1564    /// its group `$ref`, or its note text's when the section says so. The index
1565    /// is what a [`Node::Commented`] annotation carries.
1566    comment_groups: Vec<String>,
1567    /// The last `comment_section` group emitted, as `(name, self_ref)`: a
1568    /// following section of the same name adds its note to that group rather
1569    /// than opening another — one `comment-{sheet}-{cell}` group holds every
1570    /// message of a threaded comment (docling#4353).
1571    last_comment_section: Option<(String, String)>,
1572    /// Annotated items awaiting their refs: comments are usually emitted
1573    /// *after* the body they annotate (docx appends them), so the link is
1574    /// patched in once the whole document has been walked.
1575    pending_comments: Vec<(String, Vec<usize>)>,
1576    /// The items the script-position stage marked (#1005), with their runs
1577    /// and the label and link the runs take: docling adds the inline groups
1578    /// once the document is assembled, so their groups and run items come
1579    /// after every other item.
1580    pending_scripts: Vec<(String, Vec<crate::ScriptRun>, String)>,
1581    /// The last `#/texts/N` index created: the item a following
1582    /// [`Node::ProvContinuation`] belongs to (#1127).
1583    last_text: Option<usize>,
1584    /// [`Node::ProvContinuation`] fragments waiting for their page. The
1585    /// marker stands right after its item, before the page it is on.
1586    pending_continuations: Vec<PendingContinuation>,
1587}
1588
1589/// A [`Node::ProvContinuation`] the JSON walk met, waiting for its page.
1590struct PendingContinuation {
1591    /// The `#/texts/N` index of the item it continues.
1592    item: usize,
1593    /// Page markers still to pass before the fragment's page.
1594    skip: usize,
1595    location: [u16; 4],
1596    prev_end: usize,
1597    span: [usize; 2],
1598}
1599
1600impl Builder {
1601    /// Consume the pending location (if any) into a docling `prov` array: the
1602    /// 0-511 grid denormalized against the current page into BOTTOMLEFT
1603    /// points, rounded to 2 decimals like docling's own export. `char_len` is
1604    /// the item's text length in characters (0 for tables and pictures, whose
1605    /// charspan docling emits as `[0, 0]`).
1606    fn take_prov(&mut self, char_len: usize) -> Value {
1607        self.take_prov_slot(char_len).to_value()
1608    }
1609
1610    /// [`Self::take_prov`], typed.
1611    fn take_prov_slot(&mut self, char_len: usize) -> ProvSlot {
1612        let prov = self.prov_slot(char_len, false);
1613        self.pending_exact = None;
1614        self.pending_loc = None;
1615        prov
1616    }
1617
1618    /// The pending provenance without consuming it. An exact [`Node::Prov`]
1619    /// box wins over the grid; its own `charspan` is used unless
1620    /// `span_over_text` asks for `[0, char_len]` (a chart caption's span
1621    /// covers the caption text where the chart's is `[0, 0]`).
1622    fn prov_slot(&self, char_len: usize, span_over_text: bool) -> ProvSlot {
1623        let r2 = round2;
1624        if let Some(ExactProv {
1625            page_no,
1626            bbox: [l, t, r, b],
1627            bottom_left,
1628            charspan,
1629        }) = self.pending_exact
1630        {
1631            let charspan = if span_over_text {
1632                [0, char_len]
1633            } else {
1634                charspan
1635            };
1636            return ProvSlot::One {
1637                page_no,
1638                bbox: [r2(l), r2(t), r2(r), r2(b)],
1639                bottom_left,
1640                charspan,
1641            };
1642        }
1643        let Some([x0, y0, x1, y1]) = self.pending_loc else {
1644            return ProvSlot::None;
1645        };
1646        // An all-zero grid box is the sentinel for "this item has no geometry"
1647        // (a slide's speaker notes, say). docling writes a zero bbox for it,
1648        // not a box spanning the page, which is what denormalizing would give.
1649        if [x0, y0, x1, y1] == [0, 0, 0, 0] {
1650            return ProvSlot::One {
1651                page_no: self.cur_page,
1652                bbox: [0.0; 4],
1653                bottom_left: true,
1654                charspan: [0, char_len],
1655            };
1656        }
1657        ProvSlot::One {
1658            page_no: self.cur_page,
1659            bbox: [
1660                r2(x0 as f64 * self.cur_w / 512.0),
1661                r2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
1662                r2(x1 as f64 * self.cur_w / 512.0),
1663                r2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
1664            ],
1665            bottom_left: true,
1666            charspan: [0, char_len],
1667        }
1668    }
1669
1670    /// The 0–511 grid box `loc` denormalized against the current page into
1671    /// BOTTOMLEFT points, rounded to 2 decimals.
1672    fn grid_bbox(&self, [x0, y0, x1, y1]: [u16; 4]) -> [f64; 4] {
1673        [
1674            round2(x0 as f64 * self.cur_w / 512.0),
1675            round2(self.cur_h - y0 as f64 * self.cur_h / 512.0),
1676            round2(x1 as f64 * self.cur_w / 512.0),
1677            round2(self.cur_h - y1 as f64 * self.cur_h / 512.0),
1678        ]
1679    }
1680
1681    /// A page marker passed: every [`Node::ProvContinuation`] fragment on
1682    /// this page becomes one more `prov` entry of its item, after the entry
1683    /// before it is ended at `prev_end` — docling's merged paragraph, one
1684    /// `prov` per fragment, each with its `charspan` into the joined text.
1685    fn resolve_continuations(&mut self) {
1686        if self.pending_continuations.is_empty() {
1687            return;
1688        }
1689        let pending = std::mem::take(&mut self.pending_continuations);
1690        for mut p in pending {
1691            if p.skip > 1 {
1692                p.skip -= 1;
1693                self.pending_continuations.push(p);
1694                continue;
1695            }
1696            let PendingContinuation {
1697                item: idx,
1698                location: loc,
1699                prev_end,
1700                span,
1701                ..
1702            } = p;
1703            if self.cur_page == 0 || loc == [0, 0, 0, 0] {
1704                continue;
1705            }
1706            let [l, t, r, b] = self.grid_bbox(loc);
1707            let page_no = self.cur_page;
1708            let Some(item) = self.texts.get_mut(idx).map(|it| it.value_mut(idx)) else {
1709                continue;
1710            };
1711            // Clamped to the item's text: a later pass (the wrap-mark strip,
1712            // redaction) may have shortened it since the assembler counted.
1713            let total = item["text"].as_str().map_or(0, |t| t.chars().count());
1714            let Some(provs) = item.get_mut("prov").and_then(Value::as_array_mut) else {
1715                continue;
1716            };
1717            // No first fragment to continue: the item has no geometry.
1718            let Some(last) = provs.last_mut() else {
1719                continue;
1720            };
1721            last["charspan"][1] = json!(prev_end.min(total));
1722            provs.push(json!({
1723                "page_no": page_no,
1724                "bbox": {"l": l, "t": t, "r": r, "b": b, "coord_origin": "BOTTOMLEFT"},
1725                "charspan": [span[0].min(total), span[1].min(total)],
1726            }));
1727        }
1728    }
1729
1730    /// Adopt a node's own location field (tables, formulas, list items carry
1731    /// one instead of a [`Node::Located`] wrapper) when no wrapper is pending.
1732    fn adopt_loc(&mut self, loc: Option<[u16; 4]>) {
1733        if self.pending_loc.is_none() && self.cur_page > 0 {
1734            self.pending_loc = loc;
1735        }
1736    }
1737
1738    /// Give each item the script-position stage marked (#1005) its inline
1739    /// group, after the walk as docling's post-assembly stage does: the group
1740    /// is the item's first child (`insert_inline_group(…, after=False)` /
1741    /// `add_inline_group`), and each run is a text item with the item's label,
1742    /// its own `prov` (the box of its characters, per page) and
1743    /// `formatting.script` when it is raised or lowered. A linked footnote's
1744    /// link rides on its baseline runs only, so a marker stays out of it.
1745    fn link_script_runs(&mut self) {
1746        for (item, runs, label) in std::mem::take(&mut self.pending_scripts) {
1747            let group = format!("#/groups/{}", self.groups.len());
1748            let layer = self
1749                .item_mut(&item)
1750                .and_then(|v| v.get("content_layer").cloned())
1751                .unwrap_or_else(|| json!("body"));
1752            let mut children = Vec::with_capacity(runs.len());
1753            for run in &runs {
1754                let self_ref = format!("#/texts/{}", self.texts.len());
1755                children.push(ref_value(&self_ref));
1756                let prov: Vec<Value> = run
1757                    .prov
1758                    .iter()
1759                    .map(|p| {
1760                        let [l, t, r, b] = p.bbox.map(|v| round2(f64::from(v)));
1761                        json!({
1762                            "page_no": p.page_no,
1763                            "bbox": {"l": l, "t": t, "r": r, "b": b, "coord_origin": "BOTTOMLEFT"},
1764                            "charspan": p.charspan,
1765                        })
1766                    })
1767                    .collect();
1768                let mut m = serde_json::Map::new();
1769                m.insert("self_ref".into(), json!(self_ref));
1770                m.insert("parent".into(), ref_value(&group));
1771                m.insert("children".into(), json!([]));
1772                m.insert("content_layer".into(), layer.clone());
1773                m.insert("label".into(), json!(label));
1774                m.insert("prov".into(), Value::Array(prov));
1775                m.insert("orig".into(), json!(run.text));
1776                m.insert("text".into(), json!(run.text));
1777                if run.script != crate::Script::Baseline {
1778                    m.insert(
1779                        "formatting".into(),
1780                        formatting_json(&crate::tree::Formatting {
1781                            script: run.script,
1782                            ..Default::default()
1783                        }),
1784                    );
1785                }
1786                if let Some(url) = &run.hyperlink {
1787                    m.insert("hyperlink".into(), json!(url));
1788                }
1789                self.texts.push(Item::json(Value::Object(m)));
1790            }
1791            self.groups.push(json!({
1792                "self_ref": group,
1793                "parent": ref_value(&item),
1794                "children": children,
1795                "content_layer": layer,
1796                "name": "group",
1797                "label": "inline",
1798            }));
1799            if let Some(obj) = self.item_mut(&item).and_then(Value::as_object_mut) {
1800                let mut kids = vec![ref_value(&group)];
1801                if let Some(Value::Array(old)) = obj.get("children") {
1802                    kids.extend(old.iter().cloned());
1803                }
1804                obj.insert("children".into(), Value::Array(kids));
1805            }
1806        }
1807    }
1808
1809    /// Resolve the [`Node::Commented`] annotations collected during the walk
1810    /// into docling's `comments: [{"$ref": "#/groups/N"}]` key on the annotated
1811    /// item. It has to run after the whole walk: docx appends its comment
1812    /// bodies, so the groups they live in are usually allocated *later* than
1813    /// the paragraphs pointing at them. docling emits the key between `prov`
1814    /// and `orig`, so insert it in place rather than appending (serde_json runs
1815    /// with `preserve_order`, i.e. key order is output order).
1816    fn link_comments(&mut self) {
1817        let refs: Vec<(String, Vec<Value>)> = std::mem::take(&mut self.pending_comments)
1818            .into_iter()
1819            .map(|(item, comments)| {
1820                let refs = comments
1821                    .iter()
1822                    .filter_map(|i| self.comment_groups.get(*i))
1823                    .map(ref_value)
1824                    .collect();
1825                (item, refs)
1826            })
1827            .collect();
1828        for (item, comment_refs) in refs {
1829            if comment_refs.is_empty() {
1830                continue;
1831            }
1832            let Some(target) = self.item_mut(&item) else {
1833                continue;
1834            };
1835            let Some(obj) = target.as_object_mut() else {
1836                continue;
1837            };
1838            let tail: Vec<(String, Value)> = obj
1839                .iter()
1840                .skip_while(|(k, _)| k.as_str() != "prov")
1841                .skip(1)
1842                .map(|(k, v)| (k.clone(), v.clone()))
1843                .collect();
1844            for (k, _) in &tail {
1845                // Without `preserve-order` the map is sorted and the position
1846                // is moot (#970); `remove` is the only removal it has.
1847                #[cfg(feature = "preserve-order")]
1848                obj.shift_remove(k);
1849                #[cfg(not(feature = "preserve-order"))]
1850                obj.remove(k);
1851            }
1852            obj.insert("comments".into(), Value::Array(comment_refs));
1853            for (k, v) in tail {
1854                obj.insert(k, v);
1855            }
1856        }
1857    }
1858
1859    /// The stored JSON object a `#/texts/N`-style self-ref points at.
1860    fn item_mut(&mut self, self_ref: &str) -> Option<&mut Value> {
1861        let idx = ref_index(self_ref)?;
1862        if self_ref.starts_with("#/texts/") {
1863            return self.texts.get_mut(idx).map(|item| item.value_mut(idx));
1864        }
1865        if self_ref.starts_with("#/tables/") {
1866            return self.tables.get_mut(idx).map(|t| &mut t.item);
1867        }
1868        let bucket = if self_ref.starts_with("#/pictures/") {
1869            &mut self.pictures
1870        } else if self_ref.starts_with("#/groups/") {
1871            &mut self.groups
1872        } else {
1873            return None;
1874        };
1875        bucket.get_mut(idx)
1876    }
1877
1878    /// Serialize a backend-built [`ItemTree`](crate::tree::ItemTree): every
1879    /// item in creation order into its bucket, with the parent / children /
1880    /// layer the tree recorded. Returns the body's `children` refs.
1881    fn write_tree(&mut self, tree: &crate::tree::ItemTree) -> Vec<Value> {
1882        use crate::tree::TreeKind;
1883        // Every item's `self_ref` first: children may be listed before they
1884        // are written (a rich cell's group is created after its content).
1885        let mut refs: Vec<String> = Vec::with_capacity(tree.items.len());
1886        let (mut nt, mut ng, mut ntb, mut np, mut nf, mut nk) = (0, 0, 0, 0, 0, 0);
1887        for item in &tree.items {
1888            if item.deleted {
1889                refs.push(String::new());
1890                continue;
1891            }
1892            let r = match &item.kind {
1893                TreeKind::Text { .. } | TreeKind::Code { .. } => {
1894                    nt += 1;
1895                    format!("#/texts/{}", nt - 1)
1896                }
1897                TreeKind::Group { .. } => {
1898                    ng += 1;
1899                    format!("#/groups/{}", ng - 1)
1900                }
1901                TreeKind::Table { .. } => {
1902                    ntb += 1;
1903                    format!("#/tables/{}", ntb - 1)
1904                }
1905                TreeKind::Picture { .. } => {
1906                    np += 1;
1907                    format!("#/pictures/{}", np - 1)
1908                }
1909                TreeKind::FieldRegion { items } => {
1910                    // A region's marker / key / value parts are text items
1911                    // too, numbered where docling creates them.
1912                    nt += items
1913                        .iter()
1914                        .map(|i| {
1915                            [&i.marker, &i.key, &i.value]
1916                                .iter()
1917                                .filter(|p| p.is_some())
1918                                .count()
1919                        })
1920                        .sum::<usize>();
1921                    nf += 1;
1922                    format!("#/field_regions/{}", nf - 1)
1923                }
1924                TreeKind::KeyValueGraph { .. } => {
1925                    nk += 1;
1926                    format!("#/key_value_items/{}", nk - 1)
1927                }
1928            };
1929            refs.push(r);
1930        }
1931        let ref_of = |id: usize| ref_value(refs[id].as_str());
1932        for (id, item) in tree.items.iter().enumerate() {
1933            if item.deleted {
1934                continue;
1935            }
1936            let parent = item.parent.map_or("#/body", |p| refs[p].as_str());
1937            // A deleted item has no ref; one still listed as a child (a stale
1938            // backend link) is left out rather than written as `"$ref": ""`,
1939            // which docling-core rejects on load (#527).
1940            let children: Vec<Value> = item
1941                .children
1942                .iter()
1943                .filter(|&&c| !tree.items[c].deleted)
1944                .map(|&c| ref_of(c))
1945                .collect();
1946            let layer = item.layer.map_or("body", |l| l.value());
1947            // The item's own provenance, consumed by the writer below
1948            // (`take_prov`); an item without one writes `prov: []`.
1949            self.pending_exact = item.prov.as_ref().map(ExactProv::from);
1950            let self_ref = match &item.kind {
1951                TreeKind::Text {
1952                    label,
1953                    text,
1954                    orig,
1955                    formatting,
1956                    hyperlink,
1957                    level,
1958                    list,
1959                } => {
1960                    // docling's field order: …, text, formatting, hyperlink,
1961                    // then the subclass fields (`level`; `enumerated`, `marker`).
1962                    let mut tail = serde_json::Map::new();
1963                    if let Some(f) = formatting {
1964                        tail.insert("formatting".into(), formatting_json(f));
1965                    }
1966                    if let Some(h) = hyperlink {
1967                        tail.insert("hyperlink".into(), json!(h));
1968                    }
1969                    if let Some(l) = level {
1970                        tail.insert("level".into(), json!(l));
1971                    }
1972                    if let Some(l) = list {
1973                        tail.insert("enumerated".into(), json!(l.enumerated));
1974                        tail.insert("marker".into(), json!(l.marker));
1975                    }
1976                    let r = format!("#/texts/{}", self.texts.len());
1977                    let prov = self.take_prov(text.chars().count());
1978                    let mut item_json = json!({
1979                        "self_ref": r,
1980                        "parent": { "$ref": parent },
1981                        "children": children,
1982                        "content_layer": layer,
1983                        "label": label,
1984                        "prov": prov,
1985                    });
1986                    // docling's `comments` back-refs sit between `prov` and
1987                    // `orig`, and are written only when set.
1988                    if !item.comments.is_empty() {
1989                        item_json["comments"] =
1990                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
1991                    }
1992                    // `DocItem.source`, likewise only when set: a WebVTT
1993                    // cue's `TrackSource`, whose `None` fields are omitted.
1994                    if let Some(track) = &item.source {
1995                        item_json["source"] = json!([track_json(track)]);
1996                    }
1997                    merge(
1998                        &mut item_json,
1999                        json!({
2000                            "orig": orig.as_deref().unwrap_or(text),
2001                            "text": text,
2002                        }),
2003                    );
2004                    merge(&mut item_json, Value::Object(tail));
2005                    if self.note_keys {
2006                        if !item.notes.is_empty() {
2007                            item_json["_notes"] = Value::Array(
2008                                item.notes
2009                                    .iter()
2010                                    .map(|n| json!([n.offset, n.text]))
2011                                    .collect(),
2012                            );
2013                        }
2014                        if item.note_body {
2015                            item_json["_note_body"] = json!(true);
2016                        }
2017                        if !item.anchors.is_empty() {
2018                            item_json["_anchors"] = json!(item.anchors);
2019                        }
2020                        if let Some(number) = &item.number {
2021                            item_json["_number"] = json!(number);
2022                        }
2023                        if let Some(rev) = &item.revision {
2024                            let mut r = serde_json::Map::new();
2025                            r.insert("kind".into(), json!(rev.kind.as_str()));
2026                            if let Some(a) = &rev.author {
2027                                r.insert("author".into(), json!(a));
2028                            }
2029                            if let Some(d) = &rev.date {
2030                                r.insert("date".into(), json!(d));
2031                            }
2032                            item_json["_revision"] = Value::Object(r);
2033                        }
2034                    }
2035                    self.texts.push(Item::json(item_json));
2036                    r
2037                }
2038                TreeKind::Code {
2039                    text,
2040                    orig,
2041                    language,
2042                    formatting,
2043                    hyperlink,
2044                    captions,
2045                } => {
2046                    let r = format!("#/texts/{}", self.texts.len());
2047                    let prov = self.take_prov(text.chars().count());
2048                    let mut item_json = json!({
2049                        "self_ref": r,
2050                        "parent": { "$ref": parent },
2051                        "children": children,
2052                        "content_layer": layer,
2053                        "label": "code",
2054                        "prov": prov,
2055                    });
2056                    if !item.comments.is_empty() {
2057                        item_json["comments"] =
2058                            Value::Array(item.comments.iter().map(|&c| ref_of(c)).collect());
2059                    }
2060                    merge(
2061                        &mut item_json,
2062                        json!({
2063                            "orig": orig.as_deref().unwrap_or(text),
2064                            "text": text,
2065                        }),
2066                    );
2067                    if let Some(f) = formatting {
2068                        item_json["formatting"] = formatting_json(f);
2069                    }
2070                    if let Some(h) = hyperlink {
2071                        item_json["hyperlink"] = json!(h);
2072                    }
2073                    merge(
2074                        &mut item_json,
2075                        json!({
2076                            "captions": captions.iter().map(|&c| ref_of(c)).collect::<Vec<_>>(),
2077                            "references": [],
2078                            "footnotes": [],
2079                            "code_language": code_language(language.as_deref()),
2080                        }),
2081                    );
2082                    self.texts.push(Item::json(item_json));
2083                    r
2084                }
2085                TreeKind::Group { label, name } => {
2086                    self.pending_exact = None;
2087                    let r = format!("#/groups/{}", self.groups.len());
2088                    self.groups.push(json!({
2089                        "self_ref": r,
2090                        "parent": { "$ref": parent },
2091                        "children": children,
2092                        "content_layer": layer,
2093                        "name": name,
2094                        "label": label,
2095                    }));
2096                    r
2097                }
2098                TreeKind::Table {
2099                    table,
2100                    rich_cells,
2101                    captions,
2102                    footnotes,
2103                } => {
2104                    // docling's raw cell text: nothing to unescape or strip.
2105                    let r = self.add_table_with(table, parent, true);
2106                    let idx = ref_index(&r).expect("table ref");
2107                    let t = &mut self.tables[idx];
2108                    t.item["children"] = Value::Array(children);
2109                    t.item["content_layer"] = json!(layer);
2110                    t.item["captions"] =
2111                        Value::Array(captions.iter().map(|&c| ref_of(c)).collect());
2112                    t.item["footnotes"] =
2113                        Value::Array(footnotes.iter().map(|&c| ref_of(c)).collect());
2114                    // A `RichTableCell` is the plain cell plus a `ref` to the
2115                    // group holding its content — on `table_cells` only; the
2116                    // derived `grid` shows plain cells.
2117                    for &(row, col, group) in rich_cells {
2118                        let cell_ref = ref_of(group);
2119                        for c in t.data.cells.iter_mut() {
2120                            if c.start_row == row && c.start_col == col {
2121                                c.cell_ref = Some(Box::new(cell_ref.clone()));
2122                            }
2123                        }
2124                    }
2125                    r
2126                }
2127                TreeKind::Picture {
2128                    captions,
2129                    image,
2130                    classification,
2131                    extra_classes,
2132                    description,
2133                    confidence,
2134                    chart,
2135                    dpi,
2136                } => {
2137                    // A chart's meta: the kind as the one classification
2138                    // prediction (pydantic's field order puts `confidence`
2139                    // first when present), then the reconstructed data grid
2140                    // (#405).
2141                    let mut meta = classification.as_ref().map(|c| {
2142                        let mut pred = serde_json::Map::new();
2143                        if let Some(conf) = confidence {
2144                            pred.insert("confidence".into(), json!(conf));
2145                        }
2146                        pred.insert("class_name".into(), json!(c));
2147                        let mut preds = vec![Value::Object(pred)];
2148                        preds.extend(extra_classes.iter().map(|c| json!({ "class_name": c })));
2149                        json!({ "classification": { "predictions": preds } })
2150                    });
2151                    if let (Some(m), Some(t)) = (meta.as_mut(), chart) {
2152                        if !t.rows.is_empty() {
2153                            m["tabular_chart"] =
2154                                object([("chart_data", table_data(t).into_value())]);
2155                        }
2156                    }
2157                    // The OCR description (#645) goes first in the meta —
2158                    // `PictureMeta` field order — and as the annotation the
2159                    // flat node writes (see `description_meta`).
2160                    if let Some(desc) = description {
2161                        let mut d = description_meta(desc);
2162                        let mut merged = Map::new();
2163                        merged.insert("description".into(), d["description"].take());
2164                        if let Some(Value::Object(rest)) = meta {
2165                            merged.extend(rest);
2166                        }
2167                        merged.insert("annotations".into(), d["annotations"].take());
2168                        meta = Some(Value::Object(merged));
2169                    }
2170                    // The source of a picture no engine rendered (a LaTeX
2171                    // `tikzpicture`): `PictureMeta.code`.
2172                    if let Some((text, language)) = &item.code_meta {
2173                        let code = json!({ "text": text, "language": language });
2174                        match meta.as_mut() {
2175                            Some(Value::Object(m)) => {
2176                                m.insert("code".into(), code);
2177                            }
2178                            _ => meta = Some(json!({ "code": code })),
2179                        }
2180                    }
2181                    let prov = self.take_prov(0);
2182                    let r = self.push_picture(
2183                        prov,
2184                        captions.iter().map(|&c| ref_of(c)).collect(),
2185                        children,
2186                        image.as_ref(),
2187                        meta,
2188                        parent,
2189                    );
2190                    if let Some(idx) = ref_index(&r) {
2191                        self.pictures[idx]["content_layer"] = json!(layer);
2192                        // The image's dpi is the file's when the backend read
2193                        // it (python-pptx does); the default 72 otherwise.
2194                        if let (Some(dpi), Some(img)) = (dpi, self.pictures[idx].get_mut("image")) {
2195                            img["dpi"] = json!(dpi);
2196                        }
2197                    }
2198                    r
2199                }
2200                TreeKind::FieldRegion { items } => {
2201                    self.pending_exact = None;
2202                    let r = self.add_field_region(items, parent);
2203                    if let Some(region) = self.field_regions.last_mut() {
2204                        region["content_layer"] = json!(layer);
2205                    }
2206                    r
2207                }
2208                TreeKind::KeyValueGraph { cells, links } => {
2209                    self.pending_exact = None;
2210                    let r = self.add_key_value_graph(cells, links, parent);
2211                    if let Some(item) = self.key_value_items.last_mut() {
2212                        item["content_layer"] = json!(layer);
2213                    }
2214                    r
2215                }
2216            };
2217            debug_assert_eq!(self_ref, refs[id], "tree item {id} numbered out of order");
2218            // An item over several boxes (a DocLang thread read back, #1207):
2219            // one `prov` entry per box.
2220            if !item.more_prov.is_empty() {
2221                if let Some(provs) = self
2222                    .item_mut(&self_ref)
2223                    .and_then(|v| v.get_mut("prov"))
2224                    .and_then(Value::as_array_mut)
2225                {
2226                    for p in &item.more_prov {
2227                        let r2 = round2;
2228                        let [l, t, r, b] = p.bbox;
2229                        let slot = ProvSlot::One {
2230                            page_no: p.page_no,
2231                            bbox: [r2(l), r2(t), r2(r), r2(b)],
2232                            bottom_left: p.bottom_left,
2233                            charspan: p.charspan,
2234                        };
2235                        if let Value::Array(mut one) = slot.to_value() {
2236                            provs.append(&mut one);
2237                        }
2238                    }
2239                }
2240            }
2241            // A float's own footnotes (`FloatingItem.footnotes`).
2242            if !item.footnotes.is_empty() {
2243                let notes: Vec<Value> = item
2244                    .footnotes
2245                    .iter()
2246                    .filter(|&&f| !tree.items[f].deleted)
2247                    .map(|&f| ref_of(f))
2248                    .collect();
2249                if let Some(v) = self.item_mut(&self_ref) {
2250                    v["footnotes"] = Value::Array(notes);
2251                }
2252            }
2253        }
2254        tree.body
2255            .iter()
2256            .filter(|&&c| !tree.items[c].deleted)
2257            .map(|&c| ref_of(c))
2258            .collect()
2259    }
2260
2261    fn add_node(&mut self, node: &Node, parent: &str) -> Option<String> {
2262        match node {
2263            Node::Heading { level: 1, text } => {
2264                Some(self.add_text("title", text, parent, json!({})))
2265            }
2266            Node::Heading { level, text } => Some(self.add_text(
2267                "section_header",
2268                text,
2269                parent,
2270                json!({ "level": level.saturating_sub(1) }),
2271            )),
2272            Node::Caption { text, href } => {
2273                let extra = match href {
2274                    Some(url) => json!({ "hyperlink": url }),
2275                    None => json!({}),
2276                };
2277                Some(self.add_text("caption", text, parent, extra))
2278            }
2279            // A marked PDF item (#1005, docling's `ScriptPositionModel._apply`):
2280            // the item keeps its place and its `prov`, its text moves into an
2281            // inline group of the runs (see `link_script_runs`).
2282            Node::ScriptText { inner, runs } => {
2283                let label = match inner.as_ref() {
2284                    Node::LabeledText { label, .. } => label.clone(),
2285                    _ => "text".to_string(),
2286                };
2287                let r = self.add_node(inner, parent)?;
2288                let link = runs.iter().find_map(|run| run.hyperlink.clone());
2289                if let Some(obj) = self.item_mut(&r).and_then(Value::as_object_mut) {
2290                    obj.insert("orig".into(), json!(""));
2291                    obj.insert("text".into(), json!(""));
2292                    // The item keeps its own link, as docling's does.
2293                    if let Some(url) = link {
2294                        obj.insert("hyperlink".into(), json!(url));
2295                    }
2296                }
2297                self.pending_scripts.push((r.clone(), runs.clone(), label));
2298                Some(r)
2299            }
2300            // A PDF footnote: docling's own label, and its link as the item's
2301            // `hyperlink` rather than Markdown baked into the text.
2302            Node::LabeledText { label, text, href } => {
2303                let extra = match href {
2304                    Some(url) => json!({ "hyperlink": url }),
2305                    None => json!({}),
2306                };
2307                Some(self.add_text(label, text, parent, extra))
2308            }
2309            Node::Paragraph { text } | Node::ListText { text, .. } => {
2310                // A whole-paragraph display equation is a formula item (docling
2311                // wraps it in `$$…$$` and, unlike a text item, never escapes it).
2312                let t = text.trim();
2313                match t.strip_prefix("$$").and_then(|s| s.strip_suffix("$$")) {
2314                    Some(inner) if !inner.is_empty() => Some(self.add_formula(inner, parent)),
2315                    _ => Some(self.add_text("text", text, parent, json!({}))),
2316                }
2317            }
2318            Node::CheckboxItem { checked, text } => {
2319                // docling's checkbox item: the `checkbox_selected` /
2320                // `checkbox_unselected` label carries the state and the text
2321                // is the bare option label (right_to_left_03's `خير`,
2322                // docx_checkboxes' `Orange juice`). The `- [x]` task-list
2323                // marker is Markdown's rendering of it, not item text (#609).
2324                let label = if *checked {
2325                    "checkbox_selected"
2326                } else {
2327                    "checkbox_unselected"
2328                };
2329                Some(self.add_text(label, text, parent, json!({})))
2330            }
2331            Node::Code {
2332                language,
2333                text,
2334                orig,
2335                ..
2336            } => Some(self.add_code(text, language.as_deref(), orig.as_deref(), parent)),
2337            // A CodeFormula-decoded display formula: `text` carries the LaTeX,
2338            // `orig` the raw glyph extraction (docling's enriched shape).
2339            Node::Formula {
2340                latex,
2341                orig,
2342                location,
2343            } => {
2344                self.adopt_loc(*location);
2345                Some(self.add_formula_item(latex, orig, parent))
2346            }
2347            // docling's notes-layer `comment_section` group holding the
2348            // comment's text item. What the annotated items point at differs
2349            // upstream: the docx backend links the group (so a comment's
2350            // replies group together), everything going through
2351            // docling-core's `add_comment` links the note text itself.
2352            Node::CommentSection {
2353                name,
2354                text,
2355                refs_note_text,
2356                grouped,
2357            } => {
2358                if !*grouped {
2359                    // docling-core's bare `add_comment`: the note text sits
2360                    // directly under the parent and is what the back-refs
2361                    // point at.
2362                    let child =
2363                        self.add_text("text", text, parent, json!({ "content_layer": "notes" }));
2364                    self.comment_groups.push(child.clone());
2365                    return Some(child);
2366                }
2367                if let Some((_, self_ref)) = self
2368                    .last_comment_section
2369                    .as_ref()
2370                    .filter(|(n, _)| n == name)
2371                    .cloned()
2372                {
2373                    // Another message of the same thread: a further note in
2374                    // the group already open for this cell.
2375                    let child =
2376                        self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
2377                    if let Some(children) =
2378                        self.groups[group_index(&self_ref)]["children"].as_array_mut()
2379                    {
2380                        children.push(ref_value(child.as_str()));
2381                    }
2382                    self.comment_groups.push(if *refs_note_text {
2383                        child
2384                    } else {
2385                        self_ref.clone()
2386                    });
2387                    // The group is already its parent's child: listing it
2388                    // again put a thread's group in the body once per message.
2389                    return None;
2390                }
2391                let self_ref = format!("#/groups/{}", self.groups.len());
2392                self.groups.push(Value::Null);
2393                let child =
2394                    self.add_text("text", text, &self_ref, json!({ "content_layer": "notes" }));
2395                self.groups[group_index(&self_ref)] = json!({
2396                    "self_ref": self_ref,
2397                    "parent": { "$ref": parent },
2398                    "children": [{ "$ref": child }],
2399                    "content_layer": "notes",
2400                    "name": name,
2401                    "label": "comment_section",
2402                });
2403                self.last_comment_section = Some((name.clone(), self_ref.clone()));
2404                self.comment_groups.push(if *refs_note_text {
2405                    child
2406                } else {
2407                    self_ref.clone()
2408                });
2409                Some(self_ref)
2410            }
2411            // The annotation itself is a cross-reference: emit the item, then
2412            // remember it so the group refs can be filled in at the end.
2413            Node::Commented { comments, inner } => {
2414                let item = self.add_node(inner, parent)?;
2415                if !comments.is_empty() {
2416                    self.pending_comments.push((item.clone(), comments.clone()));
2417                }
2418                Some(item)
2419            }
2420            Node::Table(t) => Some(self.add_table(t, parent)),
2421            Node::Picture {
2422                caption,
2423                caption_href,
2424                image,
2425                classification,
2426                description,
2427                caption_parent,
2428                caption_location,
2429            } => Some(self.add_picture(
2430                caption.as_deref(),
2431                caption_href.as_deref(),
2432                image.as_ref(),
2433                picture_meta(classification.as_deref(), description.as_ref()),
2434                parent,
2435                (*caption_parent, *caption_location),
2436            )),
2437            // A chart is a picture item in the JSON with docling's chart
2438            // meta — `classification` (the chart kind, as the one prediction)
2439            // and `tabular_chart.chart_data`, the series reconstructed as a
2440            // `TableData` (#405) — and no image payload.
2441            Node::Chart {
2442                kind,
2443                table,
2444                caption,
2445                location,
2446            } => {
2447                self.adopt_loc(*location);
2448                let mut meta = json!({
2449                    "classification": { "predictions": [{ "class_name": kind }] },
2450                });
2451                if !table.rows.is_empty() {
2452                    meta["tabular_chart"] =
2453                        object([("chart_data", table_data(table).into_value())]);
2454                }
2455                // docling's office backends add the chart's title as a caption
2456                // item of the *container* (the sheet group, the slide), listed
2457                // before the picture that references it, with the chart's own
2458                // box and a charspan over the caption text — not as a child
2459                // of the picture, which is where a PDF caption lives.
2460                let mut captions = Vec::new();
2461                if let Some(cap) = caption.as_deref().filter(|c| !c.is_empty()) {
2462                    let prov = self.prov_slot(unescape_text(cap).chars().count(), true);
2463                    let cap_ref = self.add_text_with("caption", cap, parent, json!({}), prov);
2464                    self.pending_siblings.push(ref_value(cap_ref.as_str()));
2465                    captions.push(ref_value(cap_ref));
2466                }
2467                let prov = self.take_prov(0);
2468                Some(self.push_picture(prov, captions, Vec::new(), None, Some(meta), parent))
2469            }
2470            // A DocLang-only node is omitted from the JSON body.
2471            Node::DoclangOnly(_) => None,
2472            Node::Group {
2473                label,
2474                name,
2475                layer,
2476                children,
2477            } => Some(self.add_group(label, name.as_deref(), *layer, children, parent)),
2478            Node::FieldRegion { items } => Some(self.add_field_region(items, parent)),
2479            Node::KeyValueGraph { cells, links } => {
2480                Some(self.add_key_value_graph(cells, links, parent))
2481            }
2482            // A rich inline group is a text item over its Markdown text; the
2483            // structured runs are DocLang-only, so the JSON matches a paragraph.
2484            Node::InlineGroup { md_text, .. } => {
2485                Some(self.add_text("text", md_text, parent, json!({})))
2486            }
2487            // A plain-text backend dump is a single text item over the file body.
2488            Node::TextDump(text) => Some(self.add_text("text", text, parent, json!({}))),
2489            // Speaker notes are content a deck carries, and docling puts them
2490            // in the JSON on their own layer, so a consumer reading only JSON
2491            // can pick them (#402). Page furniture stays out of the flat
2492            // path; a backend that builds docling's item tree (HTML) puts its
2493            // furniture-layer items in the JSON through `write_tree`.
2494            Node::Furniture {
2495                layer: ContentLayer::Notes,
2496                inner,
2497            } => {
2498                let item = self.add_node(inner, parent)?;
2499                self.set_layer(&item, "notes");
2500                Some(item)
2501            }
2502            Node::Furniture { .. } => None,
2503            // PDF page headers and footers: docling writes them as body-parented
2504            // `page_header`/`page_footer` text items on the furniture layer, so a
2505            // JSON consumer can read running headers (printed page ids, dates).
2506            Node::PageFurniture {
2507                footer,
2508                location,
2509                text,
2510            } => {
2511                if self.cur_page > 0 {
2512                    self.pending_loc = Some(*location);
2513                }
2514                let label = if *footer {
2515                    "page_footer"
2516                } else {
2517                    "page_header"
2518                };
2519                let item = self.add_text(label, text, parent, json!({}));
2520                self.pending_loc = None;
2521                self.set_layer(&item, "furniture");
2522                Some(item)
2523            }
2524            // A labelled furniture paragraph (a `.doc` header / footer or
2525            // note body, #535): the item docling's office backends write.
2526            Node::FurnitureText { label, text } => {
2527                let item = self.add_text(label, text, parent, json!({}));
2528                self.set_layer(&item, "furniture");
2529                Some(item)
2530            }
2531            // A PDF picture's contained text (docling's `_add_child_elements`):
2532            // items parented to the picture just written, listed after its
2533            // caption in that picture's `children`.
2534            Node::PictureChildren(children) => {
2535                let pic = self.pictures.len().checked_sub(1)?;
2536                let pic_ref = format!("#/pictures/{pic}");
2537                let refs = self.walk_into(children, &pic_ref);
2538                if let Some(list) = self.pictures[pic]["children"].as_array_mut() {
2539                    list.extend(refs.into_iter().map(Child::into_value));
2540                }
2541                None
2542            }
2543            // A location wrapper turns into the wrapped item's `prov` entry —
2544            // but only on pages the PDF paths described with a PageInfo marker
2545            // (other geometry-bearing backends, e.g. PPTX shapes, keep their
2546            // pre-#171 provenance-less JSON until they emit markers too).
2547            Node::Located { location, inner } => {
2548                if self.cur_page > 0 {
2549                    self.pending_loc = Some(*location);
2550                }
2551                let r = self.add_node(inner, parent);
2552                self.pending_loc = None;
2553                r
2554            }
2555            Node::Anchor { id } => {
2556                self.pending_anchors.push(id.clone());
2557                None
2558            }
2559            Node::Track { track, cue, inner } => {
2560                self.pending_track = Some((track.clone(), cue.clone()));
2561                let r = self.add_node(inner, parent);
2562                self.pending_track = None;
2563                r
2564            }
2565            Node::Prov {
2566                page_no,
2567                bbox,
2568                charspan,
2569                bottom_left,
2570                inner,
2571                ..
2572            } => {
2573                self.pending_exact = Some(ExactProv {
2574                    page_no: *page_no,
2575                    bbox: bbox.map(f64::from),
2576                    bottom_left: *bottom_left,
2577                    charspan: *charspan,
2578                });
2579                let r = self.add_node(inner, parent);
2580                self.pending_exact = None;
2581                r
2582            }
2583            // Page breaks are DocLang-only; docling omits them from the JSON body.
2584            Node::PageBreak => None,
2585            // A continuation fragment of the item just written (#1127): its box
2586            // is on a later page, resolved when that page's marker comes.
2587            Node::ProvContinuation {
2588                location,
2589                prev_end,
2590                span,
2591                page_skip,
2592                exact,
2593            } => {
2594                // A docling-JSON input's further `prov` entry (#1207): written
2595                // as read, at once.
2596                if let (Some(idx), Some(p)) = (self.last_text, exact) {
2597                    let r2 = round2;
2598                    let [l, t, r, b] = p.bbox.map(f64::from);
2599                    let entry = object([
2600                        ("page_no", p.page_no.into()),
2601                        (
2602                            "bbox",
2603                            object([
2604                                ("l", r2(l).into()),
2605                                ("t", r2(t).into()),
2606                                ("r", r2(r).into()),
2607                                ("b", r2(b).into()),
2608                                ("coord_origin", ProvSlot::origin(p.bottom_left).into()),
2609                            ]),
2610                        ),
2611                        ("charspan", json!([span[0], span[1]])),
2612                    ]);
2613                    if let Some(provs) = self
2614                        .texts
2615                        .get_mut(idx)
2616                        .map(|it| it.value_mut(idx))
2617                        .and_then(|item| item.get_mut("prov"))
2618                        .and_then(Value::as_array_mut)
2619                        .filter(|provs| !provs.is_empty())
2620                    {
2621                        if let Some(last) = provs.last_mut() {
2622                            last["charspan"][1] = json!(*prev_end);
2623                        }
2624                        provs.push(entry);
2625                    }
2626                    return None;
2627                }
2628                if let Some(idx) = self.last_text.filter(|_| self.cur_page > 0) {
2629                    self.pending_continuations.push(PendingContinuation {
2630                        item: idx,
2631                        skip: *page_skip,
2632                        location: *location,
2633                        prev_end: *prev_end,
2634                        span: *span,
2635                    });
2636                }
2637                None
2638            }
2639            // The page marker: record the page's number and size for the
2640            // `pages` map, and denormalize every following location against it.
2641            Node::PageInfo {
2642                page_no,
2643                width,
2644                height,
2645            } => {
2646                self.cur_page = *page_no;
2647                self.cur_w = *width as f64;
2648                self.cur_h = *height as f64;
2649                if *page_no > 0 {
2650                    self.pages.push((*page_no, self.cur_w, self.cur_h));
2651                }
2652                self.resolve_continuations();
2653                None
2654            }
2655            // Handled by `add_list` in `walk`.
2656            Node::ListItem { .. } => None,
2657        }
2658    }
2659
2660    /// A form key-value region: `field_regions/N` holds the region, each field is
2661    /// a `field_items/M` whose children are its `marker` / `field_key` /
2662    /// `field_value` texts (absent parts are simply omitted).
2663    fn add_field_region(&mut self, items: &[crate::FieldItem], parent: &str) -> String {
2664        let self_ref = format!("#/field_regions/{}", self.field_regions.len());
2665        self.field_regions.push(Value::Null);
2666        let region_index = self.field_regions.len() - 1;
2667        let mut item_refs = Vec::new();
2668        for item in items {
2669            item_refs.push(ref_value(self.add_field_item(item, &self_ref)));
2670        }
2671        self.field_regions[region_index] = json!({
2672            "self_ref": self_ref,
2673            "parent": { "$ref": parent },
2674            "children": item_refs,
2675            "content_layer": "body",
2676            "label": "field_region",
2677            "prov": [],
2678        });
2679        self_ref
2680    }
2681
2682    /// A `KeyValueItem`: docling's `GraphData` written cell for cell and link
2683    /// for link (`key_value_items/N`), the item itself childless and without
2684    /// provenance, the way the XBRL backend creates it.
2685    fn add_key_value_graph(
2686        &mut self,
2687        cells: &[crate::GraphCell],
2688        links: &[crate::GraphLink],
2689        parent: &str,
2690    ) -> String {
2691        let self_ref = format!("#/key_value_items/{}", self.key_value_items.len());
2692        let cells: Vec<Value> = cells
2693            .iter()
2694            .map(|c| {
2695                json!({
2696                    "label": c.label,
2697                    "cell_id": c.cell_id,
2698                    "text": c.text,
2699                    "orig": c.orig,
2700                })
2701            })
2702            .collect();
2703        let links: Vec<Value> = links
2704            .iter()
2705            .map(|l| {
2706                json!({
2707                    "label": l.label,
2708                    "source_cell_id": l.source_cell_id,
2709                    "target_cell_id": l.target_cell_id,
2710                })
2711            })
2712            .collect();
2713        self.key_value_items.push(json!({
2714            "self_ref": self_ref,
2715            "parent": { "$ref": parent },
2716            "children": [],
2717            "content_layer": "body",
2718            "label": "key_value_region",
2719            "prov": [],
2720            "captions": [],
2721            "references": [],
2722            "footnotes": [],
2723            "graph": { "cells": cells, "links": links },
2724        }));
2725        self_ref
2726    }
2727
2728    fn add_field_item(&mut self, item: &crate::FieldItem, parent: &str) -> String {
2729        let self_ref = format!("#/field_items/{}", self.field_items.len());
2730        self.field_items.push(Value::Null);
2731        let item_index = self.field_items.len() - 1;
2732        let mut child_refs = Vec::new();
2733        for (label, text) in [
2734            ("marker", &item.marker),
2735            ("field_key", &item.key),
2736            ("field_value", &item.value),
2737        ] {
2738            if let Some(text) = text {
2739                // A value's `kind` (docling's `read_only` / `fillable`)
2740                // follows its text.
2741                let extra = match (label, &item.value_kind) {
2742                    ("field_value", Some(kind)) => json!({ "kind": kind }),
2743                    _ => json!({}),
2744                };
2745                child_refs.push(ref_value(self.add_text(label, text, &self_ref, extra)));
2746            }
2747        }
2748        self.field_items[item_index] = json!({
2749            "self_ref": self_ref,
2750            "parent": { "$ref": parent },
2751            "children": child_refs,
2752            "content_layer": "body",
2753            "label": "field_item",
2754            "prov": [],
2755        });
2756        self_ref
2757    }
2758
2759    /// Move an already-emitted item onto a content layer. Notes are single
2760    /// text items today; a deeper notes subtree would need its children moved
2761    /// too, and no backend builds one.
2762    fn set_layer(&mut self, self_ref: &str, layer: &str) {
2763        if let Some(item) = self.item_mut(self_ref) {
2764            item["content_layer"] = json!(layer);
2765        }
2766    }
2767
2768    fn add_text(&mut self, label: &str, text: &str, parent: &str, extra: Value) -> String {
2769        let prov = self.take_prov_slot(unescape_text(text).chars().count());
2770        self.add_text_with(label, text, parent, extra, prov)
2771    }
2772
2773    /// [`Self::add_text`] with an explicit `prov` (a chart caption shares the
2774    /// chart's box without consuming it).
2775    fn add_text_with(
2776        &mut self,
2777        label: &str,
2778        text: &str,
2779        parent: &str,
2780        extra: Value,
2781        prov: ProvSlot,
2782    ) -> String {
2783        let index = self.texts.len();
2784        self.last_text = Some(index);
2785        let self_ref = format!("#/texts/{index}");
2786        // A [`Node::Track`] item is docling's ASR text item (#614): the
2787        // segment's words as `text`, its timing as `source` — the `[time: …]`
2788        // prefix the wrapped paragraph shows is Markdown's alone. It carries a
2789        // field the compact [`TextItem`] doesn't, so it is built as JSON.
2790        let mut item = match self.pending_track.take() {
2791            None => Item::Text(Box::new(TextItem {
2792                parent: parent.into(),
2793                label: label.into(),
2794                prov,
2795                text: unescape_text(text).into(),
2796            })),
2797            Some((track, cue)) => {
2798                let mut m = serde_json::Map::with_capacity(9);
2799                m.insert("self_ref".into(), Value::String(self_ref.clone()));
2800                m.insert("parent".into(), ref_value(parent));
2801                m.insert("children".into(), Value::Array(Vec::new()));
2802                m.insert("content_layer".into(), "body".into());
2803                m.insert("label".into(), label.into());
2804                m.insert("prov".into(), prov.to_value());
2805                // `DocItem.source` follows `prov` (docling's field order).
2806                m.insert("source".into(), Value::Array(vec![track_json(&track)]));
2807                m.insert("orig".into(), Value::String(cue.clone()));
2808                m.insert("text".into(), Value::String(cue));
2809                Item::json(Value::Object(m))
2810            }
2811        };
2812        if extra.as_object().is_some_and(|e| !e.is_empty()) {
2813            merge(item.value_mut(index), extra);
2814        }
2815        // The link destinations met before this item (#852), on the Pandoc
2816        // path only — docling's model has no field for them.
2817        let anchors = std::mem::take(&mut self.pending_anchors);
2818        if self.note_keys && !anchors.is_empty() {
2819            merge(item.value_mut(index), json!({ "_anchors": anchors }));
2820        }
2821        self.texts.push(item);
2822        self_ref
2823    }
2824
2825    /// A display-math formula item. `latex` is the raw content (no `$$`); docling
2826    /// re-wraps it and never escapes it.
2827    fn add_formula(&mut self, latex: &str, parent: &str) -> String {
2828        let self_ref = format!("#/texts/{}", self.texts.len());
2829        let prov = self.take_prov(latex.chars().count());
2830        self.texts.push(Item::json(json!({
2831            "self_ref": self_ref,
2832            "parent": { "$ref": parent },
2833            "children": [],
2834            "content_layer": "body",
2835            "label": "formula",
2836            "prov": prov,
2837            "orig": latex,
2838            "text": latex,
2839        })));
2840        self_ref
2841    }
2842
2843    /// A CodeFormula-enriched display formula: `text` is the model's LaTeX
2844    /// while `orig` keeps the raw glyph extraction (docling's enriched shape;
2845    /// the plain [`Self::add_formula`] above sets both to the same string).
2846    fn add_formula_item(&mut self, latex: &str, orig: &str, parent: &str) -> String {
2847        let self_ref = format!("#/texts/{}", self.texts.len());
2848        // docling stamps the provenance when the item is assembled, from the
2849        // region's raw text: the charspan is `orig`'s length, decoded or not
2850        // (the enriched groundtruth: `text` 19 characters, charspan [0, 11]).
2851        let prov = self.take_prov(orig.chars().count());
2852        self.texts.push(Item::json(json!({
2853            "self_ref": self_ref,
2854            "parent": { "$ref": parent },
2855            "children": [],
2856            "content_layer": "body",
2857            "label": "formula",
2858            "prov": prov,
2859            "orig": orig,
2860            "text": latex,
2861        })));
2862        self_ref
2863    }
2864
2865    fn add_code(
2866        &mut self,
2867        text: &str,
2868        language: Option<&str>,
2869        orig: Option<&str>,
2870        parent: &str,
2871    ) -> String {
2872        let self_ref = format!("#/texts/{}", self.texts.len());
2873        let raw = unescape_text(text);
2874        let prov = self.take_prov(raw.chars().count());
2875        self.texts.push(Item::json(json!({
2876            "self_ref": self_ref,
2877            "parent": { "$ref": parent },
2878            "children": [],
2879            "content_layer": "body",
2880            "label": "code",
2881            "prov": prov,
2882            // With code enrichment, `text` is the model's rewrite while `orig`
2883            // keeps the raw extraction; otherwise both are the same string.
2884            "orig": orig.map(unescape_text).unwrap_or_else(|| raw.clone()),
2885            "text": raw,
2886            "captions": [],
2887            "references": [],
2888            "footnotes": [],
2889            "code_language": code_language(language),
2890        })));
2891        self_ref
2892    }
2893
2894    /// Build a list group from a run of (possibly multi-level) list items. A
2895    /// deeper level starts a nested list under the preceding item.
2896    fn add_list(&mut self, items: &[Node], parent: &str) -> String {
2897        let self_ref = format!("#/groups/{}", self.groups.len());
2898        // reserve the slot so nested groups get later indices
2899        self.groups.push(Value::Null);
2900        let base = level_of(&items[0]);
2901        let mut children = Vec::new();
2902        let mut i = 0;
2903        while i < items.len() {
2904            // Empty paragraphs absorbed into the run (blank lines between items)
2905            // are not list items — skip them.
2906            if !matches!(items[i], Node::ListItem { .. }) {
2907                i += 1;
2908                continue;
2909            }
2910            let lvl = level_of(&items[i]);
2911            if lvl > base {
2912                // shouldn't happen at the head; skip defensively
2913                i += 1;
2914                continue;
2915            }
2916            let item_ref = self.add_list_item(&items[i], &self_ref);
2917            // collect any deeper items that nest under this one
2918            let mut j = i + 1;
2919            while j < items.len() && level_of(&items[j]) > base {
2920                j += 1;
2921            }
2922            if j > i + 1 {
2923                let mut nested = Vec::new();
2924                self.add_sibling_lists(&items[i + 1..j], &item_ref, &mut nested);
2925                // the nested list group(s) are children of this item
2926                if let Some(idx) = ref_index(&item_ref) {
2927                    self.texts[idx].value_mut(idx)["children"]
2928                        .as_array_mut()
2929                        .unwrap()
2930                        .extend(nested);
2931                }
2932            }
2933            children.push(ref_value(item_ref));
2934            i = j;
2935        }
2936        self.groups[group_index(&self_ref)] = json!({
2937            "self_ref": self_ref,
2938            "parent": { "$ref": parent },
2939            "children": children,
2940            "content_layer": "body",
2941            "name": "list",
2942            "label": "list",
2943        });
2944        self_ref
2945    }
2946
2947    fn add_list_item(&mut self, node: &Node, parent: &str) -> String {
2948        let Node::ListItem {
2949            ordered,
2950            number,
2951            text,
2952            location,
2953            split,
2954            ..
2955        } = node
2956        else {
2957            unreachable!()
2958        };
2959        self.adopt_loc(*location);
2960        let self_ref = format!("#/texts/{}", self.texts.len());
2961        // A page pipeline's item (PDF) is written as docling's
2962        // `ListItemMarkerProcessor` leaves it: `orig` with the marker, `text`
2963        // without, the marker itself, `enumerated` for any numbered one.
2964        let (orig, raw, enumerated, marker) = match split.as_deref() {
2965            Some(s) => (
2966                s.orig.clone(),
2967                s.text.clone(),
2968                s.enumerated,
2969                s.marker.clone(),
2970            ),
2971            None => {
2972                let raw = unescape_text(text);
2973                let marker = if *ordered {
2974                    format!("{number}.")
2975                } else {
2976                    "-".to_string()
2977                };
2978                (raw.clone(), raw, *ordered, marker)
2979            }
2980        };
2981        let prov = self.take_prov(orig.chars().count());
2982        self.texts.push(Item::json(json!({
2983            "self_ref": self_ref,
2984            "parent": { "$ref": parent },
2985            "children": [],
2986            "content_layer": "body",
2987            "label": "list_item",
2988            "prov": prov,
2989            "orig": orig,
2990            "text": raw,
2991            "enumerated": enumerated,
2992            "marker": marker,
2993        })));
2994        self_ref
2995    }
2996
2997    fn add_table(&mut self, t: &Table, parent: &str) -> String {
2998        self.add_table_with(t, parent, false)
2999    }
3000
3001    /// [`Self::add_table`]; `raw` cell text is written verbatim (see
3002    /// [`table_data_with`]).
3003    fn add_table_with(&mut self, t: &Table, parent: &str, raw: bool) -> String {
3004        let self_ref = format!("#/tables/{}", self.tables.len());
3005        self.adopt_loc(t.location);
3006        let prov = self.take_prov(0);
3007        // The caption is a separate text item the table references (docling's
3008        // `TableItem.captions`), added before the grid so its box isn't
3009        // inherited by a later item.
3010        let (captions, children) = match t.caption.as_deref().filter(|c| !c.is_empty()) {
3011            Some(cap) => self.add_caption(
3012                cap,
3013                json!({}),
3014                &self_ref,
3015                parent,
3016                (t.caption_parent, t.caption_location),
3017            ),
3018            None => (Vec::new(), Vec::new()),
3019        };
3020        // docling-core#675 (#1009): each footnote is a `footnote` text item
3021        // under the table, added after it (docling's backends attach notes
3022        // once the table exists) and listed in its `footnotes`.
3023        // The item-tree path (`raw`) writes its own footnote items.
3024        let (mut children, mut footnotes) = (children, Vec::new());
3025        for note in t.footnotes.iter().filter(|n| !raw && !n.is_empty()) {
3026            let r = ref_value(self.add_text("footnote", note, &self_ref, json!({})));
3027            children.push(r.clone());
3028            footnotes.push(r);
3029        }
3030        let mut data = table_data_with(t, raw);
3031        if !raw {
3032            self.add_cell_pictures(t, &self_ref, &mut data, &mut children);
3033        }
3034        let item = json!({
3035            "self_ref": self_ref,
3036            "parent": { "$ref": parent },
3037            "children": children,
3038            "content_layer": "body",
3039            // docling's `DocItemLabel.DOCUMENT_INDEX` for a table of
3040            // contents (#1091), a plain `table` otherwise.
3041            "label": if t.document_index { "document_index" } else { "table" },
3042            "prov": prov,
3043            "captions": captions,
3044            "references": [],
3045            "footnotes": footnotes,
3046            // The typed `data` takes this stand-in's place on output.
3047            "data": null,
3048            "annotations": [],
3049        });
3050        self.tables.push(TableItem { item, data });
3051        self_ref
3052    }
3053
3054    /// The pictures placed in a table's cells (the XLSX "Place in Cell"
3055    /// image, docling#5015) and the rich cells of a [`crate::rich_cell_group`]
3056    /// (#1119): a cell whose blocks are exactly one
3057    /// [`Node::Prov`]-wrapped picture is docling's `RichTableCell` over a
3058    /// picture item — the picture is the table's child, the cell keeps an
3059    /// empty text and a `ref` to it. Other rich cells (and the PDF
3060    /// pipeline's [`Node::Located`] in-cell pictures) keep their flat cell.
3061    /// The cells' blocks are parallel to `rows`; a ragged (compacted) row
3062    /// pairs its blocks with that row's first-class cells in column order.
3063    fn add_cell_pictures(
3064        &mut self,
3065        t: &Table,
3066        self_ref: &str,
3067        data: &mut TableData,
3068        children: &mut Vec<Value>,
3069    ) {
3070        let Some(blocks) = t.cell_blocks.as_ref() else {
3071            return;
3072        };
3073        for (r, row) in blocks.iter().enumerate() {
3074            let mut in_row: Vec<usize> = (0..data.cells.len())
3075                .filter(|&i| data.cells[i].start_row == r)
3076                .collect();
3077            in_row.sort_by_key(|&i| data.cells[i].start_col);
3078            let ragged = t.rows.get(r).map_or(0, Vec::len) != data.num_cols;
3079            for (c, cell) in row.iter().enumerate() {
3080                let target = if ragged {
3081                    in_row.get(c).copied()
3082                } else {
3083                    in_row
3084                        .iter()
3085                        .copied()
3086                        .find(|&i| data.cells[i].start_col == c)
3087                };
3088                // A `rich_cell_group` (#1119, the DOC backend's picture
3089                // cells): the DOCX item tree's `rich_cell_group_<table>_
3090                // <col>_<row>` group under the table, holding the cell's
3091                // items, and the cell's text without its `<!-- image -->`
3092                // paragraphs.
3093                if let [Node::Group {
3094                    name: Some(name),
3095                    children: blocks,
3096                    ..
3097                }] = cell.as_slice()
3098                {
3099                    let Some(target) = target.filter(|_| name == crate::document::RICH_CELL) else {
3100                        continue;
3101                    };
3102                    let name = format!("rich_cell_group_{}_{c}_{r}", self.tables.len() + 1);
3103                    let group = ref_value(self.add_group(
3104                        "unspecified",
3105                        Some(&name),
3106                        None,
3107                        blocks,
3108                        self_ref,
3109                    ));
3110                    children.push(group.clone());
3111                    let cell = &mut data.cells[target];
3112                    cell.text = cell
3113                        .text
3114                        .split("\n\n")
3115                        .filter(|p| p.trim() != "<!-- image -->")
3116                        .collect::<Vec<_>>()
3117                        .join("\n\n")
3118                        .into();
3119                    cell.cell_ref = Some(Box::new(group));
3120                    continue;
3121                }
3122                let [node @ Node::Prov { inner, .. }] = cell.as_slice() else {
3123                    continue;
3124                };
3125                if !matches!(**inner, Node::Picture { .. }) {
3126                    continue;
3127                }
3128                let Some(target) = target else {
3129                    continue;
3130                };
3131                let Some(pic) = self.add_node(node, self_ref) else {
3132                    continue;
3133                };
3134                let pic = ref_value(pic);
3135                children.push(pic.clone());
3136                let cell = &mut data.cells[target];
3137                cell.text = "".into();
3138                cell.cell_ref = Some(Box::new(pic));
3139            }
3140        }
3141    }
3142
3143    /// Add a picture's or table's caption text item where `choice` says it
3144    /// hangs (#390), returning the `captions` entry for the item and the
3145    /// item's own `children` (the caption, when it is the item's child).
3146    /// The caption never consumes the item's pending provenance — the item
3147    /// takes its box first. Its own box, when the backend kept one (the PDF
3148    /// pipeline's caption region, #609), becomes the caption's `prov` on the
3149    /// item's page, as docling's reading-order model gives every caption the
3150    /// cluster it came from; without one the caption has no `prov`.
3151    fn add_caption(
3152        &mut self,
3153        text: &str,
3154        extra: Value,
3155        self_ref: &str,
3156        parent: &str,
3157        (choice, location): (CaptionParent, Option<[u16; 4]>),
3158    ) -> (Vec<Value>, Vec<Value>) {
3159        // docling's PDF pipeline parents the caption to the item; every
3160        // declarative backend leaves `add_text`'s default — the body — even
3161        // for an item inside a group; the office backends and HTML's
3162        // `<figure>` hang it off the item's container.
3163        let cap_parent = match choice {
3164            CaptionParent::Item => self_ref,
3165            CaptionParent::Container | CaptionParent::ContainerAfter => parent,
3166            CaptionParent::Body => "#/body",
3167        };
3168        if self.cur_page > 0 && location.is_some() {
3169            self.pending_loc = location;
3170        }
3171        let cap_ref = ref_value(self.add_text("caption", text, cap_parent, extra));
3172        match choice {
3173            CaptionParent::Item => return (vec![cap_ref.clone()], vec![cap_ref]),
3174            // Created ahead of the item, so it precedes the item in the
3175            // container's children — and, on the body, in the body's.
3176            CaptionParent::Container => self.pending_siblings.push(cap_ref.clone()),
3177            CaptionParent::Body if parent == "#/body" => {
3178                self.pending_siblings.push(cap_ref.clone())
3179            }
3180            CaptionParent::ContainerAfter => self.pending_after.push(cap_ref.clone()),
3181            // The item sits deeper: the body's children get the caption after
3182            // the top-level item under walk, where docling appended it.
3183            CaptionParent::Body => self.pending_body.push(cap_ref.clone()),
3184        }
3185        (vec![cap_ref], Vec::new())
3186    }
3187
3188    /// `meta` is the picture's docling `PictureMeta` (a classifier's
3189    /// predictions, a chart's kind and data), `None` for a plain picture.
3190    fn add_picture(
3191        &mut self,
3192        caption: Option<&str>,
3193        caption_href: Option<&str>,
3194        image: Option<&crate::PictureImage>,
3195        meta: Option<Value>,
3196        parent: &str,
3197        caption_at: (CaptionParent, Option<[u16; 4]>),
3198    ) -> String {
3199        let self_ref = format!("#/pictures/{}", self.pictures.len());
3200        // Take the picture's own provenance before the caption text is added —
3201        // the caption is a separate item and must not inherit the crop's box.
3202        let prov = self.take_prov(0);
3203        let (captions, children) = match caption.filter(|c| !c.is_empty()) {
3204            Some(cap) => {
3205                // Emit the caption as a text item that the picture references. A
3206                // wrapping `<a href>`'s link rides as docling's `hyperlink` field
3207                // on the caption item (#328).
3208                let extra = match caption_href {
3209                    Some(href) => json!({ "hyperlink": href }),
3210                    None => json!({}),
3211                };
3212                self.add_caption(cap, extra, &self_ref, parent, caption_at)
3213            }
3214            None => (Vec::new(), Vec::new()),
3215        };
3216        self.push_picture(prov, captions, children, image, meta, parent)
3217    }
3218
3219    /// Append the picture item itself — `prov`, `captions` and `children`
3220    /// (a PDF caption is the picture's child) already settled.
3221    fn push_picture(
3222        &mut self,
3223        prov: Value,
3224        captions: Vec<Value>,
3225        children: Vec<Value>,
3226        image: Option<&crate::PictureImage>,
3227        meta: Option<Value>,
3228        parent: &str,
3229    ) -> String {
3230        let self_ref = format!("#/pictures/{}", self.pictures.len());
3231        // The legacy `classification` annotation rides along with a
3232        // classifier's `meta` (see `classification_meta`); a chart's meta has
3233        // none, like docling's.
3234        let annotations = meta
3235            .as_ref()
3236            .and_then(|m| m.get("annotations").cloned())
3237            .unwrap_or_else(|| json!([]));
3238        let meta = meta.map(|mut m| {
3239            if let Some(obj) = m.as_object_mut() {
3240                obj.remove("annotations");
3241            }
3242            m
3243        });
3244        // `meta` sits between `content_layer` and `label` in docling's field
3245        // order (and `preserve_order` keeps ours byte-compatible), so the item
3246        // is built in one shot per shape rather than patched afterwards.
3247        let mut item = match meta {
3248            Some(meta) => json!({
3249                "self_ref": self_ref,
3250                "parent": { "$ref": parent },
3251                "children": children,
3252                "content_layer": "body",
3253                "meta": meta,
3254                "label": "picture",
3255                "prov": prov,
3256                "captions": captions,
3257                "references": [],
3258                "footnotes": [],
3259                "annotations": annotations,
3260            }),
3261            None => json!({
3262                "self_ref": self_ref,
3263                "parent": { "$ref": parent },
3264                "children": children,
3265                "content_layer": "body",
3266                "label": "picture",
3267                "prov": prov,
3268                "captions": captions,
3269                "references": [],
3270                "footnotes": [],
3271                "annotations": annotations,
3272            }),
3273        };
3274        // docling stores the extracted image as an `ImageRef` (data URI + size,
3275        // the size as floats) between `footnotes` and `annotations` — pydantic
3276        // field order, which `preserve_order` lets us reproduce by rebuilding
3277        // the tail.
3278        if let Some(img) = image {
3279            let mut image = image_ref_json(img);
3280            // The displayed size, for the Pandoc writer only (#834):
3281            // docling's `ImageRef` has no field for it.
3282            if self.note_keys {
3283                if let Some([w, h]) = img.display_size {
3284                    image["_display"] = json!([w, h]);
3285                }
3286            }
3287            if let Some(obj) = item.as_object_mut() {
3288                let annotations = obj.remove("annotations").unwrap_or_else(|| json!([]));
3289                obj.insert("image".into(), image);
3290                obj.insert("annotations".into(), annotations);
3291            }
3292        }
3293        self.pictures.push(item);
3294        self_ref
3295    }
3296
3297    fn add_group(
3298        &mut self,
3299        label: &str,
3300        name: Option<&str>,
3301        layer: Option<ContentLayer>,
3302        nodes: &[Node],
3303        parent: &str,
3304    ) -> String {
3305        let self_ref = format!("#/groups/{}", self.groups.len());
3306        self.groups.push(Value::Null);
3307        // Everything the walk creates belongs to this group, so a non-body
3308        // layer (a hidden sheet) is stamped on the whole subtree afterwards —
3309        // docling puts the layer on the group *and* on every item under it.
3310        let mark = (
3311            self.texts.len(),
3312            self.tables.len(),
3313            self.pictures.len(),
3314            self.groups.len(),
3315        );
3316        let children: Vec<Value> = self
3317            .walk_into(nodes, &self_ref)
3318            .into_iter()
3319            .map(Child::into_value)
3320            .collect();
3321        let name = name.unwrap_or(if label == "inline" { "group" } else { label });
3322        let content_layer = layer.map_or("body", |l| l.value());
3323        self.groups[group_index(&self_ref)] = json!({
3324            "self_ref": self_ref,
3325            "parent": { "$ref": parent },
3326            "children": children,
3327            "content_layer": content_layer,
3328            "name": name,
3329            "label": label,
3330        });
3331        if layer.is_some() {
3332            let (t, tb, p, g) = mark;
3333            for item in self.texts[t..]
3334                .iter_mut()
3335                .enumerate()
3336                .map(|(k, item)| item.value_mut(t + k))
3337                .chain(self.tables[tb..].iter_mut().map(|t| &mut t.item))
3338                .chain(self.pictures[p..].iter_mut())
3339                .chain(self.groups[g..].iter_mut())
3340            {
3341                if let Some(obj) = item.as_object_mut() {
3342                    obj.insert("content_layer".into(), json!(content_layer));
3343                }
3344            }
3345        }
3346        self_ref
3347    }
3348
3349    /// Walk a slice of sibling nodes, returning each child's `$ref`; runs of
3350    /// list items are folded into list groups (one per sibling list).
3351    fn walk_into(&mut self, nodes: &[Node], parent: &str) -> Vec<Child> {
3352        // Siblings that all carry a creation rank (an XLSX sheet's items) are
3353        // *added* in that order — so `#/tables/N` and friends are numbered as
3354        // docling numbers them — while their refs keep the node order, which
3355        // is docling's position-sorted `children`.
3356        let seqs: Option<Vec<usize>> = nodes
3357            .iter()
3358            .map(|n| match n {
3359                Node::Prov { seq: Some(s), .. } => Some(*s),
3360                _ => None,
3361            })
3362            .collect();
3363        if let Some(seqs) = seqs.filter(|s| !s.is_empty()) {
3364            let mut order: Vec<usize> = (0..nodes.len()).collect();
3365            order.sort_by_key(|&i| seqs[i]);
3366            let mut slots: Vec<Vec<Child>> = (0..nodes.len()).map(|_| Vec::new()).collect();
3367            for i in order {
3368                if let Some(r) = self.add_node(&nodes[i], parent) {
3369                    slots[i].extend(self.pending_siblings.drain(..).map(Child::json));
3370                    slots[i].push(Child::Ref(r.into()));
3371                    slots[i].extend(self.pending_after.drain(..).map(Child::json));
3372                }
3373                if parent == "#/body" {
3374                    slots[i].extend(self.pending_body.drain(..).map(Child::json));
3375                }
3376            }
3377            return slots.into_iter().flatten().collect();
3378        }
3379        let mut children = Vec::new();
3380        let mut i = 0;
3381        while i < nodes.len() {
3382            if matches!(nodes[i], Node::ListItem { .. }) {
3383                let start = i;
3384                i += 1;
3385                loop {
3386                    match nodes.get(i) {
3387                        Some(Node::ListItem { .. }) => i += 1,
3388                        // Absorb an empty paragraph sitting between two list
3389                        // items (docling keeps the ListGroup contiguous).
3390                        Some(Node::Paragraph { text })
3391                            if text.is_empty()
3392                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
3393                        {
3394                            i += 1
3395                        }
3396                        _ => break,
3397                    }
3398                }
3399                let mut lists = Vec::new();
3400                self.add_sibling_lists(&nodes[start..i], parent, &mut lists);
3401                children.extend(lists.into_iter().map(Child::json));
3402            } else {
3403                if let Some(r) = self.add_node(&nodes[i], parent) {
3404                    children.extend(self.pending_siblings.drain(..).map(Child::json));
3405                    children.push(Child::Ref(r.into()));
3406                    children.extend(self.pending_after.drain(..).map(Child::json));
3407                }
3408                i += 1;
3409            }
3410            // Body-parented captions of items deeper in the tree follow the
3411            // top-level item they were created under (#390).
3412            if parent == "#/body" {
3413                children.extend(self.pending_body.drain(..).map(Child::json));
3414            }
3415        }
3416        children
3417    }
3418
3419    /// A run of list items may hold several *sibling* lists; emit one list group
3420    /// per sibling. The boundary is the backend's `first_in_list` flag on a
3421    /// base-level item — the same rule as the Markdown serializer's blank line
3422    /// (#385; the kind-flip and number-gap guesses are gone).
3423    fn add_sibling_lists(&mut self, run: &[Node], parent: &str, out: &mut Vec<Value>) {
3424        let base = level_of(&run[0]);
3425        let mut seg = 0;
3426        for k in 0..run.len() {
3427            let Node::ListItem {
3428                first_in_list,
3429                level,
3430                ..
3431            } = &run[k]
3432            else {
3433                continue;
3434            };
3435            if *level != base {
3436                continue; // nested item — handled inside add_list
3437            }
3438            if k > seg && *first_in_list {
3439                out.push(ref_value(self.add_list(&run[seg..k], parent)));
3440                seg = k;
3441            }
3442        }
3443        out.push(ref_value(self.add_list(&run[seg..], parent)));
3444    }
3445}
3446
3447fn level_of(node: &Node) -> u8 {
3448    match node {
3449        Node::ListItem { level, .. } => *level,
3450        _ => 0,
3451    }
3452}
3453
3454fn group_index(self_ref: &str) -> usize {
3455    self_ref.rsplit('/').next().unwrap().parse().unwrap()
3456}
3457
3458fn ref_index(self_ref: &str) -> Option<usize> {
3459    self_ref.rsplit('/').next()?.parse().ok()
3460}
3461
3462/// Merge the key/values of `extra` (an object) into `target` (an object).
3463fn merge(target: &mut Value, extra: Value) {
3464    if let (Some(t), Value::Object(e)) = (target.as_object_mut(), extra) {
3465        t.extend(e);
3466    }
3467}
3468
3469/// A JSON object of exactly these entries, in this order. The hot per-item
3470/// constructors use this instead of `json!`: the macro grows its map by
3471/// doubling (an 8-key item kept 14 slots) and deep-copies every interpolated
3472/// `Value` through `to_value`. On a long text-heavy PDF those item objects
3473/// *are* the export's footprint (the same reasoning as [`cell_value`]).
3474fn object<const N: usize>(entries: [(&str, Value); N]) -> Value {
3475    let mut m = serde_json::Map::with_capacity(N);
3476    for (k, v) in entries {
3477        m.insert(k.to_owned(), v);
3478    }
3479    Value::Object(m)
3480}
3481
3482/// A `{"$ref": r}` reference object.
3483fn ref_value(r: impl Into<String>) -> Value {
3484    object([("$ref", Value::String(r.into()))])
3485}
3486
3487/// Reverse [`crate`]'s Markdown text escaping (HTML entities + `\_`).
3488fn unescape_text(s: &str) -> String {
3489    s.replace("&lt;", "<")
3490        .replace("&gt;", ">")
3491        .replace("&amp;", "&")
3492        .replace("\\_", "_")
3493}
3494
3495/// 64-bit FNV-1a, a stand-in for docling's `binary_hash` (we lack the source bytes
3496/// at export time; the value only needs to be a stable u64).
3497fn fnv1a(s: &str) -> u64 {
3498    let mut h: u64 = 0xcbf29ce484222325;
3499    for b in s.bytes() {
3500        h ^= b as u64;
3501        h = h.wrapping_mul(0x100000001b3);
3502    }
3503    h
3504}
3505
3506#[cfg(test)]
3507mod tests {
3508    #[cfg(feature = "preserve-order")]
3509    use crate::ImageMode;
3510    #[cfg(feature = "preserve-order")]
3511    use crate::PictureImage;
3512    use crate::{CaptionParent, ContentLayer, DoclingDocument, Node, Table};
3513    use serde_json::Value;
3514
3515    fn cell_at(text: &str, row: usize, col: usize, col_span: usize) -> crate::TableCell {
3516        crate::TableCell {
3517            text: text.into(),
3518            bbox: None,
3519            start_row: row,
3520            start_col: col,
3521            row_span: 1,
3522            col_span,
3523            column_header: row == 0,
3524            row_header: false,
3525            row_section: false,
3526        }
3527    }
3528
3529    /// First-class cells past the rows: rectangular rows are the grid and
3530    /// clip them (docling's `TableData.grid` on USPTO's overrun replicas);
3531    /// ragged rows — an xlsx table compacted by `skip_empty_cells` (#271) —
3532    /// are no grid, so the cells' extent sizes it and the omitted positions
3533    /// come back as empty filler cells in `grid` only.
3534    #[test]
3535    fn ragged_rows_take_their_grid_from_first_class_cells() {
3536        let cells = vec![
3537            cell_at("h0", 0, 0, 1),
3538            cell_at("h2", 0, 2, 1),
3539            cell_at("wide", 1, 0, 3),
3540        ];
3541        let export = |rows: Vec<Vec<String>>| -> Value {
3542            let mut doc = DoclingDocument::new("t");
3543            doc.push(Node::Table(Table {
3544                rows,
3545                cells: Some(cells.clone()),
3546                ..Table::default()
3547            }));
3548            let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3549            v["tables"][0]["data"].clone()
3550        };
3551        // Compacted rows: 2 and 3 wide, the cells say the grid is 3 wide.
3552        let data = export(vec![
3553            vec!["h0".into(), "h2".into()],
3554            vec!["wide".into(), "wide".into(), "wide".into()],
3555        ]);
3556        assert_eq!(data["num_rows"], 2);
3557        assert_eq!(data["num_cols"], 3);
3558        assert_eq!(data["table_cells"].as_array().unwrap().len(), 3);
3559        let row0: Vec<&str> = data["grid"][0]
3560            .as_array()
3561            .unwrap()
3562            .iter()
3563            .map(|c| c["text"].as_str().unwrap())
3564            .collect();
3565        assert_eq!(row0, ["h0", "", "h2"]);
3566        assert_eq!(data["table_cells"][2]["col_span"], 3);
3567        // Rectangular rows narrower than the cells: the rows win, the cells
3568        // are clipped to them exactly as before.
3569        let data = export(vec![
3570            vec!["h0".into(), "h2".into()],
3571            vec!["wide".into(), "wide".into()],
3572        ]);
3573        assert_eq!(data["num_cols"], 2);
3574        assert_eq!(data["grid"][0].as_array().unwrap().len(), 2);
3575    }
3576
3577    #[cfg(feature = "preserve-order")]
3578    fn doc_with_image() -> DoclingDocument {
3579        let mut doc = DoclingDocument::new("t");
3580        doc.push(Node::Picture {
3581            caption: Some("Fig 1".into()),
3582            caption_href: None,
3583            image: Some(PictureImage {
3584                dpi: crate::PictureImage::DEFAULT_DPI,
3585                mimetype: "image/png".into(),
3586                width: 4,
3587                height: 2,
3588                data: b"foobar".to_vec(),
3589                display_size: None,
3590            }),
3591            classification: None,
3592            description: None,
3593            caption_parent: Default::default(),
3594            caption_location: None,
3595        });
3596        doc
3597    }
3598
3599    /// #402: a deck's speaker notes are content, and docling puts them in the
3600    /// JSON on the `notes` layer so a consumer reading only JSON can pick them
3601    /// out. Markdown still serializes the body layer alone, and page furniture
3602    /// stays out of the JSON, where docling does keep it.
3603    #[test]
3604    fn notes_layer_items_reach_the_json_but_furniture_does_not() {
3605        let mut doc = DoclingDocument::new("t");
3606        doc.push(Node::Heading {
3607            level: 1,
3608            text: "Slide One".into(),
3609        });
3610        doc.push(Node::Furniture {
3611            layer: ContentLayer::Notes,
3612            inner: Box::new(Node::Located {
3613                location: [0, 0, 0, 0],
3614                inner: Box::new(Node::Paragraph {
3615                    text: "Speaker note for slide 1.".into(),
3616                }),
3617            }),
3618        });
3619        doc.push(Node::Furniture {
3620            layer: ContentLayer::Furniture,
3621            inner: Box::new(Node::Paragraph {
3622                text: "page header".into(),
3623            }),
3624        });
3625
3626        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3627        let texts = v["texts"].as_array().unwrap();
3628        assert_eq!(
3629            texts
3630                .iter()
3631                .map(|t| (
3632                    t["label"].as_str().unwrap(),
3633                    t["content_layer"].as_str().unwrap(),
3634                    t["text"].as_str().unwrap()
3635                ))
3636                .collect::<Vec<_>>(),
3637            vec![
3638                ("title", "body", "Slide One"),
3639                ("text", "notes", "Speaker note for slide 1."),
3640            ],
3641            "the note is carried on its own layer; the furniture is not carried"
3642        );
3643        // The body layer is what Markdown serializes, so it does not change.
3644        assert_eq!(doc.export_to_markdown(), "# Slide One\n");
3645    }
3646
3647    /// #410: a backend that describes merged ranges only as continuation
3648    /// flags (xlsx `<mergeCell>`, docx `gridSpan`/`vMerge`) gets docling's
3649    /// one-`TableCell`-per-range JSON: the anchor's offsets and spans, the
3650    /// entry repeated across the grid positions it covers — not a 1×1 cell
3651    /// per position with the text copied into each.
3652    #[test]
3653    fn continuation_flags_become_spanning_cells() {
3654        let mut doc = DoclingDocument::new("t");
3655        // A1:C2 merged ("merged"), then a plain row underneath.
3656        let rows = vec![
3657            vec!["merged".to_string(), "merged".into(), "merged".into()],
3658            vec!["merged".to_string(), "merged".into(), "merged".into()],
3659            vec!["a".to_string(), "b".into(), "c".into()],
3660        ];
3661        doc.push(Node::Table(crate::Table {
3662            footnotes: Vec::new(),
3663            footnotes_as_runs: false,
3664            rows,
3665            location: None,
3666            structure: Some(crate::TableStructure {
3667                header_row: vec![true, false, false],
3668                col_continuation: vec![
3669                    vec![false, true, true],
3670                    vec![false, true, true],
3671                    vec![false, false, false],
3672                ],
3673                row_continuation: vec![
3674                    vec![false, false, false],
3675                    vec![true, true, true],
3676                    vec![false, false, false],
3677                ],
3678                row_header: Vec::new(),
3679                col_header: Vec::new(),
3680            }),
3681            cell_blocks: None,
3682            cells: None,
3683            caption: None,
3684            caption_parent: Default::default(),
3685            caption_location: None,
3686            document_index: false,
3687        }));
3688        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3689        let data = &v["tables"][0]["data"];
3690        assert_eq!(data["num_rows"], 3);
3691        assert_eq!(data["num_cols"], 3);
3692        let cells = data["table_cells"].as_array().unwrap();
3693        assert_eq!(
3694            cells.len(),
3695            4,
3696            "one cell for the range, three for the plain row"
3697        );
3698        assert_eq!(
3699            cells[0],
3700            serde_json::json!({
3701                "row_span": 2, "col_span": 3,
3702                "start_row_offset_idx": 0, "end_row_offset_idx": 2,
3703                "start_col_offset_idx": 0, "end_col_offset_idx": 3,
3704                "text": "merged", "column_header": true, "row_header": false,
3705                "row_section": false, "fillable": false,
3706            })
3707        );
3708        assert_eq!(cells[1]["text"], "a");
3709        assert_eq!(cells[1]["row_span"], 1);
3710        assert_eq!(cells[1]["column_header"], false);
3711        // The grid repeats the range's entry at every position it covers.
3712        let grid = data["grid"].as_array().unwrap();
3713        assert_eq!(grid.len(), 3);
3714        for (r, row) in grid.iter().take(2).enumerate() {
3715            for (c, cell) in row.as_array().unwrap().iter().enumerate() {
3716                assert_eq!(*cell, cells[0], "grid[{r}][{c}]");
3717            }
3718        }
3719        assert_eq!(grid[2][2]["text"], "c");
3720    }
3721
3722    /// A [`Node::Prov`] wrapper is docling's provenance verbatim — the exact
3723    /// box in a top-left origin, the backend's charspan — and the page marker
3724    /// before it sizes the page; a chart's caption becomes a sibling of the
3725    /// picture in the container, listed first, sharing the chart's box with
3726    /// a charspan over its text. That is the JSON shape of an XLSX sheet.
3727    #[test]
3728    fn exact_provenance_pages_and_chart_captions_follow_docling() {
3729        let mut doc = DoclingDocument::new("t");
3730        doc.push(Node::PageInfo {
3731            page_no: 1,
3732            width: 3.0,
3733            height: 4.0,
3734        });
3735        let table = crate::Table {
3736            rows: vec![vec!["a".to_string(), "b".into()]],
3737            ..Default::default()
3738        };
3739        doc.push(Node::Group {
3740            label: "sheet".into(),
3741            name: Some("Data".into()),
3742            layer: None,
3743            children: vec![
3744                // Node order is the position-sorted one; creation order (the
3745                // `seq`) had the chart first — so the chart is `#/pictures/0`
3746                // *and* its caption `#/texts/0`, while the table stays the
3747                // group's first child.
3748                Node::Prov {
3749                    page_no: 1,
3750                    bbox: [0.0, 0.0, 3.0, 4.0],
3751                    charspan: [0, 0],
3752                    bottom_left: false,
3753                    seq: Some(1),
3754                    inner: Box::new(Node::Table(table.clone())),
3755                },
3756                Node::Prov {
3757                    page_no: 1,
3758                    bbox: [0.0, 1.0, 1.0, 1.0],
3759                    charspan: [0, 0],
3760                    bottom_left: false,
3761                    seq: Some(0),
3762                    inner: Box::new(Node::Chart {
3763                        kind: "bar_chart".into(),
3764                        table,
3765                        caption: Some("Sales".into()),
3766                        location: Some([0, 128, 170, 128]),
3767                    }),
3768                },
3769            ],
3770        });
3771        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3772        assert_eq!(
3773            v["pages"],
3774            serde_json::json!({"1": {"size": {"width": 3.0, "height": 4.0}, "page_no": 1}})
3775        );
3776        assert_eq!(
3777            v["tables"][0]["prov"],
3778            serde_json::json!([{
3779                "page_no": 1,
3780                "bbox": {"l": 0.0, "t": 0.0, "r": 3.0, "b": 4.0, "coord_origin": "TOPLEFT"},
3781                "charspan": [0, 0],
3782            }])
3783        );
3784        assert_eq!(v["tables"][0]["data"]["orientation"], "rot_0");
3785        // The caption is the group's child *before* the picture, parented to
3786        // the group, and referenced by the picture.
3787        let sheet = &v["groups"][0];
3788        assert_eq!(
3789            sheet["children"],
3790            serde_json::json!([
3791                {"$ref": "#/tables/0"}, {"$ref": "#/texts/0"}, {"$ref": "#/pictures/0"}
3792            ])
3793        );
3794        let cap = &v["texts"][0];
3795        assert_eq!(cap["label"], "caption");
3796        assert_eq!(cap["parent"], serde_json::json!({"$ref": "#/groups/0"}));
3797        assert_eq!(cap["prov"][0]["charspan"], serde_json::json!([0, 5]));
3798        assert_eq!(cap["prov"][0]["bbox"]["b"], 1.0);
3799        let pic = &v["pictures"][0];
3800        assert_eq!(pic["captions"], serde_json::json!([{"$ref": "#/texts/0"}]));
3801        assert_eq!(pic["prov"][0]["charspan"], serde_json::json!([0, 0]));
3802        assert_eq!(pic["prov"][0]["bbox"]["coord_origin"], "TOPLEFT");
3803        assert_eq!(
3804            pic["meta"]["classification"]["predictions"][0]["class_name"],
3805            "bar_chart"
3806        );
3807        assert_eq!(pic["meta"]["tabular_chart"]["chart_data"]["num_cols"], 2);
3808    }
3809
3810    /// An all-zero location is the "no geometry" sentinel — a slide's speaker
3811    /// notes carry one — and docling writes it as a zero bbox, not as a box
3812    /// spanning the whole page, which is what denormalizing the grid gives.
3813    #[test]
3814    fn a_zero_location_is_a_zero_bbox_not_the_whole_page() {
3815        let mut doc = DoclingDocument::new("t");
3816        doc.push(Node::PageInfo {
3817            page_no: 1,
3818            width: 12192000.0,
3819            height: 6858000.0,
3820        });
3821        doc.push(Node::Furniture {
3822            layer: ContentLayer::Notes,
3823            inner: Box::new(Node::Located {
3824                location: [0, 0, 0, 0],
3825                inner: Box::new(Node::Paragraph {
3826                    text: "a note".into(),
3827                }),
3828            }),
3829        });
3830        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3831        let prov = &v["texts"][0]["prov"][0];
3832        assert_eq!(prov["page_no"], 1);
3833        assert_eq!(prov["charspan"], serde_json::json!([0, 6]));
3834        assert_eq!(
3835            prov["bbox"],
3836            serde_json::json!({"l": 0.0, "t": 0.0, "r": 0.0, "b": 0.0, "coord_origin": "BOTTOMLEFT"})
3837        );
3838        // The page itself is recorded at its true size.
3839        assert_eq!(
3840            v["pages"]["1"]["size"],
3841            serde_json::json!({"width": 12192000.0, "height": 6858000.0})
3842        );
3843    }
3844
3845    /// #171: PageInfo markers become the `pages` map, and `Located` wrappers /
3846    /// node-level locations become per-item `prov` — the 0–511 grid
3847    /// denormalized against the page into BOTTOMLEFT points. Without markers
3848    /// (every declarative backend) the JSON stays exactly as before: empty
3849    /// `pages`, `prov: []` even for located nodes.
3850    /// #609: a PDF caption and a checkbox item carry their own page and box.
3851    /// docling's reading-order model gives every caption the cluster it came
3852    /// from (`_add_caption_or_footnote`), not its picture's or table's, and
3853    /// a checkbox is a text item like any other.
3854    #[test]
3855    fn captions_and_checkboxes_carry_their_own_prov() {
3856        let mut doc = DoclingDocument::new("t");
3857        doc.push(Node::PageInfo {
3858            page_no: 1,
3859            width: 512.0,
3860            height: 512.0,
3861        });
3862        doc.push(Node::Located {
3863            location: [64, 64, 448, 256],
3864            inner: Box::new(Node::Picture {
3865                caption: Some("Figure 1".into()),
3866                caption_href: None,
3867                image: None,
3868                classification: None,
3869                description: None,
3870                caption_parent: CaptionParent::Item,
3871                caption_location: Some([64, 264, 448, 280]),
3872            }),
3873        });
3874        doc.push(Node::PageInfo {
3875            page_no: 2,
3876            width: 512.0,
3877            height: 512.0,
3878        });
3879        doc.push(Node::Located {
3880            location: [64, 120, 448, 300],
3881            inner: Box::new(Node::Table(Table {
3882                rows: vec![vec!["a".into()]],
3883                caption: Some("Table 1".into()),
3884                caption_parent: CaptionParent::Item,
3885                caption_location: Some([64, 100, 300, 112]),
3886                ..Table::default()
3887            })),
3888        });
3889        doc.push(Node::Located {
3890            location: [64, 320, 200, 332],
3891            inner: Box::new(Node::CheckboxItem {
3892                checked: false,
3893                text: "First option".into(),
3894            }),
3895        });
3896        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3897        let texts = v["texts"].as_array().unwrap();
3898        let by_text = |t: &str| texts.iter().find(|x| x["text"] == t).expect(t).clone();
3899        let bbox = |p: &Value| {
3900            let b = &p["prov"][0]["bbox"];
3901            [&b["l"], &b["t"], &b["r"], &b["b"]].map(|x| x.as_f64().unwrap())
3902        };
3903        // Figure 1: its own box (grid == points on a 512 page, flipped to
3904        // BOTTOMLEFT), not the picture's.
3905        let fig = by_text("Figure 1");
3906        assert_eq!(fig["prov"][0]["page_no"], 1);
3907        assert_eq!(bbox(&fig), [64.0, 248.0, 448.0, 232.0]);
3908        assert_eq!(fig["prov"][0]["charspan"], serde_json::json!([0, 8]));
3909        assert_eq!(fig["parent"]["$ref"], "#/pictures/0");
3910        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
3911        // Table 1 on page 2, its own box; the table keeps its own.
3912        let tab = by_text("Table 1");
3913        assert_eq!(tab["prov"][0]["page_no"], 2);
3914        assert_eq!(bbox(&tab), [64.0, 412.0, 300.0, 400.0]);
3915        assert_eq!(v["tables"][0]["prov"][0]["bbox"]["t"], 392.0);
3916        // The checkbox item.
3917        let cb = by_text("First option");
3918        assert_eq!(cb["label"], "checkbox_unselected");
3919        assert_eq!(cb["prov"][0]["page_no"], 2);
3920        assert_eq!(bbox(&cb), [64.0, 192.0, 200.0, 180.0]);
3921        assert!(texts
3922            .iter()
3923            .all(|t| !t["prov"].as_array().unwrap().is_empty()));
3924
3925        // Without a caption box (every declarative backend) the caption
3926        // still has no prov, and nothing else moves.
3927        let mut plain = DoclingDocument::new("t");
3928        plain.push(Node::PageInfo {
3929            page_no: 1,
3930            width: 512.0,
3931            height: 512.0,
3932        });
3933        plain.push(Node::Located {
3934            location: [64, 64, 448, 256],
3935            inner: Box::new(Node::Picture {
3936                caption: Some("Figure 1".into()),
3937                caption_href: None,
3938                image: None,
3939                classification: None,
3940                description: None,
3941                caption_parent: CaptionParent::Item,
3942                caption_location: None,
3943            }),
3944        });
3945        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
3946        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
3947        assert_eq!(v["pictures"][0]["prov"][0]["bbox"]["t"], 448.0);
3948    }
3949
3950    #[test]
3951    fn page_markers_produce_pages_and_prov() {
3952        let mut doc = DoclingDocument::new("t");
3953        doc.push(Node::PageInfo {
3954            page_no: 1,
3955            width: 512.0,
3956            height: 1024.0,
3957        });
3958        doc.push(Node::Located {
3959            location: [128, 64, 256, 128], // quarter/eighth points of the grid
3960            inner: Box::new(Node::Paragraph {
3961                text: "hello".into(),
3962            }),
3963        });
3964        doc.push(Node::Table(Table {
3965            rows: vec![vec!["a".into()]],
3966            location: Some([0, 0, 512, 512]),
3967            ..Table::default()
3968        }));
3969        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
3970        assert_eq!(v["pages"]["1"]["page_no"], 1);
3971        assert_eq!(v["pages"]["1"]["size"]["width"], 512.0);
3972        assert_eq!(v["pages"]["1"]["size"]["height"], 1024.0);
3973        // 512-wide page: grid x scales 1:1; 1024-high: grid y doubles, then
3974        // flips to the BOTTOMLEFT origin (t from grid-top 64 → 1024-128=896).
3975        let prov = &v["texts"][0]["prov"][0];
3976        assert_eq!(prov["page_no"], 1);
3977        assert_eq!(prov["bbox"]["l"], 128.0);
3978        assert_eq!(prov["bbox"]["t"], 896.0);
3979        assert_eq!(prov["bbox"]["r"], 256.0);
3980        assert_eq!(prov["bbox"]["b"], 768.0);
3981        assert_eq!(prov["bbox"]["coord_origin"], "BOTTOMLEFT");
3982        assert_eq!(prov["charspan"][1], 5);
3983        // The table adopts its own location field; charspan is [0, 0].
3984        let tprov = &v["tables"][0]["prov"][0];
3985        assert_eq!(tprov["bbox"]["t"], 1024.0);
3986        assert_eq!(tprov["bbox"]["b"], 0.0);
3987        assert_eq!(tprov["charspan"][1], 0);
3988
3989        // No markers → the pre-#171 shape, byte for byte.
3990        let mut plain = DoclingDocument::new("t");
3991        plain.push(Node::Located {
3992            location: [1, 2, 3, 4],
3993            inner: Box::new(Node::Paragraph { text: "x".into() }),
3994        });
3995        let v: Value = serde_json::from_str(&plain.export_to_json()).unwrap();
3996        assert_eq!(v["pages"], serde_json::json!({}));
3997        assert_eq!(v["texts"][0]["prov"], serde_json::json!([]));
3998    }
3999
4000    /// PDF page headers/footers reach the JSON as docling writes them:
4001    /// body-parented text items on the furniture layer, with their box.
4002    #[test]
4003    fn page_furniture_becomes_furniture_layer_text() {
4004        let mut doc = DoclingDocument::new("t");
4005        doc.push(Node::PageInfo {
4006            page_no: 1,
4007            width: 512.0,
4008            height: 512.0,
4009        });
4010        doc.push(Node::PageFurniture {
4011            footer: false,
4012            location: [10, 0, 100, 20],
4013            text: "Chapter 1".into(),
4014        });
4015        doc.push(Node::Paragraph {
4016            text: "body".into(),
4017        });
4018        doc.push(Node::PageFurniture {
4019            footer: true,
4020            location: [400, 490, 500, 512],
4021            text: "1.10.2".into(),
4022        });
4023        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4024        let texts = v["texts"].as_array().unwrap();
4025        assert_eq!(texts.len(), 3);
4026        assert_eq!(texts[0]["label"], "page_header");
4027        assert_eq!(texts[0]["content_layer"], "furniture");
4028        assert_eq!(texts[0]["parent"]["$ref"], "#/body");
4029        assert_eq!(texts[0]["prov"][0]["bbox"]["l"], 10.0);
4030        assert_eq!(texts[1]["content_layer"], "body");
4031        assert_eq!(texts[1]["prov"], serde_json::json!([]));
4032        assert_eq!(texts[2]["label"], "page_footer");
4033        assert_eq!(texts[2]["text"], "1.10.2");
4034        assert_eq!(texts[2]["content_layer"], "furniture");
4035    }
4036
4037    #[test]
4038    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4039    fn picture_image_in_markdown_modes_and_json() {
4040        let doc = doc_with_image();
4041        // placeholder (default) ignores the image
4042        assert!(doc.export_to_markdown().contains("<!-- image -->"));
4043        // embedded → base64 data URI (b"foobar" → "Zm9vYmFy")
4044        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Embedded, "artifacts");
4045        assert!(
4046            md.contains("![Image](data:image/png;base64,Zm9vYmFy)"),
4047            "got:\n{md}"
4048        );
4049        assert!(files.is_empty());
4050        // referenced → file link + collected bytes
4051        let (md, files) = doc.export_to_markdown_with_images(ImageMode::Referenced, "artifacts");
4052        assert!(
4053            md.contains("![Image](artifacts/image_000000.png)"),
4054            "got:\n{md}"
4055        );
4056        assert_eq!(
4057            files,
4058            vec![("artifacts/image_000000.png".to_string(), b"foobar".to_vec())]
4059        );
4060        // JSON carries the ImageRef (data URI + size — floats, as docling's
4061        // `Size` is — placed before `annotations`).
4062        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4063        assert_eq!(v["pictures"][0]["image"]["mimetype"], "image/png");
4064        assert_eq!(v["pictures"][0]["image"]["size"]["width"], 4.0);
4065        let keys: Vec<&str> = v["pictures"][0]
4066            .as_object()
4067            .unwrap()
4068            .keys()
4069            .map(String::as_str)
4070            .collect();
4071        assert_eq!(&keys[keys.len() - 2..], ["image", "annotations"]);
4072        assert_eq!(
4073            v["pictures"][0]["image"]["uri"],
4074            "data:image/png;base64,Zm9vYmFy"
4075        );
4076    }
4077
4078    /// #1258: the placeholder JSON drops each picture's `image` and nothing
4079    /// else, and the streamed writer agrees with the `Value` byte for byte.
4080    #[test]
4081    fn placeholder_json_omits_picture_images() {
4082        let doc = doc_with_image();
4083        let full = doc.export_to_json_value();
4084        let v = doc.export_to_json_value_with_images(ImageMode::Placeholder);
4085        assert!(v["pictures"][0].get("image").is_none(), "{v}");
4086        let mut expected = full.clone();
4087        expected["pictures"][0]
4088            .as_object_mut()
4089            .unwrap()
4090            .remove("image");
4091        assert_eq!(v, expected);
4092        assert_eq!(
4093            doc.export_to_json_value_with_images(ImageMode::Embedded),
4094            full
4095        );
4096        let mut streamed = Vec::new();
4097        doc.write_json_pretty_with_images(&mut streamed, &[], ImageMode::Placeholder)
4098            .unwrap();
4099        assert_eq!(streamed, serde_json::to_vec_pretty(&v).unwrap());
4100        let mut kept = Vec::new();
4101        doc.write_json_pretty_with_images(&mut kept, &[], ImageMode::Embedded)
4102            .unwrap();
4103        assert_eq!(kept, serde_json::to_vec_pretty(&full).unwrap());
4104    }
4105
4106    #[test]
4107    fn exports_docling_schema() {
4108        let mut doc = DoclingDocument::new("t");
4109        doc.push(Node::Heading {
4110            level: 1,
4111            text: "Title".into(),
4112        });
4113        doc.push(Node::Heading {
4114            level: 2,
4115            text: "Sec".into(),
4116        });
4117        doc.push(Node::Paragraph {
4118            text: "Body &amp; more".into(),
4119        }); // markdown-escaped
4120        doc.push(Node::ListItem {
4121            ordered: false,
4122            number: 0,
4123            first_in_list: true,
4124            text: "one".into(),
4125            level: 0,
4126            marker: None,
4127            location: None,
4128            split: None,
4129            dclx: None,
4130            href: None,
4131            layer: None,
4132        });
4133        doc.push(Node::ListItem {
4134            ordered: false,
4135            number: 0,
4136            first_in_list: false,
4137            text: "two".into(),
4138            level: 0,
4139            marker: None,
4140            location: None,
4141            split: None,
4142            dclx: None,
4143            href: None,
4144            layer: None,
4145        });
4146        doc.push(Node::Table(Table {
4147            footnotes: Vec::new(),
4148            footnotes_as_runs: false,
4149            rows: vec![vec!["A".into(), "B".into()]],
4150            location: None,
4151            structure: None,
4152            cell_blocks: None,
4153            cells: None,
4154            caption: None,
4155            caption_parent: Default::default(),
4156            caption_location: None,
4157            document_index: false,
4158        }));
4159
4160        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4161        assert_eq!(v["schema_name"], "DoclingDocument");
4162        assert_eq!(v["version"], "1.11.0");
4163        assert_eq!(v["texts"][0]["label"], "title");
4164        assert_eq!(v["texts"][1]["label"], "section_header");
4165        assert_eq!(v["texts"][1]["level"], 1); // heading level 2 → docling level 1
4166        assert_eq!(v["texts"][2]["text"], "Body & more"); // un-escaped for the wire format
4167                                                          // consecutive list items fold into one list group, parented to it
4168        assert_eq!(v["groups"][0]["label"], "list");
4169        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
4170        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
4171        assert_eq!(v["texts"][3]["marker"], "-");
4172        // table grid + header flag
4173        assert_eq!(v["tables"][0]["data"]["num_cols"], 2);
4174        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["column_header"], true);
4175    }
4176    /// A named group on a non-body layer — docling's hidden spreadsheet sheet:
4177    /// the group carries the sheet's name and the `invisible` layer, and every
4178    /// item inside it carries the layer too.
4179    #[test]
4180    fn a_layered_group_stamps_its_whole_subtree() {
4181        let doc = DoclingDocument {
4182            name: "s".into(),
4183            nodes: vec![
4184                Node::Group {
4185                    label: "sheet".into(),
4186                    name: Some("Sheet1".into()),
4187                    layer: None,
4188                    children: vec![Node::Paragraph {
4189                        text: "visible".into(),
4190                    }],
4191                },
4192                Node::Group {
4193                    label: "sheet".into(),
4194                    name: Some("Sheet2".into()),
4195                    layer: Some(ContentLayer::Invisible),
4196                    children: vec![Node::Paragraph {
4197                        text: "hidden".into(),
4198                    }],
4199                },
4200            ],
4201            ..DoclingDocument::new("s")
4202        };
4203        let v = crate::json::to_json(&doc);
4204        assert_eq!(v["groups"][0]["label"], "sheet");
4205        assert_eq!(v["groups"][0]["name"], "Sheet1");
4206        assert_eq!(v["groups"][0]["content_layer"], "body");
4207        assert_eq!(v["texts"][0]["content_layer"], "body");
4208        assert_eq!(v["groups"][1]["name"], "Sheet2");
4209        assert_eq!(v["groups"][1]["content_layer"], "invisible");
4210        assert_eq!(v["texts"][1]["content_layer"], "invisible");
4211        // The group's children are the items, and the body holds the groups.
4212        assert_eq!(v["groups"][1]["children"][0]["$ref"], "#/texts/1");
4213        assert_eq!(v["body"]["children"][1]["$ref"], "#/groups/1");
4214    }
4215
4216    /// A backend-built item tree is serialized as it is: items numbered in
4217    /// creation order per bucket (a field region's part texts included), the
4218    /// tree's parents / children / layers, docling's field order for
4219    /// `formatting`, `hyperlink`, `level`, `enumerated`/`marker`, a rich
4220    /// cell's `ref` on `table_cells` only, raw cell text.
4221    /// The DOCX tree's extras: an item `delete`d (docling's `delete_items`,
4222    /// the spacer between two items of a resumed list) is neither written nor
4223    /// numbered, `comments` back-refs sit between `prov` and `orig`, and a
4224    /// chart picture carries `classification` plus `tabular_chart`.
4225    #[test]
4226    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4227    fn deleted_items_comment_refs_and_chart_meta_in_the_tree() {
4228        use crate::tree::{ItemTree, TreeKind};
4229        let mut t = ItemTree::default();
4230        let text = |txt: &str| TreeKind::Text {
4231            label: "text".into(),
4232            text: txt.into(),
4233            orig: None,
4234            formatting: None,
4235            hyperlink: None,
4236            level: None,
4237            list: None,
4238        };
4239        let a = t.add(None, None, text("a"));
4240        let blank = t.add(None, None, text(""));
4241        let b = t.add(None, None, text("b"));
4242        t.delete(blank);
4243        let group = t.add(
4244            None,
4245            Some(ContentLayer::Notes),
4246            TreeKind::Group {
4247                label: "comment_section".into(),
4248                name: "comment-0".into(),
4249            },
4250        );
4251        t.add(Some(group), Some(ContentLayer::Notes), text("note"));
4252        t.items[a].comments.push(group);
4253        t.add(
4254            None,
4255            None,
4256            TreeKind::Picture {
4257                captions: Vec::new(),
4258                image: None,
4259                extra_classes: Vec::new(),
4260                classification: Some("bar_chart".into()),
4261                description: None,
4262                confidence: None,
4263                chart: Some(Table {
4264                    rows: vec![vec!["".into(), "s".into()], vec!["c".into(), "1".into()]],
4265                    ..Table::default()
4266                }),
4267                dpi: None,
4268            },
4269        );
4270        assert_eq!(t.last_text(), Some(4), "the note; the blank is skipped");
4271        assert_eq!(t.bucket_index(b), 1, "numbered past the deleted item");
4272        let mut doc = DoclingDocument::new("t");
4273        doc.tree = Some(t);
4274        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4275        let texts = v["texts"].as_array().unwrap();
4276        assert_eq!(texts.len(), 3);
4277        assert_eq!(texts[1]["text"], "b");
4278        assert_eq!(texts[1]["self_ref"], "#/texts/1");
4279        assert_eq!(
4280            v["body"]["children"],
4281            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}, {"$ref": "#/groups/0"}, {"$ref": "#/pictures/0"}])
4282        );
4283        let keys: Vec<&str> = texts[0]
4284            .as_object()
4285            .unwrap()
4286            .keys()
4287            .map(String::as_str)
4288            .collect();
4289        assert_eq!(
4290            keys,
4291            vec![
4292                "self_ref",
4293                "parent",
4294                "children",
4295                "content_layer",
4296                "label",
4297                "prov",
4298                "comments",
4299                "orig",
4300                "text"
4301            ]
4302        );
4303        assert_eq!(
4304            texts[0]["comments"],
4305            serde_json::json!([{"$ref": "#/groups/0"}])
4306        );
4307        assert!(texts[1].get("comments").is_none());
4308        let meta = &v["pictures"][0]["meta"];
4309        assert_eq!(
4310            meta["classification"]["predictions"][0]["class_name"],
4311            "bar_chart"
4312        );
4313        assert_eq!(meta["tabular_chart"]["chart_data"]["num_rows"], 2);
4314    }
4315
4316    /// A tree item's `TreeProv` is written verbatim — a raw EMU box with
4317    /// whatever origin tag the backend set (`BOTTOMLEFT` here) and a per-item
4318    /// charspan, a note's zero `TOPLEFT` box — a picture's `image.dpi` is the file's when the backend
4319    /// read one, an item without provenance writes `prov: []`, and the page
4320    /// map still comes from the flat stream's markers.
4321    #[test]
4322    fn tree_items_carry_exact_provenance_and_dpi() {
4323        use crate::tree::{ItemTree, TreeKind, TreeProv};
4324        let text = |label: &str, t: &str| TreeKind::Text {
4325            label: label.into(),
4326            text: t.into(),
4327            orig: None,
4328            formatting: None,
4329            hyperlink: None,
4330            level: None,
4331            list: None,
4332        };
4333        let mut t = ItemTree::default();
4334        let slide = t.add(
4335            None,
4336            None,
4337            TreeKind::Group {
4338                label: "chapter".into(),
4339                name: "slide-0".into(),
4340            },
4341        );
4342        t.add_with_prov(
4343            Some(slide),
4344            None,
4345            text("paragraph", "héllo"),
4346            TreeProv {
4347                page_no: 1,
4348                bbox: [914400.0, 1828800.0, 2743200.0, 457200.0],
4349                bottom_left: true,
4350                charspan: [0, 5],
4351            },
4352        );
4353        t.add_with_prov(
4354            Some(slide),
4355            None,
4356            TreeKind::Picture {
4357                captions: Vec::new(),
4358                image: Some(crate::PictureImage {
4359                    dpi: crate::PictureImage::DEFAULT_DPI,
4360                    mimetype: "image/png".into(),
4361                    width: 2,
4362                    height: 2,
4363                    data: vec![0],
4364                    display_size: None,
4365                }),
4366                extra_classes: Vec::new(),
4367                classification: None,
4368                description: None,
4369                confidence: None,
4370                chart: None,
4371                dpi: Some(300),
4372            },
4373            TreeProv {
4374                page_no: 1,
4375                bbox: [0.0; 4],
4376                bottom_left: false,
4377                charspan: [0, 0],
4378            },
4379        );
4380        t.add(
4381            Some(slide),
4382            Some(ContentLayer::Notes),
4383            text("text", "no geometry"),
4384        );
4385        let mut doc = DoclingDocument::new("t");
4386        doc.push(Node::PageInfo {
4387            page_no: 1,
4388            width: 9144000.0,
4389            height: 6858000.0,
4390        });
4391        doc.tree = Some(t);
4392        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4393        assert_eq!(
4394            v["texts"][0]["prov"],
4395            serde_json::json!([{
4396                "page_no": 1,
4397                "bbox": { "l": 914400.0, "t": 1828800.0, "r": 2743200.0, "b": 457200.0, "coord_origin": "BOTTOMLEFT" },
4398                "charspan": [0, 5],
4399            }])
4400        );
4401        assert_eq!(v["texts"][0]["label"], "paragraph");
4402        assert_eq!(
4403            v["pictures"][0]["prov"][0]["bbox"]["coord_origin"],
4404            "TOPLEFT"
4405        );
4406        assert_eq!(v["pictures"][0]["image"]["dpi"], 300);
4407        assert_eq!(v["texts"][1]["prov"], serde_json::json!([]));
4408        assert_eq!(v["texts"][1]["content_layer"], "notes");
4409        assert_eq!(v["pages"]["1"]["size"]["width"], 9144000.0);
4410        assert_eq!(v["pages"]["1"]["page_no"], 1);
4411    }
4412
4413    /// docling-core's `validate_document` clamps every provenance box (and a
4414    /// one-page table's cell boxes) into its page — the state every
4415    /// `ConversionResult` leaves a document in, so the state docling's JSON
4416    /// shows. A box on a page the document does not describe is left alone.
4417    #[test]
4418    fn provenance_boxes_are_clamped_to_their_page() {
4419        let mut doc = DoclingDocument::new("t");
4420        doc.push(Node::PageInfo {
4421            page_no: 1,
4422            width: 10.0,
4423            height: 8.0,
4424        });
4425        doc.push(Node::Prov {
4426            page_no: 1,
4427            bbox: [-1.0, 2.0, 12.0, 9.5],
4428            charspan: [0, 1],
4429            bottom_left: false,
4430            seq: None,
4431            inner: Box::new(Node::Paragraph { text: "x".into() }),
4432        });
4433        let mut table = Table {
4434            rows: vec![vec!["a".into()]],
4435            ..Table::default()
4436        };
4437        table.cells = Some(vec![crate::TableCell {
4438            text: "a".into(),
4439            bbox: Some([1.0, 1.0, 11.0, 9.0]),
4440            start_row: 0,
4441            start_col: 0,
4442            row_span: 1,
4443            col_span: 1,
4444            column_header: false,
4445            row_header: false,
4446            row_section: false,
4447        }]);
4448        doc.push(Node::Prov {
4449            page_no: 1,
4450            bbox: [0.0, 0.0, 10.0, 8.0],
4451            charspan: [0, 0],
4452            bottom_left: false,
4453            seq: None,
4454            inner: Box::new(Node::Table(table)),
4455        });
4456        doc.push(Node::Prov {
4457            page_no: 7,
4458            bbox: [-5.0, 0.0, 50.0, 50.0],
4459            charspan: [0, 1],
4460            bottom_left: false,
4461            seq: None,
4462            inner: Box::new(Node::Paragraph { text: "y".into() }),
4463        });
4464        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4465        assert_eq!(
4466            v["texts"][0]["prov"][0]["bbox"],
4467            serde_json::json!({ "l": 0.0, "t": 2.0, "r": 10.0, "b": 8.0, "coord_origin": "TOPLEFT" })
4468        );
4469        let cell = &v["tables"][0]["data"]["table_cells"][0]["bbox"];
4470        assert_eq!(
4471            (cell["l"].as_f64(), cell["r"].as_f64(), cell["b"].as_f64()),
4472            (Some(1.0), Some(10.0), Some(8.0))
4473        );
4474        assert_eq!(v["tables"][0]["data"]["grid"][0][0]["bbox"]["r"], 10.0);
4475        assert_eq!(
4476            v["texts"][1]["prov"][0]["bbox"]["r"], 50.0,
4477            "page 7 is not described"
4478        );
4479    }
4480
4481    /// docling-core's `validate_misplaced_list_items`, as it re-homes list
4482    /// items outside a `list` group (#527) — the refs below are what
4483    /// docling-core 2.99 writes for the same document: the two consecutive
4484    /// items on the body share a group, each item in another group gets its
4485    /// own, the runs are handled last-first (new groups and re-added texts
4486    /// numbered in that order), and a well-placed item is left alone.
4487    #[test]
4488    fn misplaced_list_items_are_wrapped_like_docling_core() {
4489        use crate::tree::{ItemTree, ListMeta, TreeKind};
4490        let mut t = ItemTree::default();
4491        let li = |txt: &str| TreeKind::Text {
4492            label: "list_item".into(),
4493            text: txt.into(),
4494            orig: None,
4495            formatting: None,
4496            hyperlink: None,
4497            level: None,
4498            list: Some(ListMeta {
4499                enumerated: false,
4500                marker: "-".into(),
4501            }),
4502        };
4503        let group = |label: &str, name: &str| TreeKind::Group {
4504            label: label.into(),
4505            name: name.into(),
4506        };
4507        t.add(None, None, li("A"));
4508        t.add(None, None, li("B"));
4509        t.add(
4510            None,
4511            None,
4512            TreeKind::Text {
4513                label: "text".into(),
4514                text: "plain".into(),
4515                orig: None,
4516                formatting: None,
4517                hyperlink: None,
4518                level: None,
4519                list: None,
4520            },
4521        );
4522        let cell = t.add(None, None, group("unspecified", "cell"));
4523        t.add(Some(cell), None, li("C"));
4524        t.add(Some(cell), None, li("D"));
4525        let list = t.add(None, None, group("list", "list"));
4526        t.add(Some(list), None, li("E"));
4527        let doc = DoclingDocument {
4528            tree: Some(t),
4529            ..DoclingDocument::new("t")
4530        };
4531        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4532        let refs = |x: &Value| -> Vec<String> {
4533            x.as_array()
4534                .unwrap()
4535                .iter()
4536                .map(|r| r["$ref"].as_str().unwrap().to_string())
4537                .collect()
4538        };
4539        assert_eq!(
4540            refs(&v["body"]["children"]),
4541            ["#/groups/4", "#/texts/0", "#/groups/0", "#/groups/1"]
4542        );
4543        assert_eq!(
4544            refs(&v["groups"][0]["children"]),
4545            ["#/groups/3", "#/groups/2"]
4546        );
4547        for (g, name, kids) in [
4548            (2, "group", vec!["#/texts/2"]),
4549            (3, "group", vec!["#/texts/3"]),
4550            (4, "group", vec!["#/texts/4", "#/texts/5"]),
4551            (1, "list", vec!["#/texts/1"]),
4552        ] {
4553            assert_eq!(v["groups"][g]["label"], "list");
4554            assert_eq!(v["groups"][g]["name"], name);
4555            assert_eq!(refs(&v["groups"][g]["children"]), kids);
4556        }
4557        let texts: Vec<&str> = v["texts"]
4558            .as_array()
4559            .unwrap()
4560            .iter()
4561            .map(|t| t["text"].as_str().unwrap())
4562            .collect();
4563        assert_eq!(texts, ["plain", "E", "D", "C", "A", "B"]);
4564        assert_eq!(v["texts"][2]["parent"]["$ref"], "#/groups/2");
4565    }
4566
4567    /// A child the tree still lists after deleting it is left out instead
4568    /// of written as `"$ref": ""`, which docling-core rejects (#527).
4569    #[test]
4570    fn a_deleted_child_is_not_written_as_an_empty_ref() {
4571        use crate::tree::{ItemTree, TreeKind};
4572        let mut t = ItemTree::default();
4573        let text = |txt: &str| TreeKind::Text {
4574            label: "text".into(),
4575            text: txt.into(),
4576            orig: None,
4577            formatting: None,
4578            hyperlink: None,
4579            level: None,
4580            list: None,
4581        };
4582        let g = t.add(
4583            None,
4584            None,
4585            TreeKind::Group {
4586                label: "unspecified".into(),
4587                name: "g".into(),
4588            },
4589        );
4590        let gone = t.add(Some(g), None, text(""));
4591        t.add(Some(g), None, text("kept"));
4592        t.items[gone].deleted = true; // still in `g`'s children
4593        let doc = DoclingDocument {
4594            tree: Some(t),
4595            ..DoclingDocument::new("t")
4596        };
4597        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4598        assert_eq!(
4599            v["groups"][0]["children"],
4600            serde_json::json!([{"$ref": "#/texts/0"}])
4601        );
4602    }
4603
4604    #[test]
4605    fn a_trimmed_run_tree_gets_the_legacy_join_in_its_runs() {
4606        use crate::tree::{ItemTree, TreeKind, TreeProv};
4607        let text = |label: &str, txt: &str| TreeKind::Text {
4608            label: label.into(),
4609            text: txt.into(),
4610            orig: None,
4611            formatting: None,
4612            hyperlink: None,
4613            level: None,
4614            list: None,
4615        };
4616        let mut t = ItemTree::default();
4617        let g = t.add(
4618            None,
4619            None,
4620            TreeKind::Group {
4621                label: "inline".into(),
4622                name: "group".into(),
4623            },
4624        );
4625        t.add(Some(g), None, text("text", "left"));
4626        let prov = TreeProv {
4627            page_no: 1,
4628            bbox: [0.0, 0.0, 1.0, 1.0],
4629            bottom_left: false,
4630            charspan: [0, 1],
4631        };
4632        t.add_with_prov(Some(g), None, text("formula", "a"), prov.clone());
4633        t.add_with_prov(Some(g), None, text("formula", "b"), prov);
4634        t.add(Some(g), None, text("text", "right"));
4635        let doc = DoclingDocument {
4636            tree: Some(t),
4637            ..DoclingDocument::new("t")
4638        };
4639        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4640        let texts: Vec<&str> = v["texts"]
4641            .as_array()
4642            .unwrap()
4643            .iter()
4644            .map(|t| t["text"].as_str().unwrap())
4645            .collect();
4646        // `left ` · `a` · ` ` (standalone, appended) · `b` · ` right`.
4647        assert_eq!(texts, ["left ", "a", "b", " right", " "]);
4648        assert_eq!(v["texts"][0]["orig"], "left");
4649        assert_eq!(v["groups"][0]["children"][2]["$ref"], "#/texts/4");
4650        assert_eq!(
4651            v["texts"][4]["prov"][0]["charspan"],
4652            serde_json::json!([0, 1])
4653        );
4654    }
4655
4656    #[test]
4657    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4658    fn a_backend_item_tree_is_written_verbatim() {
4659        use crate::tree::{Formatting, ItemTree, ListMeta, TreeKind};
4660        let mut t = ItemTree {
4661            // Runs as written: no legacy separator injection (#997).
4662            inline_whitespace: true,
4663            ..ItemTree::default()
4664        };
4665        let text = |label: &str, txt: &str| TreeKind::Text {
4666            label: label.into(),
4667            text: txt.into(),
4668            orig: None,
4669            formatting: None,
4670            hyperlink: None,
4671            level: None,
4672            list: None,
4673        };
4674        let title = t.add(None, Some(ContentLayer::Furniture), text("title", "Page"));
4675        let h = t.add(None, None, text("title", "Heading"));
4676        let group = t.add(
4677            Some(h),
4678            None,
4679            TreeKind::Group {
4680                label: "inline".into(),
4681                name: "group".into(),
4682            },
4683        );
4684        t.add(
4685            Some(group),
4686            None,
4687            TreeKind::Text {
4688                label: "text".into(),
4689                text: "bold".into(),
4690                orig: None,
4691                formatting: Some(Formatting {
4692                    bold: true,
4693                    ..Formatting::default()
4694                }),
4695                hyperlink: Some("https://example.com/".into()),
4696                level: None,
4697                list: None,
4698            },
4699        );
4700        t.add(
4701            Some(group),
4702            None,
4703            TreeKind::Code {
4704                text: "x = 1".into(),
4705                orig: None,
4706                language: Some("python".into()),
4707                formatting: None,
4708                hyperlink: None,
4709                captions: Vec::new(),
4710            },
4711        );
4712        let sub = t.add(
4713            Some(h),
4714            None,
4715            TreeKind::Text {
4716                label: "section_header".into(),
4717                text: "Sub".into(),
4718                orig: Some("Sub\u{2019}".into()),
4719                formatting: None,
4720                hyperlink: None,
4721                level: Some(1),
4722                list: None,
4723            },
4724        );
4725        let item = t.add(
4726            Some(sub),
4727            None,
4728            TreeKind::Text {
4729                label: "list_item".into(),
4730                text: "item".into(),
4731                orig: None,
4732                formatting: None,
4733                hyperlink: None,
4734                level: None,
4735                list: Some(ListMeta {
4736                    enumerated: true,
4737                    marker: "3.".into(),
4738                }),
4739            },
4740        );
4741        let _region = t.add(
4742            Some(sub),
4743            None,
4744            TreeKind::FieldRegion {
4745                items: vec![crate::FieldItem {
4746                    marker: None,
4747                    key: Some("Name".into()),
4748                    value: Some("Duck".into()),
4749                    value_kind: Some("read_only".into()),
4750                }],
4751            },
4752        );
4753        let table = t.add(
4754            Some(sub),
4755            None,
4756            TreeKind::Table {
4757                footnotes: Vec::new(),
4758                table: Table {
4759                    rows: vec![vec!["a  \n&lt;".into(), "b".into()]],
4760                    cells: Some(vec![
4761                        crate::TableCell {
4762                            text: "a  \n&lt;".into(),
4763                            bbox: None,
4764                            start_row: 0,
4765                            start_col: 0,
4766                            row_span: 3,
4767                            col_span: 1,
4768                            column_header: false,
4769                            row_header: true,
4770                            row_section: false,
4771                        },
4772                        crate::TableCell {
4773                            text: "b".into(),
4774                            bbox: None,
4775                            start_row: 0,
4776                            start_col: 1,
4777                            row_span: 1,
4778                            col_span: 1,
4779                            column_header: false,
4780                            row_header: false,
4781                            row_section: false,
4782                        },
4783                    ]),
4784                    ..Table::default()
4785                },
4786                rich_cells: vec![(0, 1, 0)], // patched below
4787                captions: Vec::new(),
4788            },
4789        );
4790        let cell_group = t.add(
4791            Some(table),
4792            None,
4793            TreeKind::Group {
4794                label: "unspecified".into(),
4795                name: "rich_cell_group_1_0_0".into(),
4796            },
4797        );
4798        if let TreeKind::Table { rich_cells, .. } = &mut t.items[table].kind {
4799            *rich_cells = vec![(0, 1, cell_group)];
4800        }
4801        let after = t.add(Some(sub), None, text("text", "after the region"));
4802        let _ = (title, after);
4803        // A list item belongs in a `list` group — one outside it would be
4804        // re-homed by `wrap_misplaced_list_items` (created last, so the
4805        // other groups keep their numbers).
4806        let list = t.add(
4807            Some(sub),
4808            None,
4809            TreeKind::Group {
4810                label: "list".into(),
4811                name: "list".into(),
4812            },
4813        );
4814        t.reparent(item, Some(list));
4815
4816        let doc = DoclingDocument {
4817            tree: Some(t),
4818            ..DoclingDocument::new("t")
4819        };
4820        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
4821        // Creation order: Page, Heading, bold, x = 1, Sub, item, [Name, Duck], after.
4822        let texts: Vec<&str> = v["texts"]
4823            .as_array()
4824            .unwrap()
4825            .iter()
4826            .map(|t| t["text"].as_str().unwrap())
4827            .collect();
4828        assert_eq!(
4829            texts,
4830            [
4831                "Page",
4832                "Heading",
4833                "bold",
4834                "x = 1",
4835                "Sub",
4836                "item",
4837                "Name",
4838                "Duck",
4839                "after the region"
4840            ]
4841        );
4842        assert_eq!(
4843            v["body"]["children"],
4844            serde_json::json!([{"$ref": "#/texts/0"}, {"$ref": "#/texts/1"}])
4845        );
4846        assert_eq!(v["texts"][0]["content_layer"], "furniture");
4847        assert_eq!(
4848            v["texts"][1]["children"],
4849            serde_json::json!([{"$ref": "#/groups/0"}, {"$ref": "#/texts/4"}])
4850        );
4851        let bold = &v["texts"][2];
4852        assert_eq!(bold["parent"]["$ref"], "#/groups/0");
4853        let keys: Vec<&str> = bold
4854            .as_object()
4855            .unwrap()
4856            .keys()
4857            .map(String::as_str)
4858            .collect();
4859        assert_eq!(
4860            keys,
4861            [
4862                "self_ref",
4863                "parent",
4864                "children",
4865                "content_layer",
4866                "label",
4867                "prov",
4868                "orig",
4869                "text",
4870                "formatting",
4871                "hyperlink"
4872            ]
4873        );
4874        assert_eq!(
4875            bold["formatting"],
4876            serde_json::json!({"bold": true, "italic": false, "underline": false, "strikethrough": false, "script": "baseline"})
4877        );
4878        let code = &v["texts"][3];
4879        assert_eq!(code["label"], "code");
4880        assert_eq!(code["code_language"], "Python");
4881        let sub = &v["texts"][4];
4882        assert_eq!(sub["orig"], "Sub\u{2019}");
4883        assert_eq!(sub["level"], 1);
4884        let item = &v["texts"][5];
4885        let keys: Vec<&str> = item
4886            .as_object()
4887            .unwrap()
4888            .keys()
4889            .map(String::as_str)
4890            .collect();
4891        assert_eq!(
4892            keys,
4893            [
4894                "self_ref",
4895                "parent",
4896                "children",
4897                "content_layer",
4898                "label",
4899                "prov",
4900                "orig",
4901                "text",
4902                "enumerated",
4903                "marker"
4904            ]
4905        );
4906        assert_eq!(item["marker"], "3.");
4907        assert_eq!(v["texts"][7]["kind"], "read_only");
4908        assert_eq!(v["field_regions"][0]["parent"]["$ref"], "#/texts/4");
4909        let table = &v["tables"][0];
4910        assert_eq!(
4911            table["children"],
4912            serde_json::json!([{"$ref": "#/groups/1"}])
4913        );
4914        let cells = table["data"]["table_cells"].as_array().unwrap();
4915        assert_eq!(
4916            cells[0]["text"], "a  \n&lt;",
4917            "raw cell text is written verbatim"
4918        );
4919        assert_eq!(
4920            cells[0]["end_row_offset_idx"], 3,
4921            "declared spans are not clamped"
4922        );
4923        assert_eq!(cells[1]["ref"], serde_json::json!({"$ref": "#/groups/1"}));
4924        assert!(cells[0].get("ref").is_none());
4925        assert!(
4926            table["data"]["grid"][0][1].get("ref").is_none(),
4927            "the grid shows plain cells"
4928        );
4929        assert_eq!(v["groups"][1]["name"], "rich_cell_group_1_0_0");
4930    }
4931
4932    /// A comment section that links its note text rather than its group — the
4933    /// spreadsheet shape, where docling-core's `add_comment` appends the text
4934    /// item's ref to each target.
4935    #[test]
4936    fn a_comment_section_can_be_referenced_by_its_note_text() {
4937        let doc = DoclingDocument {
4938            name: "c".into(),
4939            nodes: vec![
4940                Node::Commented {
4941                    comments: vec![0],
4942                    inner: Box::new(Node::Paragraph {
4943                        text: "annotated".into(),
4944                    }),
4945                },
4946                Node::CommentSection {
4947                    name: "comment-Sheet1-A1".into(),
4948                    text: "[author: A]: note".into(),
4949                    refs_note_text: true,
4950                    grouped: true,
4951                },
4952            ],
4953            ..DoclingDocument::new("c")
4954        };
4955        let v = crate::json::to_json(&doc);
4956        assert_eq!(v["groups"][0]["name"], "comment-Sheet1-A1");
4957        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/texts/1");
4958    }
4959
4960    /// A thread's messages are notes of one `comment_section` group, which is
4961    /// listed once among its parent's children however many notes it holds.
4962    #[test]
4963    fn a_comment_thread_is_one_child_of_its_parent() {
4964        let note = |text: &str| Node::CommentSection {
4965            name: "comment-Sheet1-F7".into(),
4966            text: text.into(),
4967            refs_note_text: true,
4968            grouped: true,
4969        };
4970        let doc = DoclingDocument {
4971            name: "c".into(),
4972            nodes: vec![note("[author: A]: first"), note("[author: B]: reply")],
4973            ..DoclingDocument::new("c")
4974        };
4975        let v = crate::json::to_json(&doc);
4976        assert_eq!(v["body"]["children"].as_array().unwrap().len(), 1);
4977        assert_eq!(v["groups"][0]["children"].as_array().unwrap().len(), 2);
4978    }
4979
4980    /// docx reviewer comments: a `comment_section` group on the notes layer
4981    /// holding the note text, and a `comments` back-ref on the annotated item —
4982    /// keyed between `prov` and `orig`, the slot docling emits it in.
4983    #[test]
4984    #[cfg(feature = "preserve-order")] // field-order assertions (#970)
4985    fn comment_sections_link_back_to_their_items() {
4986        let doc = DoclingDocument {
4987            name: "c".into(),
4988            nodes: vec![
4989                Node::Commented {
4990                    comments: vec![0],
4991                    inner: Box::new(Node::Paragraph {
4992                        text: "annotated".into(),
4993                    }),
4994                },
4995                Node::Paragraph {
4996                    text: "plain".into(),
4997                },
4998                Node::CommentSection {
4999                    name: "comment-7".into(),
5000                    text: "[time: t]: note".into(),
5001                    refs_note_text: false,
5002                    grouped: true,
5003                },
5004            ],
5005            ..DoclingDocument::new("c")
5006        };
5007        let v = crate::json::to_json(&doc);
5008        // The group is the comment section; its only child is the notes text.
5009        assert_eq!(v["groups"][0]["label"], "comment_section");
5010        assert_eq!(v["groups"][0]["name"], "comment-7");
5011        assert_eq!(v["groups"][0]["content_layer"], "notes");
5012        assert_eq!(v["groups"][0]["children"][0]["$ref"], "#/texts/2");
5013        assert_eq!(v["texts"][2]["content_layer"], "notes");
5014        // The annotated item points back at the group; the plain one has no key.
5015        assert_eq!(v["texts"][0]["comments"][0]["$ref"], "#/groups/0");
5016        assert!(v["texts"][1].get("comments").is_none());
5017        // docling's key order: … prov, comments, orig, text.
5018        let keys: Vec<&str> = v["texts"][0]
5019            .as_object()
5020            .unwrap()
5021            .keys()
5022            .map(String::as_str)
5023            .collect();
5024        assert_eq!(
5025            &keys[keys.len() - 4..],
5026            &["prov", "comments", "orig", "text"]
5027        );
5028    }
5029
5030    fn picture(caption: &str, caption_parent: CaptionParent) -> Node {
5031        Node::Picture {
5032            caption: Some(caption.into()),
5033            caption_href: None,
5034            image: None,
5035            classification: None,
5036            description: None,
5037            caption_parent,
5038            caption_location: None,
5039        }
5040    }
5041
5042    fn group(children: Vec<Node>) -> Node {
5043        Node::Group {
5044            label: "section".into(),
5045            name: None,
5046            layer: None,
5047            children,
5048        }
5049    }
5050
5051    fn refs(v: &Value) -> Vec<&str> {
5052        v.as_array()
5053            .unwrap()
5054            .iter()
5055            .map(|r| r["$ref"].as_str().unwrap())
5056            .collect()
5057    }
5058
5059    /// #390: a declarative backend's caption is docling's `add_text` default —
5060    /// a body child, appended as it is created — wherever the picture sits:
5061    /// ahead of a top-level picture, behind the top-level item enclosing a
5062    /// nested one. The picture references it either way and has no children.
5063    #[test]
5064    fn a_body_caption_follows_the_enclosing_top_level_item() {
5065        let mut doc = DoclingDocument::new("t");
5066        doc.push(picture("top", CaptionParent::Body));
5067        doc.push(group(vec![
5068            Node::Paragraph { text: "p".into() },
5069            picture("nested", CaptionParent::Body),
5070        ]));
5071        doc.push(Node::Paragraph {
5072            text: "after".into(),
5073        });
5074        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5075        assert_eq!(
5076            refs(&v["body"]["children"]),
5077            [
5078                "#/texts/0",
5079                "#/pictures/0",
5080                "#/groups/0",
5081                "#/texts/2",
5082                "#/texts/3"
5083            ]
5084        );
5085        assert_eq!(
5086            refs(&v["groups"][0]["children"]),
5087            ["#/texts/1", "#/pictures/1"]
5088        );
5089        for (cap, pic) in [(0, 0), (2, 1)] {
5090            assert_eq!(v["texts"][cap]["label"], "caption");
5091            assert_eq!(v["texts"][cap]["parent"]["$ref"], "#/body");
5092            assert_eq!(
5093                refs(&v["pictures"][pic]["captions"]),
5094                [format!("#/texts/{cap}")]
5095            );
5096            assert_eq!(v["pictures"][pic]["children"], serde_json::json!([]));
5097        }
5098    }
5099
5100    /// The PDF pipeline's caption is the picture's (or table's) own child,
5101    /// as docling attaches a layout caption.
5102    #[test]
5103    fn an_item_caption_is_the_items_first_child() {
5104        let mut doc = DoclingDocument::new("t");
5105        doc.push(picture("fig", CaptionParent::Item));
5106        doc.push(Node::Table(Table {
5107            rows: vec![vec!["a".into()]],
5108            caption: Some("tab".into()),
5109            caption_parent: CaptionParent::Item,
5110            ..Table::default()
5111        }));
5112        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5113        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/tables/0"]);
5114        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/pictures/0");
5115        assert_eq!(refs(&v["pictures"][0]["children"]), ["#/texts/0"]);
5116        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
5117        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/tables/0");
5118        assert_eq!(refs(&v["tables"][0]["children"]), ["#/texts/1"]);
5119        assert_eq!(refs(&v["tables"][0]["captions"]), ["#/texts/1"]);
5120    }
5121
5122    /// A PDF picture's contained text (`Node::PictureChildren`) is written as
5123    /// docling's `_add_child_elements` writes it: items parented to the
5124    /// picture, after its caption in the picture's `children`, never in the
5125    /// body; a list item opens its own list group under the picture. The
5126    /// Markdown and the chunker's refs are unaffected.
5127    #[test]
5128    fn picture_children_hang_off_the_picture_after_its_caption() {
5129        let mut doc = DoclingDocument::new("t");
5130        doc.push(picture("fig", CaptionParent::Item));
5131        doc.push(Node::PictureChildren(vec![
5132            Node::Heading {
5133                level: 2,
5134                text: "in-figure title".into(),
5135            },
5136            Node::Paragraph {
5137                text: "axis label".into(),
5138            },
5139            Node::ListItem {
5140                ordered: false,
5141                number: 0,
5142                first_in_list: true,
5143                text: "callout".into(),
5144                level: 0,
5145                marker: None,
5146                location: None,
5147                split: None,
5148                dclx: None,
5149                href: None,
5150                layer: None,
5151            },
5152        ]));
5153        doc.push(Node::Paragraph {
5154            text: "after".into(),
5155        });
5156        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5157        assert_eq!(refs(&v["body"]["children"]), ["#/pictures/0", "#/texts/4"]);
5158        assert_eq!(
5159            refs(&v["pictures"][0]["children"]),
5160            ["#/texts/0", "#/texts/1", "#/texts/2", "#/groups/0"]
5161        );
5162        assert_eq!(refs(&v["pictures"][0]["captions"]), ["#/texts/0"]);
5163        assert_eq!(v["texts"][1]["label"], "section_header");
5164        assert_eq!(v["texts"][2]["label"], "text");
5165        for t in 1..=2 {
5166            assert_eq!(v["texts"][t]["parent"]["$ref"], "#/pictures/0");
5167            assert_eq!(v["texts"][t]["content_layer"], "body");
5168        }
5169        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/pictures/0");
5170        assert_eq!(v["texts"][3]["parent"]["$ref"], "#/groups/0");
5171        let md = doc.export_to_markdown();
5172        assert!(
5173            !md.contains("axis label") && !md.contains("callout"),
5174            "{md}"
5175        );
5176        assert!(md.contains("after"), "{md}");
5177    }
5178
5179    /// A container caption sits beside its item under the item's parent —
5180    /// ahead of it (an office chart's title) or behind it (an HTML
5181    /// `<figure>`'s table, whose figcaption docling adds after the table).
5182    #[test]
5183    fn a_container_caption_is_the_items_sibling() {
5184        let mut doc = DoclingDocument::new("t");
5185        doc.push(group(vec![
5186            picture("chart", CaptionParent::Container),
5187            Node::Table(Table {
5188                rows: vec![vec!["a".into()]],
5189                caption: Some("figcaption".into()),
5190                caption_parent: CaptionParent::ContainerAfter,
5191                ..Table::default()
5192            }),
5193        ]));
5194        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5195        assert_eq!(refs(&v["body"]["children"]), ["#/groups/0"]);
5196        assert_eq!(
5197            refs(&v["groups"][0]["children"]),
5198            ["#/texts/0", "#/pictures/0", "#/tables/0", "#/texts/1"]
5199        );
5200        assert_eq!(v["texts"][0]["parent"]["$ref"], "#/groups/0");
5201        assert_eq!(v["texts"][1]["parent"]["$ref"], "#/groups/0");
5202        assert_eq!(v["pictures"][0]["children"], serde_json::json!([]));
5203        assert_eq!(v["tables"][0]["children"], serde_json::json!([]));
5204    }
5205
5206    /// A PDF footnote (#620 follow-up): the JSON keeps docling's
5207    /// `footnote` label, the raw text and the link as `hyperlink`; the
5208    /// Markdown still wraps the whole item as `[text](uri)`, and the plain
5209    /// text drops the link like docling-core's `export_to_text`.
5210    #[test]
5211    fn a_labeled_text_keeps_its_label_and_hyperlink_out_of_the_text() {
5212        let mut doc = DoclingDocument::new("t");
5213        doc.push(Node::LabeledText {
5214            label: "footnote".into(),
5215            text: "1 https://example.com/a\\_b".into(),
5216            href: Some("https://example.com/a_b".into()),
5217        });
5218        doc.push(Node::LabeledText {
5219            label: "footnote".into(),
5220            text: "© 2022 the authors".into(),
5221            href: None,
5222        });
5223        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5224        let t = &v["texts"][0];
5225        assert_eq!(t["label"], "footnote");
5226        assert_eq!(t["text"], "1 https://example.com/a_b");
5227        assert_eq!(t["orig"], "1 https://example.com/a_b");
5228        assert_eq!(t["hyperlink"], "https://example.com/a_b");
5229        assert_eq!(v["texts"][1]["label"], "footnote");
5230        assert!(v["texts"][1].get("hyperlink").is_none());
5231        assert_eq!(
5232            doc.export_to_markdown(),
5233            "[1 https://example.com/a\\_b](https://example.com/a_b)\n\n© 2022 the authors\n"
5234        );
5235        assert_eq!(
5236            doc.export_to_text(),
5237            "1 https://example.com/a_b\n\n© 2022 the authors"
5238        );
5239    }
5240
5241    /// A marked PDF item (#1005, docling's `ScriptPositionModel._apply`):
5242    /// the item keeps its place with an empty text and holds an inline group
5243    /// of its runs, added after every other item; two such paragraphs stay
5244    /// separate HTML blocks; a linked footnote's link rides on its baseline
5245    /// runs only, so the marker stays out of it.
5246    #[test]
5247    fn script_runs_follow_docling() {
5248        use crate::{Script, ScriptRun, ScriptRunProv};
5249        let run = |text: &str, script, hyperlink: Option<&str>| ScriptRun {
5250            text: text.into(),
5251            script,
5252            prov: vec![ScriptRunProv {
5253                page_no: 1,
5254                bbox: [10.0, 700.0, 20.0, 690.0],
5255                charspan: [0, text.chars().count()],
5256            }],
5257            hyperlink: hyperlink.map(String::from),
5258        };
5259        let mut doc = DoclingDocument::new("t");
5260        doc.push(Node::PageInfo {
5261            page_no: 1,
5262            width: 612.0,
5263            height: 792.0,
5264        });
5265        let located = |inner: Node| Node::Located {
5266            location: [40, 80, 200, 90],
5267            inner: Box::new(inner),
5268        };
5269        doc.push(located(Node::ScriptText {
5270            inner: Box::new(Node::Paragraph {
5271                text: "E = mc2".into(),
5272            }),
5273            runs: vec![
5274                run("E = mc", Script::Baseline, None),
5275                run("2", Script::Super, None),
5276            ],
5277        }));
5278        doc.push(located(Node::ScriptText {
5279            inner: Box::new(Node::Paragraph { text: "H2O".into() }),
5280            runs: vec![
5281                run("H", Script::Baseline, None),
5282                run("2", Script::Sub, None),
5283                run("O", Script::Baseline, None),
5284            ],
5285        }));
5286        let url = "https://example.com/x";
5287        doc.push(located(Node::ScriptText {
5288            inner: Box::new(Node::LabeledText {
5289                label: "footnote".into(),
5290                text: format!("1[Note text]({url})"),
5291                href: None,
5292            }),
5293            runs: vec![
5294                run("1", Script::Super, None),
5295                run("Note text", Script::Baseline, Some(url)),
5296            ],
5297        }));
5298        doc.push(located(Node::Paragraph {
5299            text: "Plain line".into(),
5300        }));
5301
5302        let v: Value = serde_json::from_str(&doc.export_to_json()).unwrap();
5303        let texts = v["texts"].as_array().unwrap();
5304        // The items first, in place; the runs after them.
5305        assert_eq!(texts[0]["text"], "");
5306        assert_eq!(
5307            texts[0]["children"],
5308            serde_json::json!([{"$ref": "#/groups/0"}])
5309        );
5310        assert_eq!(texts[2]["label"], "footnote");
5311        assert_eq!(texts[2]["hyperlink"], url);
5312        assert_eq!(texts[3]["text"], "Plain line");
5313        assert_eq!(texts[4]["text"], "E = mc");
5314        assert_eq!(texts[5]["formatting"]["script"], "super");
5315        assert_eq!(texts[5]["prov"][0]["bbox"]["coord_origin"], "BOTTOMLEFT");
5316        assert_eq!(texts[7]["formatting"]["script"], "sub");
5317        assert_eq!(texts[9]["label"], "footnote");
5318        assert!(texts[9].get("hyperlink").is_none());
5319        assert_eq!(texts[10]["hyperlink"], url);
5320        assert_eq!(v["groups"][0]["label"], "inline");
5321        assert_eq!(v["groups"][0]["parent"]["$ref"], "#/texts/0");
5322
5323        assert_eq!(
5324            doc.export_to_markdown(),
5325            format!("E = mc2\n\nH2O\n\n1[Note text]({url})\n\nPlain line\n")
5326        );
5327        let html = doc.export_to_html();
5328        // Each marked item is a block of its own (the footnote too, as
5329        // docling-core renders it).
5330        assert_eq!(
5331            html.matches("<p><span class='inline-group'>").count(),
5332            3,
5333            "{html}"
5334        );
5335        assert!(html.contains("E = mc<sup>2</sup>"), "{html}");
5336        assert!(html.contains("H<sub>2</sub>O"), "{html}");
5337        assert!(
5338            html.contains(&format!("<sup>1</sup><a href=\"{url}\">Note text</a>")),
5339            "{html}"
5340        );
5341        let dclx = doc.export_to_doclang();
5342        assert!(
5343            dclx.contains("E = mc<superscript>2</superscript>"),
5344            "{dclx}"
5345        );
5346    }
5347}