Skip to main content

docling_core/
chunker.rs

1//! Document chunking for RAG pipelines — the Rust port of docling-core's
2//! `docling_core.transforms.chunker`.
3//!
4//! Two chunkers, matching docling's semantics output-for-output:
5//!
6//! * [`HierarchicalChunker`] walks the document tree and yields one chunk per
7//!   top-level item (paragraph, whole list, table, picture caption, …), each
8//!   carrying the heading path it sits under. Tables are serialized in
9//!   docling's *triplet* form (`row, column = value`), pictures contribute
10//!   their captions.
11//! * [`HybridChunker`] refines the hierarchical chunks with a tokenizer:
12//!   oversized chunks are split (at item boundaries first, then within the
13//!   text by docling's `semchunk` algorithm), and undersized neighbours that
14//!   share the same headings are merged back together.
15//!
16//! [`contextualize`] renders a chunk to the string an embedding model should
17//! see: the heading path plus the chunk text.
18//!
19//! Anything tokenizer-related is abstracted behind [`ChunkTokenizer`]; a
20//! HuggingFace `tokenizers` implementation ships behind the `chunking` cargo
21//! feature as [`HuggingFaceTokenizer`].
22
23use std::collections::{BTreeMap, VecDeque};
24
25use crate::document::{DoclingDocument, Node, Table};
26
27/// What kind of document item a [`ChunkItem`] points at — only what the
28/// hybrid splitting logic needs to know.
29#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
30pub enum ChunkItemKind {
31    /// A text-ish item (paragraph, list item, code, formula, caption, …).
32    Text,
33    /// A table item (single-item oversized chunks re-split per line, repeating
34    /// docling's header handling).
35    Table,
36    /// A picture item.
37    Picture,
38}
39
40/// One document item contributing to a chunk — the analogue of an entry in
41/// docling's `DocMeta.doc_items`.
42#[derive(Debug, Clone, PartialEq)]
43pub struct ChunkItem {
44    /// The item's ref in [`DoclingDocument::export_to_json`] output
45    /// (`#/texts/12`, `#/tables/0`, `#/pictures/1`, …).
46    pub self_ref: String,
47    pub kind: ChunkItemKind,
48    /// The item serialized *standalone* (docling re-serializes individual
49    /// items when splitting an oversized multi-item chunk — e.g. a nested
50    /// list item flattens to `- text` with no indentation).
51    pub text: String,
52}
53
54/// One chunk — the analogue of docling's `DocChunk` (text + `DocMeta`).
55#[derive(Debug, Clone, PartialEq)]
56pub struct DocChunk {
57    /// The chunk body (markdown-flavoured, unescaped — same text docling puts
58    /// in `DocChunk.text`).
59    pub text: String,
60    /// The heading path above this chunk, outermost first (`DocMeta.headings`;
61    /// `None` when the chunk sits above any heading).
62    pub headings: Option<Vec<String>>,
63    /// The document items the chunk was built from (`DocMeta.doc_items`).
64    pub doc_items: Vec<ChunkItem>,
65}
66
67/// Render a chunk for embedding: the heading path, then the text, joined with
68/// newlines — docling's `BaseChunker.contextualize()`.
69pub fn contextualize(chunk: &DocChunk) -> String {
70    let mut parts: Vec<&str> = Vec::new();
71    if let Some(h) = &chunk.headings {
72        parts.extend(h.iter().map(String::as_str));
73    }
74    parts.push(&chunk.text);
75    parts.join("\n")
76}
77
78// ---------------------------------------------------------------------------
79// Hierarchical chunker
80// ---------------------------------------------------------------------------
81
82/// Structure-driven chunker: one chunk per document item, lists and inline
83/// groups kept whole, heading path tracked as metadata — docling-core's
84/// `HierarchicalChunker` with default parameters.
85#[derive(Debug, Clone, Default)]
86pub struct HierarchicalChunker;
87
88impl HierarchicalChunker {
89    /// Chunk the document.
90    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
91        let mut chunks = Vec::new();
92        self.chunk_with(doc, &mut |c| {
93            chunks.push(c);
94            true
95        });
96        chunks
97    }
98
99    /// Stream the chunks: `sink` is called with each chunk as the document
100    /// walk produces it, so a consumer can process (embed, forward) chunks
101    /// without materializing the whole `Vec` first. A `false` return from
102    /// `sink` cancels the walk. [`Self::chunk`] is this with a collecting
103    /// sink — the chunks and their order are identical.
104    ///
105    /// Each chunk's [`ChunkItem::self_ref`] is the item's ref in the
106    /// document's [JSON export](DoclingDocument::export_to_json_value)
107    /// (#1041): the walk numbers the flat nodes, which is the JSON's
108    /// numbering only for a document without an item tree, so the refs are
109    /// mapped onto the export's items ([`RefMapper`]).
110    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
111        let mut mapper = RefMapper::new(&doc.export_to_json_value());
112        Self::walk_nodes(doc, &mut |c| sink(mapper.remap(c)));
113    }
114
115    /// The walk itself, its refs in the flat nodes' numbering — what
116    /// [`HybridChunker`] splits and merges before the refs are mapped.
117    fn walk_nodes(doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
118        // The Markdown-fallback marks (#1205) are the Markdown export's alone.
119        let strip = crate::fallback::any_marks();
120        let mut sink = |mut c: DocChunk| {
121            if strip {
122                c.text = crate::fallback::strip_owned(std::mem::take(&mut c.text));
123                for h in c.headings.iter_mut().flatten() {
124                    *h = crate::fallback::strip_owned(std::mem::take(h));
125                }
126                for it in &mut c.doc_items {
127                    it.text = crate::fallback::strip_owned(std::mem::take(&mut it.text));
128                }
129            }
130            sink(c)
131        };
132        let mut w = Walker {
133            alloc: Alloc::default(),
134            headings: BTreeMap::new(),
135            stopped: false,
136            sink: &mut sink,
137        };
138        w.walk(&doc.nodes);
139    }
140}
141
142/// Maps the walk's chunk items onto the document's JSON export — a port of
143/// `docling_rs.chunking._RefMapper`, which the Python binding has applied to
144/// the caller's document since #1012.
145///
146/// The walk numbers the flat nodes the way the JSON export numbers a
147/// document *without* an item tree; a backend's tree (HTML, DOCX, ODF, JATS,
148/// LaTeX, …) is numbered by its own structure — a furniture title first, an
149/// inline paragraph as several runs, empty items kept — so the refs drift
150/// (#1041: on the corpus half of the text refs pointed at another item). The
151/// items still arrive in (nearly) reading order with their kind and Markdown
152/// text, so each is matched against the export's items walked in the same
153/// order (the `body` tree, pictures and tables not descended): a table or
154/// picture to the next untaken one of its kind, a text to an item it renders
155/// exactly (`Section 2` for `[Section 2](#s2)`, `x` for `- x`), else by
156/// containment close to the last match — an inline paragraph the walk
157/// reports as one item then maps to the run of items it contains. Candidates
158/// lie in a window around the last match, so an item emitted out of tree
159/// order (a caption next to its float) neither strands the rest nor goes
160/// unmatched; an item repeated across the chunks it is split into maps to
161/// the same items again. An item that matches nothing is left out rather
162/// than pointed at the wrong item.
163struct RefMapper {
164    /// The export's items in reading order: `(ref, kind, normalized text)`.
165    order: Vec<(String, ChunkItemKind, String)>,
166    /// Per item, a list item's marker and text as its Markdown prints them
167    /// (`甲. 甲项`), the marker being a field of its own in the JSON.
168    marked: Vec<Option<String>>,
169    taken: Vec<bool>,
170    /// The earliest untaken item.
171    low: usize,
172    /// One past the latest match.
173    last: usize,
174    seen: std::collections::HashMap<(String, ChunkItemKind, String), Vec<usize>>,
175}
176
177impl RefMapper {
178    const WINDOW: usize = 64;
179    const NEAR: usize = 16;
180    const MIN_CONTAINED: usize = 4;
181
182    fn new(doc: &serde_json::Value) -> Self {
183        use serde_json::Value;
184        let mut index: std::collections::HashMap<&str, &Value> = std::collections::HashMap::new();
185        for key in [
186            "texts",
187            "tables",
188            "pictures",
189            "groups",
190            "field_regions",
191            "field_items",
192            "key_value_items",
193            "form_items",
194        ] {
195            for it in doc.get(key).and_then(Value::as_array).into_iter().flatten() {
196                if let Some(r) = it.get("self_ref").and_then(Value::as_str) {
197                    index.insert(r, it);
198                }
199            }
200        }
201        let children = |v: &Value| -> Vec<String> {
202            v.get("children")
203                .and_then(Value::as_array)
204                .into_iter()
205                .flatten()
206                .filter_map(|c| c.get("$ref").or_else(|| c.get("cref")))
207                .filter_map(Value::as_str)
208                .map(str::to_string)
209                .collect()
210        };
211        let mut order = Vec::new();
212        let mut marked: Vec<Option<String>> = Vec::new();
213        let mut stack: Vec<std::vec::IntoIter<String>> = doc
214            .get("body")
215            .map(|b| vec![children(b).into_iter()])
216            .unwrap_or_default();
217        // A crafted document can list an item twice or cyclically: each is
218        // walked once.
219        let mut visited = std::collections::HashSet::new();
220        while let Some(top) = stack.last_mut() {
221            let Some(r) = top.next() else {
222                stack.pop();
223                continue;
224            };
225            let Some(it) = index.get(r.as_str()).copied() else {
226                continue;
227            };
228            if !visited.insert(r.clone()) {
229                continue;
230            }
231            let text_of = |it: &Value| norm(it.get("text").and_then(Value::as_str).unwrap_or(""));
232            if r.starts_with("#/texts/") {
233                let marker = it.get("marker").and_then(Value::as_str).unwrap_or("");
234                while marked.len() < order.len() {
235                    marked.push(None);
236                }
237                marked
238                    .push((!marker.is_empty()).then(|| norm(&format!("{marker} {}", text_of(it)))));
239                order.push((r, ChunkItemKind::Text, text_of(it)));
240            } else if r.starts_with("#/tables/") || r.starts_with("#/pictures/") {
241                // A float is not descended, but its captions and footnotes are
242                // chunked with it — wherever they hang (a PDF caption is the
243                // float's child, a declarative one the body's).
244                let refs = |key: &str| -> Vec<String> {
245                    it.get(key)
246                        .and_then(Value::as_array)
247                        .into_iter()
248                        .flatten()
249                        .filter_map(|c| c.get("$ref").and_then(Value::as_str))
250                        .map(str::to_string)
251                        .collect()
252                };
253                let mut sat = |order: &mut Vec<(String, ChunkItemKind, String)>, key: &str| {
254                    for c in refs(key) {
255                        if let Some(t) = index.get(c.as_str()) {
256                            if visited.insert(c.clone()) {
257                                order.push((c, ChunkItemKind::Text, text_of(t)));
258                            }
259                        }
260                    }
261                };
262                sat(&mut order, "captions");
263                let kind = if r.starts_with("#/tables/") {
264                    ChunkItemKind::Table
265                } else {
266                    ChunkItemKind::Picture
267                };
268                order.push((r, kind, String::new()));
269                sat(&mut order, "footnotes");
270                continue;
271            }
272            stack.push(children(it).into_iter());
273        }
274        let n = order.len();
275        marked.resize(n, None);
276        RefMapper {
277            order,
278            marked,
279            taken: vec![false; n],
280            low: 0,
281            last: 0,
282            seen: std::collections::HashMap::new(),
283        }
284    }
285
286    /// Untaken items of `kind` in `[lo, hi)`, nearest-first: forward from
287    /// the last match, then backward.
288    fn near(&self, lo: usize, hi: usize, used: &[usize], kind: ChunkItemKind) -> Vec<usize> {
289        let last = self.last.max(lo).min(hi);
290        (last..hi)
291            .chain((lo..last).rev())
292            .filter(|&i| !self.taken[i] && !used.contains(&i) && self.order[i].1 == kind)
293            .collect()
294    }
295
296    fn find(
297        &self,
298        (lo, hi): (usize, usize),
299        used: &[usize],
300        kind: ChunkItemKind,
301        text: &str,
302    ) -> Option<usize> {
303        if kind != ChunkItemKind::Text {
304            return self.near(lo, hi, used, kind).first().copied();
305        }
306        let plain = plain(text);
307        if let Some(i) = self
308            .near(lo, hi, used, kind)
309            .into_iter()
310            .find(|&i| self.matches(i, text, &plain))
311        {
312            return Some(i);
313        }
314        // Containment only close to the last match and for texts long enough
315        // to mean something: a short one ("duck", ")") is contained in many
316        // renderings and would pull the mapping out of step.
317        let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
318        let near_hi = hi.min(self.last + Self::NEAR);
319        if near_lo >= near_hi {
320            return None;
321        }
322        self.near(near_lo, near_hi, used, kind)
323            .into_iter()
324            .find(|&i| {
325                let t = &self.order[i].2;
326                t.chars().count() >= Self::MIN_CONTAINED && text.contains(t.as_str())
327            })
328    }
329
330    /// Whether item `i` is what `text` (or its plain form) renders exactly.
331    fn matches(&self, i: usize, text: &str, plain: &str) -> bool {
332        let t = &self.order[i].2;
333        t == text || t == plain || self.marked[i].as_deref().is_some_and(|m| m == plain)
334    }
335
336    /// Past the window, forward from the last match: an item matched
337    /// exactly, or a long one the rendering contains — what is left when the
338    /// walk skipped more of the export than the window spans (a large
339    /// region it does not chunk). Short texts never match this far.
340    fn find_far(&self, used: &[usize], kind: ChunkItemKind, text: &str) -> Option<usize> {
341        const FAR_CONTAINED: usize = 16;
342        // Bounded, so a document whose walk emits many items the export
343        // lacks stays linear.
344        const FAR: usize = 4096;
345        if kind != ChunkItemKind::Text || text.chars().count() < FAR_CONTAINED {
346            return None;
347        }
348        let plain = plain(text);
349        let free = |i: &usize| !self.taken[*i] && !used.contains(i) && self.order[*i].1 == kind;
350        let end = self.order.len().min(self.last + FAR);
351        let far = || (self.last..end).filter(free);
352        far().find(|&i| self.matches(i, text, &plain)).or_else(|| {
353            far().find(|&i| {
354                let t = &self.order[i].2;
355                t.chars().count() >= FAR_CONTAINED && text.contains(t.as_str())
356            })
357        })
358    }
359
360    /// A text the walk split off one of the export's items (a paragraph cut
361    /// at what its inline parser took for markup): the item that contains
362    /// it — the latest match first, though already taken, then an untaken
363    /// one close to it. Only for texts long enough to place.
364    fn part_of(&self, lo: usize, hi: usize, text: &str) -> Option<usize> {
365        let piece = plain(text);
366        if piece.chars().count() < 2 * Self::MIN_CONTAINED {
367            return None;
368        }
369        let contains = |i: usize| {
370            self.order[i].1 == ChunkItemKind::Text && self.order[i].2.contains(piece.as_str())
371        };
372        if let Some(prev) = self.last.checked_sub(1).filter(|&p| contains(p)) {
373            return Some(prev);
374        }
375        let near_lo = lo.max(self.last.saturating_sub(Self::NEAR));
376        let near_hi = hi.min(self.last + Self::NEAR);
377        (near_lo..near_hi).find(|&i| !self.taken[i] && contains(i))
378    }
379
380    /// The text items after a containment match that the same rendering
381    /// also contains, in order — the runs of an inline paragraph.
382    fn runs_after(&self, hit: usize, hi: usize, used: &[usize], text: &str) -> Vec<usize> {
383        let first = &self.order[hit].2;
384        let mut pos = text.find(first.as_str()).map_or(0, |p| p + first.len());
385        let mut extra = Vec::new();
386        let mut j = hit + 1;
387        while j < hi
388            && !self.taken[j]
389            && !used.contains(&j)
390            && self.order[j].1 == ChunkItemKind::Text
391        {
392            let t = &self.order[j].2;
393            let Some(at) = (!t.is_empty())
394                .then(|| text.get(pos..).and_then(|rest| rest.find(t.as_str())))
395                .flatten()
396            else {
397                break;
398            };
399            extra.push(j);
400            pos += at + t.len();
401            j += 1;
402        }
403        extra
404    }
405
406    fn remap(&mut self, mut chunk: DocChunk) -> DocChunk {
407        let n = chunk.doc_items.len();
408        let lo = self.low.max(self.last.saturating_sub(Self::WINDOW));
409        let hi = self.order.len().min(self.last + Self::WINDOW + n);
410        let mut used: Vec<usize> = Vec::new();
411        let mut items = Vec::with_capacity(n);
412        for item in std::mem::take(&mut chunk.doc_items) {
413            let text = norm(&item.text);
414            let key = (item.self_ref.clone(), item.kind, text.clone());
415            let mut runs = self
416                .seen
417                .get(&key)
418                .filter(|r| !r.iter().any(|h| used.contains(h)))
419                .cloned();
420            if runs.is_none() && lo < hi {
421                let hit = self
422                    .find((lo, hi), &used, item.kind, &text)
423                    .or_else(|| self.find_far(&used, item.kind, &text));
424                if let Some(hit) = hit {
425                    let mut r = vec![hit];
426                    if item.kind == ChunkItemKind::Text && !self.matches(hit, &text, &plain(&text))
427                    {
428                        r.extend(self.runs_after(hit, hi, &used, &text));
429                    }
430                    self.seen.insert(key, r.clone());
431                    runs = Some(r);
432                } else if item.kind == ChunkItemKind::Text {
433                    runs = self.part_of(lo, hi, &text).map(|h| vec![h]);
434                }
435            }
436            let Some(runs) = runs else {
437                crate::debug_log!(
438                    "chunker: no JSON item for {} ({:?}) in [{lo}, {hi}), last {}",
439                    item.self_ref,
440                    text.chars().take(60).collect::<String>(),
441                    self.last
442                );
443                continue;
444            };
445            for (k, &h) in runs.iter().enumerate() {
446                if items
447                    .iter()
448                    .any(|i: &ChunkItem| i.self_ref == self.order[h].0)
449                {
450                    continue; // another piece of the same item
451                }
452                used.push(h);
453                self.taken[h] = true;
454                self.last = self.last.max(h + 1);
455                // The walk's item keeps its own text (what the hybrid splitter
456                // re-serializes); the runs after it are the export's items.
457                items.push(ChunkItem {
458                    self_ref: self.order[h].0.clone(),
459                    kind: item.kind,
460                    text: if k == 0 {
461                        item.text.clone()
462                    } else {
463                        self.order[h].2.clone()
464                    },
465                });
466            }
467        }
468        while self.low < self.taken.len() && self.taken[self.low] {
469            self.low += 1;
470        }
471        chunk.doc_items = items;
472        chunk
473    }
474}
475
476/// `_norm`: an item text comparable to its Markdown rendering — entities
477/// decoded, escapes dropped, whitespace collapsed.
478fn norm(text: &str) -> String {
479    crate::doclang_xml::decode_entities(text)
480        .replace('\\', "")
481        .split_whitespace()
482        .collect::<Vec<_>>()
483        .join(" ")
484}
485
486/// `_plain`: a Markdown item rendering reduced toward the item's plain text —
487/// link targets, emphasis and code markers and a heading or list prefix
488/// dropped.
489fn plain(md: &str) -> String {
490    use std::sync::OnceLock;
491    static LINK: OnceLock<regex::Regex> = OnceLock::new();
492    static PREFIX: OnceLock<regex::Regex> = OnceLock::new();
493    let link = LINK.get_or_init(|| regex::Regex::new(r"!?\[([^\]]*)\]\([^)]*\)").expect("static"));
494    let prefix = PREFIX.get_or_init(|| {
495        regex::Regex::new(r"^(#{1,6}(\s+|$)|[-*+](\s+\[[ xX]\])?(\s+|$)|\d+[.)](\s+|$))")
496            .expect("static")
497    });
498    let mut text = link.replace_all(md, "$1").into_owned();
499    for marker in ["**", "~~", "`", "*"] {
500        text = text.replace(marker, "");
501    }
502    let text = prefix.replace(&text, "");
503    // A formula renders in `$$…$$` / `$…$`.
504    let text = text.trim();
505    let text = text
506        .strip_prefix("$$")
507        .and_then(|t| t.strip_suffix("$$"))
508        .or_else(|| text.strip_prefix('$').and_then(|t| t.strip_suffix('$')))
509        .unwrap_or(text);
510    text.trim().to_string()
511}
512
513/// Ref allocator mirroring the numbering `json.rs` gives every item, so
514/// `ChunkItem::self_ref` matches the document's JSON export.
515#[derive(Debug, Default)]
516struct Alloc {
517    texts: usize,
518    groups: usize,
519    tables: usize,
520    pictures: usize,
521    field_regions: usize,
522    field_items: usize,
523}
524
525impl Alloc {
526    fn text(&mut self) -> String {
527        let r = format!("#/texts/{}", self.texts);
528        self.texts += 1;
529        r
530    }
531    fn group(&mut self) -> String {
532        let r = format!("#/groups/{}", self.groups);
533        self.groups += 1;
534        r
535    }
536    fn table(&mut self) -> String {
537        let r = format!("#/tables/{}", self.tables);
538        self.tables += 1;
539        r
540    }
541    fn picture(&mut self) -> String {
542        let r = format!("#/pictures/{}", self.pictures);
543        self.pictures += 1;
544        r
545    }
546    fn field_region(&mut self) -> String {
547        let r = format!("#/field_regions/{}", self.field_regions);
548        self.field_regions += 1;
549        r
550    }
551    fn field_item(&mut self) -> String {
552        let r = format!("#/field_items/{}", self.field_items);
553        self.field_items += 1;
554        r
555    }
556}
557
558struct Walker<'s> {
559    alloc: Alloc,
560    /// Active heading per docling level (title = 0, `section_header` = its
561    /// `level`), pruned like docling's `heading_by_level`.
562    headings: BTreeMap<u8, String>,
563    /// Set once the sink refuses a chunk; the walk unwinds without emitting.
564    stopped: bool,
565    sink: &'s mut dyn FnMut(DocChunk) -> bool,
566}
567
568impl Walker<'_> {
569    fn emit(&mut self, text: String, doc_items: Vec<ChunkItem>) {
570        if self.stopped || text.is_empty() {
571            return;
572        }
573        let headings: Vec<String> = self.headings.values().cloned().collect();
574        self.stopped = !(self.sink)(DocChunk {
575            text,
576            headings: (!headings.is_empty()).then_some(headings),
577            doc_items,
578        });
579    }
580
581    /// Emit a text chunk whose doc items follow docling's inline granularity:
582    /// mixed inline content (a paragraph docling represents as an inline group)
583    /// contributes one item per span, plain text one item.
584    fn emit_inline(&mut self, md_text: &str, self_ref: String) {
585        self.emit_inline_with_runs(md_text, self_ref, &[]);
586    }
587
588    fn emit_inline_with_runs(
589        &mut self,
590        md_text: &str,
591        self_ref: String,
592        runs: &[crate::InlineRun],
593    ) {
594        let body = unescape_text(md_text);
595        if body.is_empty() {
596            return;
597        }
598        let segments: Vec<String> = inline_segments_tagged(md_text, runs)
599            .into_iter()
600            .flat_map(|(text, is_plain)| {
601                if is_plain {
602                    if let Some(split) = split_plain_by_runs(&text, runs) {
603                        return split;
604                    }
605                }
606                vec![text]
607            })
608            .collect();
609        let items: Vec<ChunkItem> = if segments.len() <= 1 {
610            vec![ChunkItem {
611                self_ref,
612                kind: ChunkItemKind::Text,
613                text: body.clone(),
614            }]
615        } else {
616            segments
617                .into_iter()
618                .map(|text| ChunkItem {
619                    self_ref: self_ref.clone(),
620                    kind: ChunkItemKind::Text,
621                    text,
622                })
623                .collect()
624        };
625        self.emit(body, items);
626    }
627
628    fn set_heading(&mut self, doc_level: u8, text: String) {
629        self.headings.retain(|k, _| *k < doc_level);
630        self.headings.insert(doc_level, text);
631    }
632
633    fn walk(&mut self, nodes: &[Node]) {
634        let mut i = 0;
635        while i < nodes.len() {
636            if self.stopped {
637                return;
638            }
639            if matches!(nodes[i], Node::ListItem { .. }) {
640                let start = i;
641                i += 1;
642                loop {
643                    match nodes.get(i) {
644                        Some(Node::ListItem { .. }) => i += 1,
645                        // An empty paragraph between two list items is absorbed
646                        // into the run (mirrors json.rs / markdown.rs).
647                        Some(Node::Paragraph { text })
648                            if text.is_empty()
649                                && matches!(nodes.get(i + 1), Some(Node::ListItem { .. })) =>
650                        {
651                            i += 1
652                        }
653                        _ => break,
654                    }
655                }
656                self.sibling_lists(&nodes[start..i]);
657            } else {
658                self.one(&nodes[i]);
659                i += 1;
660            }
661        }
662    }
663
664    /// Split a run of list items into sibling lists exactly like
665    /// `json.rs::add_sibling_lists`, chunking each list separately (docling
666    /// yields one chunk per `ListGroup`).
667    fn sibling_lists(&mut self, run: &[Node]) {
668        let base = level_of(&run[0]);
669        let mut seg = 0;
670        for k in 0..run.len() {
671            let Node::ListItem {
672                first_in_list,
673                level,
674                ..
675            } = &run[k]
676            else {
677                continue;
678            };
679            if *level != base {
680                continue; // nested item — handled inside `list`
681            }
682            // The backend's list boundary, as in `json.rs::add_sibling_lists`.
683            if k > seg && *first_in_list {
684                self.list(&run[seg..k]);
685                seg = k;
686            }
687        }
688        self.list(&run[seg..]);
689    }
690
691    /// One `ListGroup`: allocate refs in `json.rs::add_list` order (group,
692    /// then per top item its text ref followed by any nested groups) and emit
693    /// a single chunk whose text is the indented markdown list.
694    fn list(&mut self, items: &[Node]) {
695        self.alloc.group();
696        let mut chunk_items = Vec::new();
697        self.list_refs(items, &mut chunk_items);
698        let text = render_list(items);
699        self.emit(text, chunk_items);
700    }
701
702    /// Allocate refs for one list's items (and nested sibling lists), mirroring
703    /// `json.rs::add_list` / `add_sibling_lists` recursion, collecting the
704    /// non-furniture items in allocation (= document) order.
705    fn list_refs(&mut self, items: &[Node], out: &mut Vec<ChunkItem>) {
706        let base = level_of(&items[0]);
707        let mut i = 0;
708        while i < items.len() {
709            let Node::ListItem {
710                ordered,
711                number,
712                text,
713                level,
714                layer,
715                ..
716            } = &items[i]
717            else {
718                i += 1;
719                continue;
720            };
721            if *level > base {
722                i += 1;
723                continue;
724            }
725            let item_ref = self.alloc.text();
726            let mut j = i + 1;
727            while j < items.len() && level_of(&items[j]) > base {
728                j += 1;
729            }
730            let has_nested = j > i + 1;
731            if layer.is_none() {
732                let marker = if *ordered {
733                    format!("{number}.")
734                } else {
735                    "-".to_string()
736                };
737                // An item that carries both inline spans and a nested list is an
738                // empty list item wrapping an inline group in docling's model:
739                // its marker and each inline span are separate doc items.
740                // docling represents a list item whose content is not pure
741                // inline text (it carries a nested list or child pictures) as
742                // an empty item wrapping an inline group: its marker and each
743                // inline span become separate doc items.
744                // docling represents a list item whose content is not pure
745                // inline text (it carries a nested list or its own images) as
746                // an empty item wrapping an inline group: its marker and each
747                // inline span become separate doc items. The chunker's
748                // image placeholder is empty, so the markers are stripped from
749                // the text before segmentation.
750                let has_pics = text.contains("<!-- image -->");
751                let text = strip_image_markers(text);
752                let text = text.as_str();
753                let segments = inline_segments(text);
754                if (has_nested || has_pics) && segments.len() > 1 && text.contains("](") {
755                    out.push(ChunkItem {
756                        self_ref: item_ref.clone(),
757                        kind: ChunkItemKind::Text,
758                        text: format!("{marker} "),
759                    });
760                    for seg in segments {
761                        out.push(ChunkItem {
762                            self_ref: item_ref.clone(),
763                            kind: ChunkItemKind::Text,
764                            text: seg,
765                        });
766                    }
767                } else {
768                    out.push(ChunkItem {
769                        self_ref: item_ref.clone(),
770                        kind: ChunkItemKind::Text,
771                        text: format!("{marker} {}", unescape_text(text)),
772                    });
773                }
774            }
775            // nested items group under this one; each nested sibling list is a
776            // fresh group ref
777            if j > i + 1 {
778                self.nested_sibling_lists(&items[i + 1..j], out);
779            }
780            i = j;
781        }
782    }
783
784    fn nested_sibling_lists(&mut self, run: &[Node], out: &mut Vec<ChunkItem>) {
785        let base = level_of(&run[0]);
786        let mut seg = 0;
787        for k in 0..run.len() {
788            let Node::ListItem {
789                first_in_list,
790                level,
791                ..
792            } = &run[k]
793            else {
794                continue;
795            };
796            if *level != base {
797                continue;
798            }
799            if k > seg && *first_in_list {
800                self.alloc.group();
801                self.list_refs(&run[seg..k], out);
802                seg = k;
803            }
804        }
805        self.alloc.group();
806        self.list_refs(&run[seg..], out);
807    }
808
809    fn one(&mut self, node: &Node) {
810        match node {
811            Node::Heading { level, text } => {
812                let doc_level = if *level == 1 {
813                    0
814                } else {
815                    level.saturating_sub(1)
816                };
817                self.alloc.text();
818                // docling stores heading text unformatted: a heading that is one
819                // uniformly formatted span keeps its plain text; a *partially*
820                // formatted heading becomes an empty heading whose only child is
821                // an inline group. docling-core 2.106 (docling-core#924, #1012)
822                // serializes that child as the heading's context and consumes
823                // it, so it is no longer a body chunk under an empty heading.
824                let runs = crate::inline_runs_from_markdown(text);
825                let heading = if runs.len() <= 1 {
826                    runs.first()
827                        .map(|r| r.text.clone())
828                        .unwrap_or_else(|| text.clone())
829                } else {
830                    text.clone()
831                };
832                self.set_heading(doc_level, unescape_text(&heading));
833            }
834            Node::Paragraph { text } | Node::ListText { text, .. } => {
835                let t = text.trim();
836                let self_ref = self.alloc.text();
837                // A whole-paragraph display equation is a formula item; docling's
838                // chunk serializer re-wraps the raw latex in `$$…$$`.
839                if let Some(inner) = t
840                    .strip_prefix("$$")
841                    .and_then(|s| s.strip_suffix("$$"))
842                    .filter(|s| !s.is_empty())
843                {
844                    let body = format!("$${inner}$$");
845                    self.emit(
846                        body.clone(),
847                        vec![ChunkItem {
848                            self_ref,
849                            kind: ChunkItemKind::Text,
850                            text: body,
851                        }],
852                    );
853                    return;
854                }
855                self.emit_inline(text, self_ref);
856            }
857            // A standalone caption chunks like any text item (docling's chunker
858            // does not treat `caption` specially outside a table/picture).
859            Node::Caption { text, .. } => {
860                let self_ref = self.alloc.text();
861                self.emit_inline(text, self_ref);
862            }
863            Node::LabeledText { .. } => self.one(&node.labeled_as_paragraph()),
864            Node::CheckboxItem { checked, text } => {
865                let self_ref = self.alloc.text();
866                let mark = if *checked { "- [x] " } else { "- [ ] " };
867                let body = format!("{mark}{}", unescape_text(text));
868                self.emit(
869                    body.clone(),
870                    vec![ChunkItem {
871                        self_ref,
872                        kind: ChunkItemKind::Text,
873                        text: body,
874                    }],
875                );
876            }
877            // An enriched display formula chunks like docling's formula item:
878            // the LaTeX is the chunk text.
879            Node::Formula { latex, orig, .. } => {
880                // The item takes its `#/texts/N` slot whatever it prints.
881                let self_ref = self.alloc.text();
882                // An undecoded formula (#1120) chunks as the Markdown
883                // serializer prints it — the placeholder — and one with no
884                // text at all is no chunk.
885                let body = if !latex.is_empty() {
886                    format!("$${}$$", latex)
887                } else if !orig.is_empty() {
888                    crate::markdown::FORMULA_NOT_DECODED.to_string()
889                } else {
890                    return;
891                };
892                self.emit(
893                    body.clone(),
894                    vec![ChunkItem {
895                        self_ref,
896                        kind: ChunkItemKind::Text,
897                        text: body,
898                    }],
899                );
900            }
901            Node::Code { text, .. } => {
902                let self_ref = self.alloc.text();
903                let body = crate::markdown::code_fence("", &unescape_text(text));
904                self.emit(
905                    body.clone(),
906                    vec![ChunkItem {
907                        self_ref,
908                        kind: ChunkItemKind::Text,
909                        text: body,
910                    }],
911                );
912            }
913            Node::Table(t) => {
914                // `TripletTableSerializer`: the captions open the table's
915                // chunk and are among its doc items — the caption is the
916                // `#/texts/N` item the JSON writes ahead of the table (#1041:
917                // it took no ref here, so every later text ref pointed one
918                // item too early).
919                let mut items = Vec::new();
920                let mut parts = Vec::new();
921                if let Some(cap) = t.caption.as_deref().filter(|c| !c.is_empty()) {
922                    let text = unescape_text(cap);
923                    parts.push(text.clone());
924                    items.push(ChunkItem {
925                        self_ref: self.alloc.text(),
926                        kind: ChunkItemKind::Text,
927                        text,
928                    });
929                }
930                let self_ref = self.alloc.table();
931                let body = triplet_table_text(t);
932                items.push(ChunkItem {
933                    self_ref,
934                    kind: ChunkItemKind::Table,
935                    text: body.clone(),
936                });
937                // docling-core#675: the table's footnotes (the `footnote`
938                // texts the JSON writes after it) close its chunk, one
939                // paragraph each, and are among its doc items.
940                parts.push(body);
941                for note in t.footnotes.iter().filter(|n| !n.is_empty()) {
942                    let text = unescape_text(note);
943                    parts.push(text.clone());
944                    items.push(ChunkItem {
945                        self_ref: self.alloc.text(),
946                        kind: ChunkItemKind::Text,
947                        text,
948                    });
949                }
950                let body = parts
951                    .into_iter()
952                    .filter(|p| !p.is_empty())
953                    .collect::<Vec<_>>()
954                    .join("\n\n");
955                self.emit(body, items);
956            }
957            Node::Picture {
958                caption,
959                description,
960                ..
961            } => {
962                let cap = caption.as_deref().filter(|c| !c.is_empty());
963                let cap_item = cap.map(|c| ChunkItem {
964                    self_ref: self.alloc.text(),
965                    kind: ChunkItemKind::Text,
966                    text: unescape_text(c),
967                });
968                let pic_ref = self.alloc.picture();
969                // The picture itself serializes to the (empty) chunking image
970                // placeholder, and its caption is already consumed by the
971                // caption chunk — so only the caption text is emitted. A
972                // description (the picture-OCR text, #645) is the picture's
973                // own annotation text — docling's chunker serializes the
974                // picture through the Markdown picture serializer, so the
975                // description lands in the chunk after the caption.
976                let desc = description
977                    .as_ref()
978                    .map(|d| d.text.as_str())
979                    .filter(|t| !t.is_empty());
980                match (cap_item, desc) {
981                    (Some(cap_item), None) => {
982                        let body = cap_item.text.clone();
983                        self.emit(body, vec![cap_item]);
984                    }
985                    (Some(cap_item), Some(desc)) => {
986                        let body = format!("{}\n\n{desc}", cap_item.text);
987                        let pic_item = ChunkItem {
988                            self_ref: pic_ref,
989                            kind: ChunkItemKind::Picture,
990                            text: desc.to_string(),
991                        };
992                        self.emit(body, vec![cap_item, pic_item]);
993                    }
994                    (None, Some(desc)) => {
995                        let pic_item = ChunkItem {
996                            self_ref: pic_ref,
997                            kind: ChunkItemKind::Picture,
998                            text: desc.to_string(),
999                        };
1000                        self.emit(desc.to_string(), vec![pic_item]);
1001                    }
1002                    (None, None) => {}
1003                }
1004            }
1005            Node::Chart {
1006                kind,
1007                table,
1008                caption,
1009                ..
1010            } => {
1011                let cap = caption.as_deref().filter(|c| !c.is_empty());
1012                let cap_item = cap.map(|c| ChunkItem {
1013                    self_ref: self.alloc.text(),
1014                    kind: ChunkItemKind::Text,
1015                    text: unescape_text(c),
1016                });
1017                let pic_ref = self.alloc.picture();
1018                // caption, humanized classification, then the chart's data grid
1019                // as a (padded) markdown table — docling's picture serializer
1020                // parts, joined with blank lines.
1021                let mut parts: Vec<String> = Vec::new();
1022                if let Some(ci) = &cap_item {
1023                    parts.push(ci.text.clone());
1024                }
1025                parts.push(humanize_label(kind));
1026                let grid = crate::markdown::render_table(table, false);
1027                if !grid.is_empty() {
1028                    parts.push(unescape_text(&grid));
1029                }
1030                let body = parts.join("\n\n");
1031                // Re-serialized standalone (the hybrid window join), the picture
1032                // carries its caption itself, while the caption *item* renders
1033                // empty — docling's markdown serializer emits caption-label text
1034                // only through the picture.
1035                let pic_item = ChunkItem {
1036                    self_ref: pic_ref,
1037                    kind: ChunkItemKind::Picture,
1038                    text: body.clone(),
1039                };
1040                let items = match cap_item {
1041                    Some(mut ci) => {
1042                        ci.text = String::new();
1043                        vec![ci, pic_item]
1044                    }
1045                    None => vec![pic_item],
1046                };
1047                self.emit(body, items);
1048            }
1049            // A group on a non-body layer (a hidden spreadsheet sheet) carries
1050            // no chunkable content, like every other non-body item.
1051            Node::Group { layer: Some(_), .. } => {}
1052            Node::Group { children, .. } => {
1053                // A generic group is a structural container: docling recurses
1054                // into it rather than chunking it whole.
1055                self.alloc.group();
1056                self.walk(children);
1057            }
1058            // A key-value graph holds no text items, so no chunk comes of it.
1059            Node::KeyValueGraph { .. } => {}
1060            Node::FieldRegion { items } => {
1061                // Each field part (marker / key / value) is its own text item,
1062                // and docling chunks each one individually.
1063                self.alloc.field_region();
1064                for item in items {
1065                    self.alloc.field_item();
1066                    for part in [&item.marker, &item.key, &item.value].into_iter().flatten() {
1067                        let self_ref = self.alloc.text();
1068                        let body = unescape_text(part);
1069                        self.emit(
1070                            body.clone(),
1071                            vec![ChunkItem {
1072                                self_ref,
1073                                kind: ChunkItemKind::Text,
1074                                text: body,
1075                            }],
1076                        );
1077                    }
1078                }
1079            }
1080            Node::InlineGroup { md_text, runs, .. } => {
1081                let self_ref = self.alloc.text();
1082                self.emit_inline_with_runs(md_text, self_ref, runs);
1083            }
1084            Node::TextDump(text) => {
1085                let self_ref = self.alloc.text();
1086                let body = unescape_text(text);
1087                self.emit(
1088                    body.clone(),
1089                    vec![ChunkItem {
1090                        self_ref,
1091                        kind: ChunkItemKind::Text,
1092                        text: body,
1093                    }],
1094                );
1095            }
1096            // Layout provenance and comment annotations are transparent.
1097            Node::Located { inner, .. }
1098            | Node::Prov { inner, .. }
1099            | Node::Track { inner, .. }
1100            | Node::ScriptText { inner, .. }
1101            | Node::Commented { inner, .. } => self.one(inner),
1102            // A PDF page header/footer is a furniture-layer JSON text item:
1103            // never chunked (docling's chunker reads the body layer), but it
1104            // takes a `#/texts/N` number, so later refs keep matching the JSON.
1105            Node::PageFurniture { .. } | Node::FurnitureText { .. } => {
1106                self.alloc.text();
1107            }
1108            // A picture's children are JSON items docling's chunker never
1109            // reaches (it iterates without `traverse_pictures`): allocate
1110            // their refs only — one text each, plus the list group `json.rs`
1111            // opens for each list item (each starts its own list) — so later
1112            // refs keep matching the JSON.
1113            Node::PictureChildren(children) => {
1114                for child in children {
1115                    match child {
1116                        // A header/footer child is numbered exactly as a
1117                        // top-level one is, whatever the JSON does with it.
1118                        Node::PageFurniture { .. } => self.one(child),
1119                        Node::ListItem { .. } => {
1120                            self.alloc.group();
1121                            self.alloc.text();
1122                        }
1123                        _ => {
1124                            self.alloc.text();
1125                        }
1126                    }
1127                }
1128            }
1129            // Non-body layers and doclang-only nodes don't reach the chunker
1130            // (nor the JSON body).
1131            Node::CommentSection { .. }
1132            | Node::Furniture { .. }
1133            | Node::PageBreak
1134            | Node::PageInfo { .. }
1135            | Node::ProvContinuation { .. }
1136            | Node::Anchor { .. }
1137            | Node::DoclangOnly(_) => {}
1138            // Runs are grouped by `walk`; a stray single item (hand-built
1139            // document, `Located` wrapper) still chunks instead of panicking.
1140            Node::ListItem { .. } => self.sibling_lists(std::slice::from_ref(node)),
1141        }
1142    }
1143}
1144
1145fn level_of(node: &Node) -> u8 {
1146    match node {
1147        Node::ListItem { level, .. } => *level,
1148        _ => 0,
1149    }
1150}
1151
1152/// Render one sibling list as its markdown chunk text (indented items, same
1153/// rules as the full markdown serializer's list rendering).
1154fn render_list(items: &[Node]) -> String {
1155    let mut lines: Vec<String> = Vec::new();
1156    for item in items {
1157        let Node::ListItem {
1158            ordered,
1159            number,
1160            text,
1161            level,
1162            layer,
1163            ..
1164        } = item
1165        else {
1166            continue;
1167        };
1168        if layer.is_some() {
1169            continue;
1170        }
1171        let indent = "    ".repeat(*level as usize);
1172        let marker = if *ordered {
1173            format!("{number}.")
1174        } else {
1175            "-".to_string()
1176        };
1177        lines.push(format!(
1178            "{indent}{marker} {}",
1179            unescape_text(&strip_image_markers(text))
1180        ));
1181    }
1182    lines.join("\n")
1183}
1184
1185/// Strip the Markdown image placeholders a list item's own images fold into
1186/// its text (the chunking serializer's `image_placeholder` is empty, so
1187/// docling's chunk text carries no marker), collapsing the newlines that
1188/// carried them.
1189fn strip_image_markers(text: &str) -> String {
1190    if !text.contains("<!-- image -->") {
1191        return text.to_string();
1192    }
1193    let cleaned: Vec<&str> = text
1194        .split('\n')
1195        .map(str::trim_end)
1196        .filter(|l| *l != "<!-- image -->")
1197        .collect();
1198    cleaned.join("\n").trim_end().to_string()
1199}
1200
1201/// docling-core's `_humanize_text`: underscores to spaces, first letter
1202/// capitalized (`line_chart` → `Line chart`).
1203fn humanize_label(label: &str) -> String {
1204    let text = label.replace('_', " ");
1205    let mut chars = text.chars();
1206    match chars.next() {
1207        Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
1208        None => text,
1209    }
1210}
1211
1212/// docling's `TripletTableSerializer` over `export_to_dataframe` semantics: the
1213/// leading rows carrying column-header cells become the dataframe's column
1214/// names (multiple header rows join per column with `.`; no header rows at all
1215/// yield pandas' integer column names), the rest are data rows; the dataframe
1216/// is then rendered as `row, column = value` sentences (with the header-only /
1217/// single-column special cases and the plain-text flatten fallback).
1218fn triplet_table_text(t: &Table) -> String {
1219    let anchors = t.span_anchors();
1220    let rows: Vec<Vec<String>> = t
1221        .rows
1222        .iter()
1223        .enumerate()
1224        .map(|(ri, r)| {
1225            (0..r.len())
1226                .map(|ci| cell_chunk_text(t, &anchors, ri, ci))
1227                .collect()
1228        })
1229        .collect();
1230    let num_rows = rows.len();
1231    let num_cols = rows.iter().map(Vec::len).max().unwrap_or(0);
1232    if num_rows == 0 || num_cols == 0 {
1233        return String::new();
1234    }
1235    let cell = |r: usize, c: usize| -> &str {
1236        rows.get(r)
1237            .and_then(|row| row.get(c))
1238            .map(String::as_str)
1239            .unwrap_or("")
1240    };
1241
1242    // The header block is the one the Markdown serializer uses
1243    // (`Table::column_header_row_count`, docling-core#767), without its
1244    // "no flags -> row 0" fallback: pandas then gets integer column names.
1245    let num_headers = t.column_header_row_count().min(num_rows);
1246
1247    // Column names: header-row texts joined per column with '.', or the integer
1248    // positions when there are no header rows.
1249    let columns: Vec<String> = if num_headers > 0 {
1250        (0..num_cols)
1251            .map(|c| {
1252                let mut name = String::new();
1253                for r in 0..num_headers {
1254                    if !name.is_empty() {
1255                        name.push('.');
1256                    }
1257                    name.push_str(cell(r, c));
1258                }
1259                name
1260            })
1261            .collect()
1262    } else {
1263        (0..num_cols).map(|c| c.to_string()).collect()
1264    };
1265    let data_rows = num_headers..num_rows;
1266    let n_data = data_rows.len();
1267
1268    // Header-only table: emit the header texts directly.
1269    if n_data == 0 {
1270        return columns
1271            .iter()
1272            .map(|s| s.trim())
1273            .filter(|s| !s.is_empty())
1274            .collect::<Vec<_>>()
1275            .join(". ");
1276    }
1277
1278    let data = |r: usize, c: usize| -> &str { cell(num_headers + r, c) };
1279    let text = if num_cols == 1 {
1280        // Single-column: the first data row is the column name, the rest are
1281        // values (a single data row emits its cell text alone).
1282        let col_name = data(0, 0).trim().to_string();
1283        if n_data == 1 {
1284            col_name
1285        } else {
1286            (1..n_data)
1287                .map(|r| format!("{col_name} = {}", data(r, 0).trim()))
1288                .collect::<Vec<_>>()
1289                .join(". ")
1290        }
1291    } else {
1292        // Triplets over the dataframe with the column names copied as row 0.
1293        let mut parts = Vec::new();
1294        for r in 0..n_data {
1295            for (c, col_name) in columns.iter().enumerate().skip(1) {
1296                parts.push(format!(
1297                    "{}, {} = {}",
1298                    data(r, 0).trim(),
1299                    col_name.trim(),
1300                    data(r, c).trim()
1301                ));
1302            }
1303        }
1304        parts.join(". ")
1305    };
1306    if !text.is_empty() {
1307        return text;
1308    }
1309
1310    // Last-resort flatten: the data rows' non-blank cells joined with '. '
1311    // (the header rows are the dataframe's columns, so they are not included).
1312    (0..n_data)
1313        .flat_map(|r| (0..num_cols).map(move |c| (r, c)))
1314        .map(|(r, c)| data(r, c).trim())
1315        .filter(|s| !s.is_empty())
1316        .collect::<Vec<_>>()
1317        .join(". ")
1318}
1319
1320/// Split a markdown-flavoured text into docling's inline-item granularity: a
1321/// hyperlink / formatted span / inline formula is its own document item in
1322/// docling's model, with plain text runs between them. Returns the standalone
1323/// serialization of each item (`[text](url)`, `**bold**`, a formula re-wrapped
1324/// as `$$latex$$`, plain text), or a single-element vector when the text is one
1325/// uniform item. The single space docling's serializer inserts between inline
1326/// items is stripped from the adjacent plain runs.
1327fn inline_segments(md: &str) -> Vec<String> {
1328    inline_segments_tagged(md, &[])
1329        .into_iter()
1330        .map(|(t, _)| t)
1331        .collect()
1332}
1333
1334/// Like [`inline_segments`], with each segment tagged `true` when it came from
1335/// plain (unmarked) text — those may still need splitting at run boundaries
1336/// invisible in markdown (underline, soft breaks).
1337///
1338/// `runs` are the node's structured inline runs (empty for a plain
1339/// paragraph). The flat text cannot tell an inline formula's `$…$` from a
1340/// literal dollar sign (`a bet of $5 … has won $6`, #1065), so a `$…$` span
1341/// is a formula only when it is one: when the node carries `formula` runs,
1342/// the span's LaTeX must be one of them; otherwise it must satisfy Pandoc's
1343/// `tex_math_dollars` delimiter rule ([`dollar_math_closer`]), which no
1344/// currency amount does.
1345fn inline_segments_tagged(md: &str, runs: &[crate::InlineRun]) -> Vec<(String, bool)> {
1346    let formula_runs: Vec<&str> = runs
1347        .iter()
1348        .filter(|r| r.formula)
1349        .map(|r| r.text.trim())
1350        .collect();
1351    let chars: Vec<char> = md.chars().collect();
1352    let n = chars.len();
1353    let find = |from: usize, pat: &str| -> Option<usize> {
1354        let hay: String = chars[from..].iter().collect();
1355        hay.find(pat).map(|p| from + hay[..p].chars().count())
1356    };
1357    let mut out: Vec<(String, bool)> = Vec::new();
1358    let mut plain = String::new();
1359    let mut after_span = false;
1360
1361    fn flush(
1362        out: &mut Vec<(String, bool)>,
1363        plain: &mut String,
1364        before_span: bool,
1365        after_span: bool,
1366    ) {
1367        let mut p = std::mem::take(plain);
1368        if after_span {
1369            if let Some(rest) = p.strip_prefix(' ') {
1370                p = rest.to_string();
1371            }
1372        }
1373        if before_span {
1374            if let Some(rest) = p.strip_suffix(' ') {
1375                p = rest.to_string();
1376            }
1377        }
1378        if !p.is_empty() {
1379            out.push((unescape_text(&p), true));
1380        }
1381    }
1382
1383    let mut i = 0;
1384    while i < n {
1385        let rest: String = chars[i..].iter().collect();
1386        // A hyperlink span (not an image): the whole `[text](url)` is one item.
1387        // The URL may itself contain balanced parentheses (`/Duck_(film)`),
1388        // so the closing `)` is found by paren depth, not first match.
1389        if chars[i] == '[' && !rest.starts_with("[](") {
1390            // The label may itself contain balanced brackets (`[[ 1 ]](#ref)`
1391            // has label `[ 1 ]`), but an *unbalanced* `[` means this bracket is
1392            // plain text preceding a real link (`[ [*note*](url) ]`).
1393            let balanced = |c: usize| {
1394                let mut d = 0i32;
1395                for &ch in &chars[i + 1..c] {
1396                    match ch {
1397                        '[' => d += 1,
1398                        ']' => d -= 1,
1399                        _ => {}
1400                    }
1401                }
1402                d == 0
1403            };
1404            if let Some(close) = find(i + 1, "](").filter(|&c| balanced(c)) {
1405                let mut depth = 0usize;
1406                let mut url_end = None;
1407                for (k, &c) in chars.iter().enumerate().skip(close + 2) {
1408                    match c {
1409                        '(' => depth += 1,
1410                        ')' => {
1411                            if depth == 0 {
1412                                url_end = Some(k);
1413                                break;
1414                            }
1415                            depth -= 1;
1416                        }
1417                        _ => {}
1418                    }
1419                }
1420                if let Some(endp) = url_end {
1421                    // An unsafe destination (`javascript:`, #860) is plain
1422                    // text, not a hyperlink item.
1423                    let url: String = chars[close + 2..endp].iter().collect();
1424                    if !crate::hyperlink::is_safe_hyperlink(&url) {
1425                        plain.extend(&chars[i + 1..close]);
1426                        i = endp + 1;
1427                        continue;
1428                    }
1429                    flush(&mut out, &mut plain, true, after_span);
1430                    out.push((
1431                        unescape_text(&chars[i..=endp].iter().collect::<String>()),
1432                        false,
1433                    ));
1434                    i = endp + 1;
1435                    after_span = true;
1436                    continue;
1437                }
1438            }
1439        }
1440        // An inline code span is a code item in docling's model, whose
1441        // standalone form is a fenced block; its backticks may run longer
1442        // than one (#859).
1443        if chars[i] == '`' {
1444            if let Some((s, e, after)) = crate::markdown::code_span_bounds(&chars, i) {
1445                if e > s && !chars[s..e].iter().all(|c| c.is_whitespace()) {
1446                    flush(&mut out, &mut plain, true, after_span);
1447                    let inner: String = chars[s..e].iter().collect();
1448                    out.push((
1449                        crate::markdown::code_fence("", &unescape_text(&inner)),
1450                        false,
1451                    ));
1452                    i = after;
1453                    after_span = true;
1454                    continue;
1455                }
1456            }
1457        }
1458        // A formatted span; longest markers first.
1459        let mut matched = false;
1460        for marker in ["***", "**", "*", "~~"] {
1461            if rest.starts_with(marker) {
1462                let mlen = marker.chars().count();
1463                if let Some(end) = find(i + mlen, marker) {
1464                    // A whitespace-only span (`* *` from a literal asterisk in
1465                    // running text next to a real italic) is not a docling run:
1466                    // treat the marker as plain text.
1467                    let inner_blank = chars[i + mlen..end].iter().all(|c| c.is_whitespace());
1468                    if end > i + mlen && !inner_blank {
1469                        flush(&mut out, &mut plain, true, after_span);
1470                        out.push((
1471                            unescape_text(&chars[i..end + mlen].iter().collect::<String>()),
1472                            false,
1473                        ));
1474                        i = end + mlen;
1475                        after_span = true;
1476                        matched = true;
1477                    }
1478                }
1479                break;
1480            }
1481        }
1482        if matched {
1483            continue;
1484        }
1485        // A literal `$$` inside running text is not an inline formula: copy it
1486        // through as plain characters.
1487        if rest.starts_with("$$") {
1488            plain.push_str("$$");
1489            i += 2;
1490            continue;
1491        }
1492        // An inline formula: standalone it re-serializes in display form.
1493        if chars[i] == '$' {
1494            let end = if formula_runs.is_empty() {
1495                dollar_math_closer(&chars, i)
1496            } else {
1497                find(i + 1, "$").filter(|&end| {
1498                    let latex: String = chars[i + 1..end].iter().collect();
1499                    formula_runs.contains(&latex.trim())
1500                })
1501            };
1502            if let Some(end) = end {
1503                if end > i + 1 {
1504                    flush(&mut out, &mut plain, true, after_span);
1505                    let latex: String = chars[i + 1..end].iter().collect();
1506                    out.push((format!("$${latex}$$"), false));
1507                    i = end + 1;
1508                    after_span = true;
1509                    continue;
1510                }
1511            }
1512        }
1513        plain.push(chars[i]);
1514        i += 1;
1515    }
1516    flush(&mut out, &mut plain, false, after_span);
1517    if out.is_empty() {
1518        out.push((unescape_text(md), true));
1519    }
1520    out
1521}
1522
1523/// The closing `$` of an inline formula opened at `open`, by Pandoc's
1524/// `tex_math_dollars` rule: the opener has a non-space character right after
1525/// it, the closer is the next `$`, has a non-space character right before it
1526/// and is not followed by a digit. `$5 riding … won $6` fails it twice (a
1527/// space before the second `$`, a digit after it), so a price is never a
1528/// formula, while `$x$`, `$a+b$` and `$E=mc^2$` still are.
1529fn dollar_math_closer(chars: &[char], open: usize) -> Option<usize> {
1530    let first = *chars.get(open + 1)?;
1531    if first.is_whitespace() || first == '$' {
1532        return None;
1533    }
1534    let end = open + 1 + chars[open + 1..].iter().position(|&c| c == '$')?;
1535    let before_ok = !chars[end - 1].is_whitespace();
1536    let after_ok = !chars.get(end + 1).is_some_and(|c| c.is_ascii_digit());
1537    (before_ok && after_ok).then_some(end)
1538}
1539
1540/// Split a plain markdown segment at run boundaries the markdown cannot show
1541/// (an underlined run, a `<sub>`/`<sup>` run): when a consecutive window of
1542/// two or more unmarked runs exactly covers the segment, each run is its own
1543/// document item.
1544fn split_plain_by_runs(segment: &str, runs: &[crate::InlineRun]) -> Option<Vec<String>> {
1545    let target = segment.trim();
1546    if target.is_empty() {
1547        return None;
1548    }
1549    let plainish =
1550        |r: &crate::InlineRun| !r.bold && !r.italic && !r.strike && !r.code && !r.formula;
1551    let fully_plain =
1552        |r: &crate::InlineRun| plainish(r) && !r.underline && r.script == crate::Script::Baseline;
1553    let unmarked: Vec<(&str, bool)> = runs
1554        .iter()
1555        .filter(|r| plainish(r))
1556        .map(|r| (r.text.as_str(), fully_plain(r)))
1557        .collect();
1558    for start in 0..unmarked.len() {
1559        let mut rest = target;
1560        let mut taken: Vec<(String, bool)> = Vec::new();
1561        for (t, fully) in &unmarked[start..] {
1562            let t = t.trim();
1563            if t.is_empty() {
1564                continue;
1565            }
1566            match rest.strip_prefix(t) {
1567                Some(r) => {
1568                    taken.push((unescape_text(t), *fully));
1569                    rest = r.trim_start();
1570                    if rest.is_empty() {
1571                        break;
1572                    }
1573                }
1574                None => break,
1575            }
1576        }
1577        if rest.is_empty() && taken.len() >= 2 {
1578            // Consecutive fully-plain pieces (no underline / sub / sup) are one
1579            // annotation in docling's model — `simplify_text_elements` merges
1580            // them joined with a space, so they never split between themselves.
1581            // Only an underline / sub / sup run is a genuine boundary.
1582            let mut merged: Vec<(String, bool)> = Vec::new();
1583            for (t, fully) in taken {
1584                match merged.last_mut() {
1585                    Some((last, true)) if fully => {
1586                        last.push(' ');
1587                        last.push_str(&t);
1588                    }
1589                    _ => merged.push((t, fully)),
1590                }
1591            }
1592            if merged.len() >= 2 {
1593                return Some(merged.into_iter().map(|(t, _)| t).collect());
1594            }
1595            return None;
1596        }
1597    }
1598    None
1599}
1600
1601/// A table cell's text for the triplet serializer. A *rich* cell (one carrying
1602/// block content) is re-serialized the way docling's chunking serializer sees
1603/// it: paragraphs joined with blank lines, a nested table as its own triplet
1604/// sentences, pictures as an empty placeholder. Plain cells use the flat text
1605/// with the markdown image placeholder stripped (the chunking serializer's
1606/// `image_placeholder` is empty).
1607fn cell_chunk_text(t: &Table, anchors: &[Vec<(usize, usize)>], r: usize, c: usize) -> String {
1608    // A rich cell's blocks live on its anchor; every position it covers
1609    // reads them (docling-core#857, #777).
1610    let (ar, ac) = anchors
1611        .get(r)
1612        .and_then(|row| row.get(c))
1613        .copied()
1614        .unwrap_or((r, c));
1615    if let Some(blocks) = t
1616        .cell_blocks
1617        .as_ref()
1618        .and_then(|b| b.get(ar))
1619        .and_then(|row| row.get(ac))
1620        .filter(|b| !b.is_empty())
1621    {
1622        let mut parts: Vec<String> = Vec::new();
1623        for node in blocks.iter() {
1624            let part = block_chunk_text(node);
1625            if !part.is_empty() {
1626                parts.push(part);
1627            }
1628        }
1629        return parts.join("\n\n");
1630    }
1631    let flat = t
1632        .rows
1633        .get(r)
1634        .and_then(|row| row.get(c))
1635        .map(String::as_str)
1636        .unwrap_or("");
1637    unescape_text(flat)
1638        .replace("<!-- image -->", "")
1639        .trim()
1640        .to_string()
1641}
1642
1643/// One block of a rich cell, serialized for chunking.
1644fn block_chunk_text(node: &Node) -> String {
1645    match node {
1646        Node::Paragraph { text } | Node::ListText { text, .. } => unescape_text(text),
1647        Node::LabeledText { .. } => block_chunk_text(&node.labeled_as_paragraph()),
1648        Node::InlineGroup { md_text, .. } => unescape_text(md_text),
1649        Node::Code { text, .. } => crate::markdown::code_fence("", &unescape_text(text)),
1650        Node::Table(inner) => triplet_table_text(inner),
1651        Node::Picture { caption, .. } => caption
1652            .as_deref()
1653            .filter(|c| !c.is_empty())
1654            .map(unescape_text)
1655            .unwrap_or_default(),
1656        Node::ListItem {
1657            ordered,
1658            number,
1659            text,
1660            ..
1661        } => {
1662            let marker = if *ordered {
1663                format!("{number}.")
1664            } else {
1665                "-".to_string()
1666            };
1667            format!("{marker} {}", unescape_text(text))
1668        }
1669        Node::CheckboxItem { checked, text } => {
1670            let mark = if *checked { "- [x] " } else { "- [ ] " };
1671            format!("{mark}{}", unescape_text(text))
1672        }
1673        Node::Heading { text, .. } => unescape_text(text),
1674        Node::Located { inner, .. }
1675        | Node::Prov { inner, .. }
1676        | Node::Track { inner, .. }
1677        | Node::ScriptText { inner, .. }
1678        | Node::Commented { inner, .. } => block_chunk_text(inner),
1679        Node::Group { layer: Some(_), .. } => String::new(),
1680        Node::Group { children, .. } => children
1681            .iter()
1682            .map(block_chunk_text)
1683            .filter(|s| !s.is_empty())
1684            .collect::<Vec<_>>()
1685            .join("\n"),
1686        _ => String::new(),
1687    }
1688}
1689
1690/// Reverse the model's baked markdown text escaping — same mapping as the JSON
1691/// exporter (docling chunks carry raw text).
1692fn unescape_text(s: &str) -> String {
1693    s.replace("&lt;", "<")
1694        .replace("&gt;", ">")
1695        .replace("&amp;", "&")
1696        .replace("\\_", "_")
1697}
1698
1699// ---------------------------------------------------------------------------
1700// Hybrid chunker
1701// ---------------------------------------------------------------------------
1702
1703/// Token counting for [`HybridChunker`] — docling's `BaseTokenizer`.
1704pub trait ChunkTokenizer {
1705    /// Number of tokens in `text` (no special tokens).
1706    fn count_tokens(&self, text: &str) -> usize;
1707    /// The chunk budget (docling's `max_tokens`, e.g. 256 for MiniLM).
1708    fn max_tokens(&self) -> usize;
1709}
1710
1711/// Tokenization-aware chunker on top of [`HierarchicalChunker`] — docling's
1712/// `HybridChunker` with default parameters (`merge_peers`,
1713/// `repeat_table_header` on; `omit_header_on_overflow` off).
1714pub struct HybridChunker<T: ChunkTokenizer> {
1715    tokenizer: T,
1716    merge_peers: bool,
1717}
1718
1719impl<T: ChunkTokenizer> HybridChunker<T> {
1720    pub fn new(tokenizer: T) -> Self {
1721        Self {
1722            tokenizer,
1723            merge_peers: true,
1724        }
1725    }
1726
1727    /// Disable merging of undersized same-heading neighbours.
1728    pub fn with_merge_peers(mut self, merge_peers: bool) -> Self {
1729        self.merge_peers = merge_peers;
1730        self
1731    }
1732
1733    pub fn max_tokens(&self) -> usize {
1734        self.tokenizer.max_tokens()
1735    }
1736
1737    /// Chunk the document.
1738    pub fn chunk(&self, doc: &DoclingDocument) -> Vec<DocChunk> {
1739        let mut chunks = Vec::new();
1740        self.chunk_with(doc, &mut |c| {
1741            chunks.push(c);
1742            true
1743        });
1744        chunks
1745    }
1746
1747    /// Stream the chunks: each hierarchical chunk is split against the token
1748    /// budget as the document walk produces it, and the peer merge flushes a
1749    /// merged chunk to `sink` as soon as its window closes (a chunk with
1750    /// different headings arrives, or the budget fills). A `false` return from
1751    /// `sink` cancels the chunking. [`Self::chunk`] is this with a collecting
1752    /// sink — the chunks and their order are identical.
1753    pub fn chunk_with(&self, doc: &DoclingDocument, sink: &mut dyn FnMut(DocChunk) -> bool) {
1754        // The refs are mapped onto the JSON export last, on the chunks as
1755        // emitted: the splitting re-serializes the walk's items (#1041).
1756        let mut mapper = RefMapper::new(&doc.export_to_json_value());
1757        let sink = &mut |c: DocChunk| sink(mapper.remap(c));
1758        let mut merger = PeerMerger::default();
1759        let mut alive = true;
1760        HierarchicalChunker::walk_nodes(doc, &mut |c| {
1761            for split in self.split_by_doc_items(c) {
1762                for chunk in self.split_using_plain_text(split) {
1763                    if !alive {
1764                        return false;
1765                    }
1766                    alive = if self.merge_peers {
1767                        self.merge_push(&mut merger, chunk, sink)
1768                    } else {
1769                        sink(chunk)
1770                    };
1771                }
1772            }
1773            alive
1774        });
1775        if alive {
1776            self.merge_flush(&mut merger, sink);
1777        }
1778    }
1779
1780    fn count_chunk_tokens(&self, chunk: &DocChunk) -> usize {
1781        self.tokenizer.count_tokens(&contextualize(chunk))
1782    }
1783
1784    /// docling's `_make_chunk_from_doc_items`: single-item chunks keep their
1785    /// text; multi-item windows re-join the items' standalone serializations.
1786    fn window_chunk(&self, chunk: &DocChunk, start: usize, end: usize) -> DocChunk {
1787        let doc_items: Vec<ChunkItem> = chunk.doc_items[start..=end].to_vec();
1788        let text = if chunk.doc_items.len() == 1 {
1789            chunk.text.clone()
1790        } else {
1791            doc_items
1792                .iter()
1793                .filter(|it| !it.text.is_empty())
1794                .map(|it| it.text.as_str())
1795                .collect::<Vec<_>>()
1796                .join("\n")
1797        };
1798        DocChunk {
1799            text,
1800            headings: chunk.headings.clone(),
1801            doc_items,
1802        }
1803    }
1804
1805    fn split_by_doc_items(&self, chunk: DocChunk) -> Vec<DocChunk> {
1806        if chunk.doc_items.is_empty() {
1807            return vec![chunk];
1808        }
1809        let max = self.max_tokens();
1810        let num_items = chunk.doc_items.len();
1811        let mut chunks = Vec::new();
1812        let mut window_start = 0usize;
1813        let mut window_end = 0usize; // inclusive
1814        while window_end < num_items {
1815            let mut new_chunk = self.window_chunk(&chunk, window_start, window_end);
1816            if self.count_chunk_tokens(&new_chunk) <= max {
1817                if window_end < num_items - 1 {
1818                    window_end += 1;
1819                    continue;
1820                } else {
1821                    window_end = num_items; // last loop
1822                }
1823            } else if window_start == window_end {
1824                // One item that doesn't fit: keep it; the plain-text splitter
1825                // takes over.
1826                window_end += 1;
1827                window_start = window_end;
1828            } else {
1829                // The window without its last item fit; flush that and start a
1830                // new window at the current item.
1831                new_chunk = self.window_chunk(&chunk, window_start, window_end - 1);
1832                window_start = window_end;
1833            }
1834            chunks.push(new_chunk);
1835        }
1836        chunks
1837    }
1838
1839    fn split_using_plain_text(&self, chunk: DocChunk) -> Vec<DocChunk> {
1840        let total = self.count_chunk_tokens(&chunk);
1841        let max = self.max_tokens();
1842        if total <= max {
1843            return vec![chunk];
1844        }
1845        let text_len = self.tokenizer.count_tokens(&chunk.text);
1846        let other_len = total - text_len;
1847        if other_len >= max {
1848            // Headings alone exceed the budget: drop them and retry.
1849            let stripped = DocChunk {
1850                headings: None,
1851                ..chunk
1852            };
1853            return self.split_using_plain_text(stripped);
1854        }
1855        let available = max - other_len;
1856
1857        let make = |segments: Vec<String>| -> Vec<DocChunk> {
1858            segments
1859                .into_iter()
1860                .map(|s| DocChunk {
1861                    text: s,
1862                    headings: chunk.headings.clone(),
1863                    doc_items: chunk.doc_items.clone(),
1864                })
1865                .collect()
1866        };
1867        if chunk.doc_items.len() == 1 && chunk.doc_items[0].kind == ChunkItemKind::Table {
1868            // Table: split line-based. The triplet serializer has no header
1869            // lines, so this is a line-preserving split of the table text.
1870            // docling-core ≥ 2.103 (docling-core#690, docling.rs#987) budgets
1871            // the pieces at `available` (the window minus the heading path),
1872            // like text, and re-splits with a smaller budget when a piece's
1873            // `contextualize()` still overshoots — token counts are not
1874            // additive, so the subtraction alone can leave a piece a token
1875            // or two over. (≤ 2.102 packed the full window, so every piece
1876            // overran by the heading length — a deliberate fix here.)
1877            let lines: Vec<String> = chunk
1878                .text
1879                .split('\n')
1880                .filter(|l| !l.trim().is_empty())
1881                .map(|l| l.to_string())
1882                .collect();
1883            let mut budget = available;
1884            loop {
1885                let pieces = make(line_chunk_text(&lines, &self.tokenizer, budget));
1886                let overflow = pieces
1887                    .iter()
1888                    .map(|p| self.count_chunk_tokens(p).saturating_sub(max))
1889                    .max()
1890                    .unwrap_or(0);
1891                if overflow == 0 || budget <= overflow {
1892                    return pieces;
1893                }
1894                budget -= overflow;
1895            }
1896        }
1897        make(semchunk(&chunk.text, available, &self.tokenizer))
1898    }
1899
1900    /// One step of docling's `_merge_chunks_with_matching_metadata`, streamed:
1901    /// extend the window with `chunk` when its headings match the window's and
1902    /// the merged window stays within budget, otherwise flush the window to
1903    /// `sink` and start a new one at `chunk`. Returns `false` once the sink
1904    /// cancels.
1905    ///
1906    /// Linear, as docling-core 2.102 has it (docling-core#823, #782): each
1907    /// chunk's text is counted once, the window grows on a running estimate
1908    /// (text tokens, the delimiter's cost, the headings' overhead), an exact
1909    /// count of the merged window runs only where the estimate overflows, and
1910    /// the final window is verified exactly — shrunk back to the largest one
1911    /// that fits when the estimate under-counted, the chunks it gives up
1912    /// starting the next window. Rebuilding and re-tokenizing the whole window
1913    /// for every chunk was quadratic in the window's length.
1914    fn merge_push(
1915        &self,
1916        m: &mut PeerMerger,
1917        chunk: DocChunk,
1918        sink: &mut dyn FnMut(DocChunk) -> bool,
1919    ) -> bool {
1920        self.merge_feed(m, VecDeque::from([(chunk, None)]), sink)
1921    }
1922
1923    /// Feed chunks (with their text token count when already known) to the
1924    /// merge window, closing it whenever a chunk cannot join.
1925    fn merge_feed(
1926        &self,
1927        m: &mut PeerMerger,
1928        mut pending: VecDeque<(DocChunk, Option<usize>)>,
1929        sink: &mut dyn FnMut(DocChunk) -> bool,
1930    ) -> bool {
1931        while let Some((chunk, tokens)) = pending.pop_front() {
1932            let tokens = tokens.unwrap_or_else(|| self.tokenizer.count_tokens(&chunk.text));
1933            if let Err(chunk) = self.merge_extend(m, chunk, tokens) {
1934                let (alive, rest) = self.merge_close(m, sink);
1935                if !alive {
1936                    return false;
1937                }
1938                pending.push_front((chunk, Some(tokens)));
1939                for item in rest.into_iter().rev() {
1940                    pending.push_front(item);
1941                }
1942            }
1943        }
1944        true
1945    }
1946
1947    /// Add `chunk` (of `tokens` text tokens) to the window, or hand it back
1948    /// when its headings differ or the window would overflow.
1949    fn merge_extend(
1950        &self,
1951        m: &mut PeerMerger,
1952        chunk: DocChunk,
1953        tokens: usize,
1954    ) -> Result<(), DocChunk> {
1955        let max = self.max_tokens() as i64;
1956        if m.window.is_empty() {
1957            // The headings' overhead around the joined text is shared by every
1958            // candidate of this window (it may be negative).
1959            m.overhead = self.count_chunk_tokens(&chunk) as i64 - tokens as i64;
1960            m.running = tokens as i64;
1961            m.window.push((chunk, tokens));
1962            return Ok(());
1963        }
1964        if chunk.headings != m.window[0].0.headings {
1965            return Err(chunk);
1966        }
1967        let delim = *m.delim.get_or_insert_with(|| {
1968            // `_estimate_delimiter_tokens`: what joining two texts adds.
1969            let t = &self.tokenizer;
1970            t.count_tokens("a\nb") as i64 - t.count_tokens("a") as i64 - t.count_tokens("b") as i64
1971        });
1972        m.running += tokens as i64 + delim;
1973        if m.running + m.overhead > max {
1974            let exact = self.count_chunk_tokens(&merged_chunk(
1975                m.window.iter().map(|(c, _)| c).chain([&chunk]),
1976            )) as i64;
1977            if exact > max {
1978                return Err(chunk);
1979            }
1980            // The estimate overshot; re-anchor it on the exact count.
1981            m.running = exact - m.overhead;
1982        }
1983        m.window.push((chunk, tokens));
1984        Ok(())
1985    }
1986
1987    /// Close the window: verify it exactly, shrinking it back to the largest
1988    /// prefix that fits, emit that (a single chunk unchanged), and return the
1989    /// chunks given up, which start the next window.
1990    fn merge_close(
1991        &self,
1992        m: &mut PeerMerger,
1993        sink: &mut dyn FnMut(DocChunk) -> bool,
1994    ) -> (bool, Vec<(DocChunk, Option<usize>)>) {
1995        if m.window.is_empty() {
1996            return (true, Vec::new());
1997        }
1998        let max = self.max_tokens();
1999        let mut fit = m.window.len() - 1;
2000        while fit > 0
2001            && self.count_chunk_tokens(&merged_chunk(m.window[..=fit].iter().map(|(c, _)| c))) > max
2002        {
2003            fit -= 1;
2004        }
2005        let rest = m
2006            .window
2007            .split_off(fit + 1)
2008            .into_iter()
2009            .map(|(c, t)| (c, Some(t)))
2010            .collect();
2011        let out = if m.window.len() == 1 {
2012            m.window.pop().expect("single-chunk window").0
2013        } else {
2014            let merged = merged_chunk(m.window.iter().map(|(c, _)| c));
2015            m.window.clear();
2016            merged
2017        };
2018        (sink(out), rest)
2019    }
2020
2021    /// Flush the merge window at the end of the stream (feeding back what a
2022    /// shrunk window gave up). Returns `false` once the sink cancels.
2023    fn merge_flush(&self, m: &mut PeerMerger, sink: &mut dyn FnMut(DocChunk) -> bool) -> bool {
2024        while !m.window.is_empty() {
2025            let (alive, rest) = self.merge_close(m, sink);
2026            if !alive || !self.merge_feed(m, rest.into(), sink) {
2027                return false;
2028            }
2029        }
2030        true
2031    }
2032}
2033
2034/// docling's merged peer chunk: the texts joined by `\n`, every chunk's doc
2035/// items, the first chunk's headings.
2036fn merged_chunk<'a>(chunks: impl Iterator<Item = &'a DocChunk> + Clone) -> DocChunk {
2037    let mut first = chunks.clone();
2038    DocChunk {
2039        text: chunks
2040            .clone()
2041            .map(|c| c.text.as_str())
2042            .collect::<Vec<_>>()
2043            .join("\n"),
2044        headings: first.next().and_then(|c| c.headings.clone()),
2045        doc_items: chunks.flat_map(|c| c.doc_items.iter().cloned()).collect(),
2046    }
2047}
2048
2049/// The in-flight peer-merge window of [`HybridChunker::chunk_with`]: the
2050/// window's chunks with their text token counts, the running token estimate
2051/// of the joined text, the window's headings overhead, and the delimiter's
2052/// token cost (measured once).
2053#[derive(Default)]
2054struct PeerMerger {
2055    window: Vec<(DocChunk, usize)>,
2056    running: i64,
2057    overhead: i64,
2058    delim: Option<i64>,
2059}
2060
2061// ---------------------------------------------------------------------------
2062// Line-based token chunking (docling's LineBasedTokenChunker, empty prefix)
2063// ---------------------------------------------------------------------------
2064
2065/// Pack lines into chunks of at most `max_tokens`, splitting a line only when
2066/// it exceeds the budget on its own — docling's `LineBasedTokenChunker
2067/// .chunk_text` with an empty prefix (which is what the triplet table
2068/// serializer yields). Reproduces its exact output, including the `\n` it
2069/// prepends to a carried-over segment of an oversized line.
2070fn line_chunk_text<T: ChunkTokenizer>(lines: &[String], tok: &T, max_tokens: usize) -> Vec<String> {
2071    let mut chunks: Vec<String> = Vec::new();
2072    let mut current = String::new();
2073    let mut current_len = 0usize;
2074
2075    for line in lines {
2076        let mut remaining: Vec<char> = line.chars().collect();
2077        loop {
2078            let rem_str: String = remaining.iter().collect();
2079            let line_tokens = tok.count_tokens(&rem_str);
2080            let available = max_tokens.saturating_sub(current_len);
2081
2082            if line_tokens <= available {
2083                current.push_str(&rem_str);
2084                current_len += line_tokens;
2085                break;
2086            }
2087            if line_tokens <= max_tokens {
2088                chunks.push(std::mem::take(&mut current));
2089                current_len = 0;
2090                continue;
2091            }
2092            // Too large even for an empty chunk: split off what fits.
2093            let (mut take, rest) = split_by_token_limit(&remaining, available, tok);
2094            let mut rest = rest;
2095            if take.is_empty() {
2096                if rest.is_empty() {
2097                    break;
2098                }
2099                take = rest[..1].iter().collect();
2100                rest = rest[1..].to_vec();
2101            }
2102            current.push('\n');
2103            current.push_str(&take);
2104            chunks.push(std::mem::take(&mut current));
2105            current_len = 0;
2106            remaining = rest;
2107        }
2108    }
2109    if !current.is_empty() {
2110        chunks.push(current);
2111    }
2112    chunks
2113}
2114
2115/// Binary-search the longest char-prefix of `text` within `token_limit`
2116/// tokens, preferring to break at the last ASCII space — docling's
2117/// `split_by_token_limit`.
2118fn split_by_token_limit<T: ChunkTokenizer>(
2119    text: &[char],
2120    token_limit: usize,
2121    tok: &T,
2122) -> (String, Vec<char>) {
2123    if token_limit == 0 || text.is_empty() {
2124        return (String::new(), text.to_vec());
2125    }
2126    let full: String = text.iter().collect();
2127    if tok.count_tokens(&full) <= token_limit {
2128        return (full, Vec::new());
2129    }
2130    let (mut lo, mut hi) = (0usize, text.len());
2131    let mut best: Option<usize> = None;
2132    while lo <= hi {
2133        let mid = (lo + hi) / 2;
2134        let head: String = text[..mid].iter().collect();
2135        if tok.count_tokens(&head) <= token_limit {
2136            best = Some(mid);
2137            lo = mid + 1;
2138        } else {
2139            if mid == 0 {
2140                break;
2141            }
2142            hi = mid - 1;
2143        }
2144    }
2145    let mut best_idx = match best {
2146        Some(b) if b > 0 => b,
2147        _ => return (String::new(), text.to_vec()),
2148    };
2149    // Snap back to the last space, if that leaves a non-empty head.
2150    if let Some(pos) = text[..best_idx].iter().rposition(|c| *c == ' ') {
2151        if pos > 0 {
2152            best_idx = pos;
2153        }
2154    }
2155    (text[..best_idx].iter().collect(), text[best_idx..].to_vec())
2156}
2157
2158// ---------------------------------------------------------------------------
2159// semchunk port (the plain-text splitter HybridChunker delegates to)
2160// ---------------------------------------------------------------------------
2161
2162/// Semantically meaningful non-whitespace splitters, most desirable first.
2163const NON_WS_SPLITTERS: &[&str] = &[
2164    ".", "?", "!", "*", ";", ",", "(", ")", "[", "]", "\u{201c}", "\u{201d}", "\u{2018}",
2165    "\u{2019}", "'", "\"", "`", ":", "\u{2014}", "\u{2026}", "/", "\\", "\u{2013}", "&", "-",
2166];
2167
2168/// Split `text` into chunks of at most `chunk_size` tokens using the most
2169/// semantically meaningful splitter available — the `semchunk` algorithm
2170/// docling's HybridChunker delegates plain-text splitting to.
2171pub fn semchunk<T: ChunkTokenizer>(text: &str, chunk_size: usize, tok: &T) -> Vec<String> {
2172    let mut cache: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
2173    let mut counter = |s: &str| -> usize {
2174        if let Some(n) = cache.get(s) {
2175            return *n;
2176        }
2177        let n = tok.count_tokens(s);
2178        cache.insert(s.to_string(), n);
2179        n
2180    };
2181    let chunks = semchunk_rec(text, chunk_size, &mut counter);
2182    // top-level: drop empty / all-whitespace chunks
2183    chunks
2184        .into_iter()
2185        .filter(|c| !c.is_empty() && !c.chars().all(char::is_whitespace))
2186        .collect()
2187}
2188
2189/// One recursion level of semchunk: split, merge windows back up to size, and
2190/// recurse into oversized splits.
2191fn semchunk_rec(
2192    text: &str,
2193    chunk_size: usize,
2194    counter: &mut dyn FnMut(&str) -> usize,
2195) -> Vec<String> {
2196    let (splitter, splitter_is_ws, splits) = split_text(text);
2197
2198    let split_lens: Vec<usize> = splits.iter().map(|s| s.chars().count()).collect();
2199    let mut cum_lens = Vec::with_capacity(splits.len() + 1);
2200    cum_lens.push(0usize);
2201    for l in &split_lens {
2202        cum_lens.push(cum_lens.last().unwrap() + l);
2203    }
2204    let num_splits_plus_one = splits.len() + 1;
2205
2206    let mut chunks: Vec<String> = Vec::new();
2207    let mut skips: std::collections::HashSet<usize> = std::collections::HashSet::new();
2208
2209    for i in 0..splits.len() {
2210        if skips.contains(&i) {
2211            continue;
2212        }
2213        let split = &splits[i];
2214        if counter(split) > chunk_size {
2215            let inner = semchunk_rec(split, chunk_size, counter);
2216            chunks.extend(inner);
2217        } else {
2218            let (end, merged) = merge_splits(
2219                &splits,
2220                &cum_lens,
2221                chunk_size,
2222                &splitter,
2223                counter,
2224                i,
2225                num_splits_plus_one,
2226            );
2227            for j in (i + 1)..end {
2228                skips.insert(j);
2229            }
2230            chunks.push(merged);
2231        }
2232        // Re-attach a non-whitespace splitter to the last chunk (or emit it as
2233        // its own chunk if it doesn't fit).
2234        let is_last = i == splits.len() - 1 || ((i + 1)..splits.len()).all(|j| skips.contains(&j));
2235        if !splitter_is_ws && !is_last {
2236            let with_splitter = format!(
2237                "{}{}",
2238                chunks.last().map(String::as_str).unwrap_or(""),
2239                splitter
2240            );
2241            if counter(&with_splitter) <= chunk_size {
2242                if let Some(last) = chunks.last_mut() {
2243                    *last = with_splitter;
2244                } else {
2245                    chunks.push(with_splitter);
2246                }
2247            } else {
2248                chunks.push(splitter.clone());
2249            }
2250        }
2251    }
2252    chunks
2253}
2254
2255/// docling/semchunk's `merge_splits`: extend the window with a cum-length-guided
2256/// binary search until the token budget is hit.
2257fn merge_splits(
2258    splits: &[String],
2259    cum_lens: &[usize],
2260    chunk_size: usize,
2261    splitter: &str,
2262    counter: &mut dyn FnMut(&str) -> usize,
2263    start: usize,
2264    high_init: usize,
2265) -> (usize, String) {
2266    let mut average = 0.2f64;
2267    let mut low = start;
2268    let mut high = high_init;
2269    let offset = cum_lens[start];
2270    let mut target = offset as f64 + (chunk_size as f64 * average);
2271
2272    while low < high {
2273        let i = bisect_left(cum_lens, target, low, high);
2274        let midpoint = i.min(high - 1);
2275        let joined = splits[start..midpoint.max(start)].join(splitter);
2276        let tokens = counter(&joined);
2277        let local_cum = cum_lens[midpoint] - offset;
2278        if local_cum > 0 && tokens > 0 {
2279            average = local_cum as f64 / tokens as f64;
2280            target = offset as f64 + (chunk_size as f64 * average);
2281        }
2282        if tokens > chunk_size {
2283            high = midpoint;
2284        } else {
2285            low = midpoint + 1;
2286        }
2287    }
2288    let end = low - 1;
2289    (end, splits[start..end.max(start)].join(splitter))
2290}
2291
2292fn bisect_left(sorted: &[usize], target: f64, mut low: usize, mut high: usize) -> usize {
2293    while low < high {
2294        let mid = (low + high) / 2;
2295        if (sorted[mid] as f64) < target {
2296            low = mid + 1;
2297        } else {
2298            high = mid;
2299        }
2300    }
2301    low
2302}
2303
2304/// semchunk's `_split_text`: pick the most desirable splitter present.
2305fn split_text(text: &str) -> (String, bool, Vec<String>) {
2306    // Longest run of newlines/carriage returns.
2307    if text.contains('\n') || text.contains('\r') {
2308        let splitter = longest_run(text, |c| c == '\n' || c == '\r');
2309        return (splitter.clone(), true, split_on(text, &splitter));
2310    }
2311    // Longest run of tabs.
2312    if text.contains('\t') {
2313        let splitter = longest_run(text, |c| c == '\t');
2314        return (splitter.clone(), true, split_on(text, &splitter));
2315    }
2316    // Longest run of whitespace.
2317    if text.chars().any(char::is_whitespace) {
2318        let splitter = longest_run(text, char::is_whitespace);
2319        if splitter.chars().count() == 1 {
2320            // Prefer a whitespace char preceded by a semantic splitter.
2321            for preceder in NON_WS_SPLITTERS {
2322                if let Some((ws, parts)) = split_after_preceder(text, preceder) {
2323                    return (ws, true, parts);
2324                }
2325            }
2326        }
2327        return (splitter.clone(), true, split_on(text, &splitter));
2328    }
2329    // Most desirable semantic splitter present.
2330    for s in NON_WS_SPLITTERS {
2331        if text.contains(s) {
2332            return (s.to_string(), false, split_on(text, s));
2333        }
2334    }
2335    // No splitter at all: split into characters.
2336    (
2337        String::new(),
2338        true,
2339        text.chars().map(|c| c.to_string()).collect(),
2340    )
2341}
2342
2343/// The longest maximal run of chars matching `pred` (first one wins ties).
2344fn longest_run(text: &str, pred: impl Fn(char) -> bool) -> String {
2345    let mut best = String::new();
2346    let mut cur = String::new();
2347    for c in text.chars() {
2348        if pred(c) {
2349            cur.push(c);
2350        } else {
2351            if cur.chars().count() > best.chars().count() {
2352                best = cur.clone();
2353            }
2354            cur.clear();
2355        }
2356    }
2357    if cur.chars().count() > best.chars().count() {
2358        best = cur;
2359    }
2360    best
2361}
2362
2363fn split_on(text: &str, splitter: &str) -> Vec<String> {
2364    text.split(splitter).map(str::to_string).collect()
2365}
2366
2367/// Python: `re.search(rf'{p}(\s)', text)` → the first whitespace char preceded
2368/// by `p`; then `re.split(rf'(?<={p}){s}', text)` — split at every occurrence
2369/// of that whitespace char immediately preceded by `p`.
2370fn split_after_preceder(text: &str, preceder: &str) -> Option<(String, Vec<String>)> {
2371    let chars: Vec<char> = text.chars().collect();
2372    let p: Vec<char> = preceder.chars().collect();
2373    let mut ws: Option<char> = None;
2374    for i in p.len()..chars.len() {
2375        if chars[i].is_whitespace() && chars[i - p.len()..i] == p[..] {
2376            ws = Some(chars[i]);
2377            break;
2378        }
2379    }
2380    let ws = ws?;
2381    let mut parts = Vec::new();
2382    let mut cur = String::new();
2383    let mut i = 0usize;
2384    while i < chars.len() {
2385        if chars[i] == ws && i >= p.len() && chars[i - p.len()..i] == p[..] {
2386            parts.push(std::mem::take(&mut cur));
2387            i += 1;
2388            continue;
2389        }
2390        cur.push(chars[i]);
2391        i += 1;
2392    }
2393    parts.push(cur);
2394    Some((ws.to_string(), parts))
2395}
2396
2397// ---------------------------------------------------------------------------
2398// HuggingFace tokenizer (feature `chunking`)
2399// ---------------------------------------------------------------------------
2400
2401#[cfg(feature = "chunking")]
2402mod hf {
2403    use super::ChunkTokenizer;
2404
2405    /// Where `scripts/install/download_dependencies.sh` puts the hybrid
2406    /// chunker's default tokenizer (all-MiniLM-L6-v2's `tokenizer.json`),
2407    /// relative to the process's working directory — the same convention as
2408    /// the `.models/` ONNX files.
2409    pub const DEFAULT_TOKENIZER_PATH: &str = ".models/chunk/tokenizer.json";
2410
2411    /// Resolve the tokenizer path for the hybrid chunker: an explicit path
2412    /// wins; otherwise fall back to [`DEFAULT_TOKENIZER_PATH`] when it exists
2413    /// on disk. Errors with the download instructions when neither is
2414    /// available.
2415    pub fn resolve_tokenizer_path(explicit: Option<&str>) -> Result<String, String> {
2416        if let Some(p) = explicit {
2417            return Ok(p.to_string());
2418        }
2419        let resolved = crate::assets::resolve(DEFAULT_TOKENIZER_PATH);
2420        if std::path::Path::new(&resolved).exists() {
2421            return Ok(resolved);
2422        }
2423        Err(format!(
2424            "the hybrid chunker needs a HuggingFace tokenizer.json: none passed and \
2425             {DEFAULT_TOKENIZER_PATH} does not exist — run \
2426             scripts/install/download_dependencies.sh (or pass an explicit path)"
2427        ))
2428    }
2429
2430    /// [`ChunkTokenizer`] backed by a HuggingFace `tokenizer.json` — the Rust
2431    /// analogue of docling's `HuggingFaceTokenizer` (whose default is
2432    /// `sentence-transformers/all-MiniLM-L6-v2` with `max_tokens` 256).
2433    pub struct HuggingFaceTokenizer {
2434        tok: tokenizers::Tokenizer,
2435        max_tokens: usize,
2436    }
2437
2438    impl HuggingFaceTokenizer {
2439        /// Load the tokenizer from an explicit path, or from
2440        /// [`DEFAULT_TOKENIZER_PATH`] when `path` is `None` (see
2441        /// [`resolve_tokenizer_path`]).
2442        pub fn resolve(path: Option<&str>, max_tokens: usize) -> Result<Self, String> {
2443            Self::from_file(resolve_tokenizer_path(path)?, max_tokens)
2444        }
2445
2446        /// Load a `tokenizer.json`. `max_tokens` is the chunk budget (docling
2447        /// resolves it from the model's `sentence_bert_config.json`; for the
2448        /// default MiniLM model that is 256).
2449        pub fn from_file(
2450            path: impl AsRef<std::path::Path>,
2451            max_tokens: usize,
2452        ) -> Result<Self, String> {
2453            let mut tok = tokenizers::Tokenizer::from_file(path.as_ref())
2454                .map_err(|e| format!("failed to load tokenizer: {e}"))?;
2455            // Counting must see the full text (docling tokenizes without
2456            // truncation, padding, or special tokens — MiniLM's tokenizer.json
2457            // ships with fixed-length padding enabled, which would make every
2458            // short string count as the padded length).
2459            let _ = tok.with_truncation(None);
2460            tok.with_padding(None);
2461            Ok(Self { tok, max_tokens })
2462        }
2463    }
2464
2465    impl ChunkTokenizer for HuggingFaceTokenizer {
2466        fn count_tokens(&self, text: &str) -> usize {
2467            self.tok
2468                .encode(text, false)
2469                .map(|e| e.get_tokens().len())
2470                .unwrap_or(0)
2471        }
2472        fn max_tokens(&self) -> usize {
2473            self.max_tokens
2474        }
2475    }
2476}
2477
2478#[cfg(feature = "chunking")]
2479pub use hf::{resolve_tokenizer_path, HuggingFaceTokenizer, DEFAULT_TOKENIZER_PATH};
2480
2481// ---------------------------------------------------------------------------
2482// Window chunker (feature `chunking`) — docling-rag's Markdown window chunker
2483// ---------------------------------------------------------------------------
2484
2485#[cfg(feature = "chunking")]
2486mod window {
2487    use super::DocChunk;
2488    use pulldown_cmark::{Event, HeadingLevel, Parser, Tag, TagEnd};
2489
2490    /// A contiguous run of body text under a heading path.
2491    #[derive(Debug, Clone, Default)]
2492    pub struct Section {
2493        /// The heading stack in effect for this section, outermost first
2494        /// (e.g. `["Guide", "Setup"]`). Empty for pre-heading / body-only text.
2495        pub heading_path: Vec<String>,
2496        /// The plain words of the section body, markup stripped.
2497        pub words: Vec<String>,
2498    }
2499
2500    impl Section {
2501        /// The heading path rendered as a single context line, e.g.
2502        /// `# Guide > Setup`. Empty string when there is no heading.
2503        pub fn heading_context(&self) -> String {
2504            if self.heading_path.is_empty() {
2505                String::new()
2506            } else {
2507                format!("# {}", self.heading_path.join(" > "))
2508            }
2509        }
2510    }
2511
2512    fn level_index(level: HeadingLevel) -> usize {
2513        match level {
2514            HeadingLevel::H1 => 1,
2515            HeadingLevel::H2 => 2,
2516            HeadingLevel::H3 => 3,
2517            HeadingLevel::H4 => 4,
2518            HeadingLevel::H5 => 5,
2519            HeadingLevel::H6 => 6,
2520        }
2521    }
2522
2523    /// Parse Markdown into heading-bounded sections. A new section starts at
2524    /// every heading; the heading path is maintained as a stack keyed by
2525    /// heading level.
2526    pub fn parse_sections(markdown: &str) -> Vec<Section> {
2527        parse_sections_with_stack(markdown, Vec::new()).0
2528    }
2529
2530    /// [`parse_sections`] with an explicit initial heading stack, returning the
2531    /// final stack — lets a streaming caller carry heading context across
2532    /// pieces. `heading_stack[i]` holds the current heading text at level `i+1`
2533    /// (may be empty when a level was skipped).
2534    pub fn parse_sections_with_stack(
2535        markdown: &str,
2536        initial_stack: Vec<String>,
2537    ) -> (Vec<Section>, Vec<String>) {
2538        let mut heading_stack: Vec<String> = initial_stack;
2539        let mut sections: Vec<Section> = Vec::new();
2540        // Text before the first heading of this piece continues the carried-over
2541        // section, so it keeps the heading path in effect at the split point.
2542        let mut current = Section {
2543            heading_path: heading_stack
2544                .iter()
2545                .filter(|h| !h.is_empty())
2546                .cloned()
2547                .collect(),
2548            words: Vec::new(),
2549        };
2550
2551        let mut in_heading = false;
2552        let mut heading_level = 0usize;
2553        let mut heading_buf = String::new();
2554
2555        let push_words = |section: &mut Section, text: &str| {
2556            for w in text.split_whitespace() {
2557                section.words.push(w.to_string());
2558            }
2559        };
2560
2561        let flush = |sections: &mut Vec<Section>, section: &mut Section| {
2562            if !section.words.is_empty() {
2563                sections.push(std::mem::take(section));
2564            } else {
2565                *section = Section::default();
2566            }
2567        };
2568
2569        for event in Parser::new(markdown) {
2570            match event {
2571                Event::Start(Tag::Heading { level, .. }) => {
2572                    in_heading = true;
2573                    heading_level = level_index(level);
2574                    heading_buf.clear();
2575                }
2576                Event::End(TagEnd::Heading(_)) => {
2577                    in_heading = false;
2578                    // Update the heading stack: set this level, drop anything deeper.
2579                    let idx = heading_level.saturating_sub(1);
2580                    if heading_stack.len() <= idx {
2581                        heading_stack.resize(idx + 1, String::new());
2582                    } else {
2583                        heading_stack.truncate(idx + 1);
2584                    }
2585                    heading_stack[idx] = heading_buf.trim().to_string();
2586                    // A heading begins a new section.
2587                    flush(&mut sections, &mut current);
2588                    current.heading_path = heading_stack
2589                        .iter()
2590                        .filter(|h| !h.is_empty())
2591                        .cloned()
2592                        .collect();
2593                }
2594                Event::Text(t) | Event::Code(t) => {
2595                    if in_heading {
2596                        if !heading_buf.is_empty() {
2597                            heading_buf.push(' ');
2598                        }
2599                        heading_buf.push_str(&t);
2600                    } else {
2601                        push_words(&mut current, &t);
2602                    }
2603                }
2604                // Treat hard/soft breaks and rules as whitespace (words already split).
2605                Event::SoftBreak | Event::HardBreak | Event::Rule => {}
2606                _ => {}
2607            }
2608        }
2609        flush(&mut sections, &mut current);
2610        (sections, heading_stack)
2611    }
2612
2613    /// docling-rag's Markdown **window chunker**: the document is split into
2614    /// heading-bounded [`Section`]s of plain words (markup stripped), and a
2615    /// fixed-size window of [`Self::max_words`] words slides over each section
2616    /// with [`Self::overlap`] fractional overlap. A chunk never crosses a
2617    /// heading boundary; [`Self::contextualize`] prefixes the heading path.
2618    #[derive(Debug, Clone)]
2619    pub struct WindowChunker {
2620        /// Window size in words (docling-rag's default 300).
2621        pub max_words: usize,
2622        /// Fractional overlap between consecutive windows (default 0.05 = 5%).
2623        pub overlap: f32,
2624    }
2625
2626    impl Default for WindowChunker {
2627        fn default() -> Self {
2628            WindowChunker {
2629                max_words: 300,
2630                overlap: 0.05,
2631            }
2632        }
2633    }
2634
2635    impl WindowChunker {
2636        pub fn new(max_words: usize, overlap: f32) -> Self {
2637            WindowChunker { max_words, overlap }
2638        }
2639
2640        /// The window size, kept ≥ 1.
2641        fn word_budget(&self) -> usize {
2642            self.max_words.max(1)
2643        }
2644
2645        /// Number of words carried from one window into the next; capped so
2646        /// the window always advances.
2647        fn overlap_words(&self, budget: usize) -> usize {
2648            let o = (budget as f32 * self.overlap).round() as usize;
2649            o.min(budget.saturating_sub(1))
2650        }
2651
2652        /// Chunk a Markdown document.
2653        pub fn chunk(&self, markdown: &str) -> Vec<DocChunk> {
2654            let mut chunks = Vec::new();
2655            self.chunk_with(markdown, &mut |c| {
2656                chunks.push(c);
2657                true
2658            });
2659            chunks
2660        }
2661
2662        /// Stream the chunks: `sink` receives each window as it is cut, and a
2663        /// `false` return cancels. [`Self::chunk`] is this with a collecting
2664        /// sink — the chunks and their order are identical.
2665        pub fn chunk_with(&self, markdown: &str, sink: &mut dyn FnMut(DocChunk) -> bool) {
2666            let (sections, _) = parse_sections_with_stack(markdown, Vec::new());
2667            for section in &sections {
2668                if !self.pack_section(section, sink) {
2669                    return;
2670                }
2671            }
2672        }
2673
2674        /// Slide the window over one completed section, feeding each chunk to
2675        /// `sink`. Returns `false` once the sink cancels — exposed so a
2676        /// streaming caller (docling-rag) can pack sections as they complete.
2677        pub fn pack_section(
2678            &self,
2679            section: &Section,
2680            sink: &mut dyn FnMut(DocChunk) -> bool,
2681        ) -> bool {
2682            let words = &section.words;
2683            if words.is_empty() {
2684                return true;
2685            }
2686            let budget = self.word_budget();
2687            let step = budget - self.overlap_words(budget); // ≥ 1 by construction
2688            let mut start = 0;
2689            loop {
2690                let end = (start + budget).min(words.len());
2691                let chunk = DocChunk {
2692                    text: words[start..end].join(" "),
2693                    headings: (!section.heading_path.is_empty())
2694                        .then(|| section.heading_path.clone()),
2695                    doc_items: Vec::new(),
2696                };
2697                if !sink(chunk) {
2698                    return false;
2699                }
2700                if end >= words.len() {
2701                    return true;
2702                }
2703                start += step;
2704            }
2705        }
2706
2707        /// Render a window chunk for embedding — docling-rag's rendering: the
2708        /// heading path as a `# Outer > Inner` context line, a blank line,
2709        /// then the body (just the body above any heading). Note this differs
2710        /// from the docling chunkers' [`contextualize`](super::contextualize),
2711        /// matching docling-rag instead.
2712        pub fn contextualize(chunk: &DocChunk) -> String {
2713            match &chunk.headings {
2714                Some(h) if !h.is_empty() => format!("# {}\n\n{}", h.join(" > "), chunk.text),
2715                _ => chunk.text.clone(),
2716            }
2717        }
2718    }
2719
2720    #[cfg(test)]
2721    mod tests {
2722        use super::*;
2723
2724        #[test]
2725        fn splits_on_headings_and_tracks_path() {
2726            let md = "\
2727intro words
2728# Chapter 1
2729para one
2730## Section 1.1
2731para two
2732# Chapter 2
2733para three";
2734            let secs = parse_sections(md);
2735            // pre-heading intro, Chapter 1, Section 1.1, Chapter 2.
2736            assert_eq!(secs.len(), 4);
2737            assert!(secs[0].heading_path.is_empty());
2738            assert_eq!(secs[1].heading_path, vec!["Chapter 1"]);
2739            assert_eq!(secs[2].heading_path, vec!["Chapter 1", "Section 1.1"]);
2740            // A deeper heading is dropped when we return to H1.
2741            assert_eq!(secs[3].heading_path, vec!["Chapter 2"]);
2742        }
2743
2744        #[test]
2745        fn strips_markup_to_plain_words() {
2746            let md = "# T\n\nSome **bold** and `code` and [a link](http://x).";
2747            let secs = parse_sections(md);
2748            let words = &secs[0].words;
2749            assert!(words.contains(&"bold".to_string()));
2750            assert!(words.contains(&"code".to_string()));
2751            assert!(words.contains(&"link".to_string()));
2752            // No markdown punctuation survives as its own token.
2753            assert!(!words.iter().any(|w| w.contains('*') || w.contains('`')));
2754        }
2755
2756        #[test]
2757        fn windows_overlap_and_never_cross_headings() {
2758            let body: Vec<String> = (0..25).map(|i| format!("w{i}")).collect();
2759            let md = format!("# A\n\n{}\n\n# B\n\nshort tail\n", body.join(" "));
2760            let chunker = WindowChunker::new(10, 0.2); // step 8, overlap 2
2761            let chunks = chunker.chunk(&md);
2762            // Section A: 25 words → windows [0..10), [8..18), [16..25).
2763            let a: Vec<_> = chunks
2764                .iter()
2765                .filter(|c| c.headings.as_deref() == Some(&["A".to_string()][..]))
2766                .collect();
2767            assert_eq!(a.len(), 3);
2768            assert!(a[0].text.starts_with("w0 ") && a[0].text.ends_with(" w9"));
2769            assert!(a[1].text.starts_with("w8 "), "overlap carries 2 words");
2770            assert!(a[2].text.ends_with(" w24"));
2771            // Section B stays its own chunk; nothing crosses the heading.
2772            let b: Vec<_> = chunks
2773                .iter()
2774                .filter(|c| c.headings.as_deref() == Some(&["B".to_string()][..]))
2775                .collect();
2776            assert_eq!(b.len(), 1);
2777            assert_eq!(b[0].text, "short tail");
2778            assert_eq!(WindowChunker::contextualize(b[0]), "# B\n\nshort tail");
2779        }
2780
2781        #[test]
2782        fn sink_false_cancels_the_window_walk() {
2783            let md = format!(
2784                "# A\n\n{}\n",
2785                (0..50)
2786                    .map(|i| format!("w{i}"))
2787                    .collect::<Vec<_>>()
2788                    .join(" ")
2789            );
2790            let chunker = WindowChunker::new(10, 0.0);
2791            let mut n = 0;
2792            chunker.chunk_with(&md, &mut |_| {
2793                n += 1;
2794                false
2795            });
2796            assert_eq!(n, 1);
2797        }
2798    }
2799}
2800
2801#[cfg(feature = "chunking")]
2802pub use window::{parse_sections, parse_sections_with_stack, Section, WindowChunker};
2803
2804#[cfg(test)]
2805mod tests {
2806    use super::*;
2807
2808    /// A whitespace "tokenizer" for algorithm tests.
2809    struct WordTok(usize);
2810    impl ChunkTokenizer for WordTok {
2811        fn count_tokens(&self, text: &str) -> usize {
2812            text.split_whitespace().count()
2813        }
2814        fn max_tokens(&self) -> usize {
2815            self.0
2816        }
2817    }
2818
2819    fn doc_with(nodes: Vec<Node>) -> DoclingDocument {
2820        let mut d = DoclingDocument::new("t");
2821        for n in nodes {
2822            d.push(n);
2823        }
2824        d
2825    }
2826
2827    #[test]
2828    fn hierarchical_headings_and_items() {
2829        let doc = doc_with(vec![
2830            Node::Heading {
2831                level: 1,
2832                text: "Title".into(),
2833            },
2834            Node::Paragraph {
2835                text: "Intro".into(),
2836            },
2837            Node::Heading {
2838                level: 2,
2839                text: "Sec".into(),
2840            },
2841            Node::Paragraph {
2842                text: "Body".into(),
2843            },
2844        ]);
2845        let chunks = HierarchicalChunker.chunk(&doc);
2846        assert_eq!(chunks.len(), 2);
2847        assert_eq!(chunks[0].text, "Intro");
2848        assert_eq!(chunks[0].headings.as_deref(), Some(&["Title".into()][..]));
2849        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/1");
2850        assert_eq!(
2851            chunks[1].headings.as_deref(),
2852            Some(&["Title".into(), "Sec".into()][..])
2853        );
2854        assert_eq!(contextualize(&chunks[1]), "Title\nSec\nBody");
2855    }
2856
2857    /// A page footer is a JSON text item (furniture layer) the chunker never
2858    /// chunks; the refs of the items after it still match the JSON.
2859    #[test]
2860    fn page_furniture_keeps_refs_aligned_with_json() {
2861        let doc = doc_with(vec![
2862            Node::Paragraph {
2863                text: "Before".into(),
2864            },
2865            Node::PageFurniture {
2866                footer: true,
2867                location: [0, 490, 100, 512],
2868                text: "1.10.2".into(),
2869            },
2870            Node::Paragraph {
2871                text: "After".into(),
2872            },
2873        ]);
2874        let chunks = HierarchicalChunker.chunk(&doc);
2875        assert_eq!(chunks.len(), 2);
2876        assert_eq!(chunks[1].text, "After");
2877        let json: serde_json::Value = serde_json::from_str(&doc.export_to_json()).unwrap();
2878        assert_eq!(json["texts"][2]["text"], "After");
2879        assert_eq!(chunks[1].doc_items[0].self_ref, "#/texts/2");
2880    }
2881
2882    /// #1041: a table's caption is the `#/texts/N` item the JSON writes
2883    /// ahead of the table — it opens the table's chunk (docling's
2884    /// `TripletTableSerializer`), and the text refs after it stay aligned.
2885    #[test]
2886    fn captioned_table_keeps_the_text_refs_aligned() {
2887        let table = Table {
2888            rows: vec![
2889                vec!["Year".into(), "Revenue".into()],
2890                vec!["2024".into(), "10".into()],
2891            ],
2892            caption: Some("Table 1: Revenue".into()),
2893            ..Table::default()
2894        };
2895        let doc = doc_with(vec![
2896            Node::Table(table.clone()),
2897            Node::Paragraph {
2898                text: "Revenue grew in 2024.".into(),
2899            },
2900            Node::Table(table),
2901            Node::Paragraph {
2902                text: "Costs were flat.".into(),
2903            },
2904        ]);
2905        let chunks = HierarchicalChunker.chunk(&doc);
2906        assert_eq!(chunks[0].text, "Table 1: Revenue\n\n2024, Revenue = 10");
2907        let refs: Vec<Vec<&str>> = chunks
2908            .iter()
2909            .map(|c| c.doc_items.iter().map(|i| i.self_ref.as_str()).collect())
2910            .collect();
2911        assert_eq!(
2912            refs,
2913            [
2914                vec!["#/texts/0", "#/tables/0"],
2915                vec!["#/texts/1"],
2916                vec!["#/texts/2", "#/tables/1"],
2917                vec!["#/texts/3"],
2918            ]
2919        );
2920        let json = doc.export_to_json_value();
2921        assert_eq!(json["texts"][1]["text"], "Revenue grew in 2024.");
2922        assert_eq!(json["texts"][3]["text"], "Costs were flat.");
2923    }
2924
2925    /// #1041: an item tree numbers the export by its own structure (a
2926    /// furniture title first, an inline paragraph as runs); the refs are
2927    /// mapped onto it, so each names the item its chunk was built from.
2928    #[test]
2929    fn refs_follow_an_item_tree() {
2930        use crate::tree::{ItemTree, TreeKind};
2931        let text = |label: &str, t: &str| TreeKind::Text {
2932            label: label.into(),
2933            text: t.into(),
2934            orig: None,
2935            formatting: None,
2936            hyperlink: None,
2937            level: None,
2938            list: None,
2939        };
2940        let mut doc = doc_with(vec![
2941            Node::Paragraph {
2942                text: "Lead **bold** tail".into(),
2943            },
2944            Node::Paragraph {
2945                text: "Second.".into(),
2946            },
2947        ]);
2948        let mut t = ItemTree {
2949            inline_whitespace: true,
2950            ..Default::default()
2951        };
2952        t.add(
2953            None,
2954            Some(crate::ContentLayer::Furniture),
2955            text("title", "Page"),
2956        );
2957        let g = t.add(
2958            None,
2959            None,
2960            TreeKind::Group {
2961                label: "inline".into(),
2962                name: "group".into(),
2963            },
2964        );
2965        t.add(Some(g), None, text("text", "Lead "));
2966        t.add(Some(g), None, text("text", "bold"));
2967        t.add(Some(g), None, text("text", " tail"));
2968        t.add(None, None, text("text", "Second."));
2969        doc.tree = Some(t);
2970        let refs: Vec<Vec<String>> = HierarchicalChunker
2971            .chunk(&doc)
2972            .iter()
2973            .map(|c| c.doc_items.iter().map(|i| i.self_ref.clone()).collect())
2974            .collect();
2975        assert_eq!(
2976            refs,
2977            [
2978                vec![
2979                    "#/texts/1".to_string(),
2980                    "#/texts/2".into(),
2981                    "#/texts/3".into()
2982                ],
2983                vec!["#/texts/4".to_string()],
2984            ]
2985        );
2986    }
2987
2988    /// A picture's children are never chunked, but they take `#/texts/N`
2989    /// (and list-group) slots in the JSON — the refs after them must still
2990    /// point at the right items.
2991    #[test]
2992    fn picture_children_are_not_chunked_but_keep_refs_aligned() {
2993        let doc = doc_with(vec![
2994            Node::Picture {
2995                caption: None,
2996                caption_href: None,
2997                image: None,
2998                classification: None,
2999                description: None,
3000                caption_parent: crate::CaptionParent::Item,
3001                caption_location: None,
3002            },
3003            Node::PictureChildren(vec![
3004                Node::Paragraph {
3005                    text: "axis label".into(),
3006                },
3007                Node::ListItem {
3008                    ordered: false,
3009                    number: 0,
3010                    first_in_list: true,
3011                    text: "callout".into(),
3012                    level: 0,
3013                    marker: None,
3014                    location: None,
3015                    split: None,
3016                    dclx: None,
3017                    href: None,
3018                    layer: None,
3019                },
3020            ]),
3021            Node::Paragraph {
3022                text: "Body".into(),
3023            },
3024        ]);
3025        let chunks = HierarchicalChunker.chunk(&doc);
3026        assert_eq!(chunks.len(), 1);
3027        assert_eq!(chunks[0].text, "Body");
3028        let json = doc.export_to_json_value();
3029        assert_eq!(json["texts"][2]["text"], "Body");
3030        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3031    }
3032
3033    #[test]
3034    fn heading_shadowing_prunes_deeper_levels() {
3035        let doc = doc_with(vec![
3036            Node::Heading {
3037                level: 2,
3038                text: "A".into(),
3039            },
3040            Node::Heading {
3041                level: 3,
3042                text: "A.1".into(),
3043            },
3044            Node::Heading {
3045                level: 2,
3046                text: "B".into(),
3047            },
3048            Node::Paragraph { text: "p".into() },
3049        ]);
3050        let chunks = HierarchicalChunker.chunk(&doc);
3051        assert_eq!(chunks[0].headings.as_deref(), Some(&["B".into()][..]));
3052    }
3053
3054    /// #1012 (docling-core#924, `test_rich_heading_chunk_metadata`): a
3055    /// partially formatted heading — an empty heading over an inline group
3056    /// in docling — is the heading context of the body, not a chunk of its
3057    /// own under an empty heading.
3058    #[test]
3059    fn rich_heading_is_the_heading_context() {
3060        for body in [Some("Body."), None] {
3061            let mut nodes = vec![Node::Heading {
3062                level: 1,
3063                text: "Hello **bold** world".into(),
3064            }];
3065            if let Some(b) = body {
3066                nodes.push(Node::Paragraph { text: b.into() });
3067            }
3068            let doc = doc_with(nodes);
3069            for chunks in [
3070                HierarchicalChunker.chunk(&doc),
3071                HybridChunker::new(WordTok(64)).chunk(&doc),
3072            ] {
3073                let got: Vec<_> = chunks
3074                    .iter()
3075                    .map(|c| (c.text.as_str(), c.headings.clone()))
3076                    .collect();
3077                let want: Vec<_> = body
3078                    .map(|b| (b, Some(vec!["Hello **bold** world".to_string()])))
3079                    .into_iter()
3080                    .collect();
3081                assert_eq!(got, want);
3082            }
3083        }
3084    }
3085
3086    /// #1012 (docling-core#924,
3087    /// `test_rich_heading_is_emitted_before_a_sibling_heading`): a rich
3088    /// heading shadowed by a sibling leaves no chunk, and the sibling's body
3089    /// carries only the sibling.
3090    #[test]
3091    fn rich_heading_shadowed_by_a_sibling() {
3092        let doc = doc_with(vec![
3093            Node::Heading {
3094                level: 1,
3095                text: "Energy *E* here".into(),
3096            },
3097            Node::Heading {
3098                level: 1,
3099                text: "Next".into(),
3100            },
3101            Node::Paragraph {
3102                text: "Body.".into(),
3103            },
3104        ]);
3105        let chunks = HierarchicalChunker.chunk(&doc);
3106        assert_eq!(chunks.len(), 1);
3107        assert_eq!(chunks[0].text, "Body.");
3108        assert_eq!(chunks[0].headings.as_deref(), Some(&["Next".into()][..]));
3109        assert_eq!(chunks[0].doc_items[0].self_ref, "#/texts/2");
3110    }
3111
3112    /// docling.rs#987 (docling-core#690): table pieces are budgeted at the
3113    /// window minus the heading path, so `contextualize()` stays in budget.
3114    #[test]
3115    fn split_table_pieces_fit_with_headings() {
3116        let rows: Vec<Vec<String>> = std::iter::once(vec!["".to_string(), "A".into(), "B".into()])
3117            .chain((0..40).map(|i| vec![format!("R{i}"), format!("{i}"), format!("v{i}")]))
3118            .collect();
3119        let doc = doc_with(vec![
3120            Node::Heading {
3121                level: 1,
3122                text: "one two three four five six".into(),
3123            },
3124            Node::Table(Table {
3125                rows,
3126                ..Default::default()
3127            }),
3128        ]);
3129        let h = HybridChunker::new(WordTok(20));
3130        let chunks = h.chunk(&doc);
3131        assert!(chunks.len() > 1);
3132        for c in &chunks {
3133            assert!(
3134                h.count_chunk_tokens(c) <= 20,
3135                "over budget: {}",
3136                h.count_chunk_tokens(c)
3137            );
3138        }
3139    }
3140
3141    #[test]
3142    fn triplet_table() {
3143        let t = Table {
3144            rows: vec![
3145                vec!["".into(), "Col1".into()],
3146                vec!["Row1".into(), "v".into()],
3147            ],
3148            ..Default::default()
3149        };
3150        assert_eq!(triplet_table_text(&t), "Row1, Col1 = v");
3151        // Single-column: row 0 is the dataframe header, the first data row
3152        // becomes the column name, the rest the values.
3153        let single = Table {
3154            rows: vec![vec!["H".into()], vec!["a".into()], vec!["b".into()]],
3155            ..Default::default()
3156        };
3157        assert_eq!(triplet_table_text(&single), "a = b");
3158    }
3159
3160    /// The peer merge before docling-core#823 (#782): rebuild and re-count
3161    /// the whole window for every chunk. The linear merge must give the
3162    /// same chunks.
3163    fn quadratic_merge<T: ChunkTokenizer>(
3164        h: &HybridChunker<T>,
3165        chunks: Vec<DocChunk>,
3166    ) -> Vec<DocChunk> {
3167        let mut out = Vec::new();
3168        let mut window: Vec<DocChunk> = Vec::new();
3169        let flush = |window: &mut Vec<DocChunk>, out: &mut Vec<DocChunk>| match window.len() {
3170            0 => {}
3171            1 => out.push(window.pop().unwrap()),
3172            _ => {
3173                out.push(merged_chunk(window.iter()));
3174                window.clear();
3175            }
3176        };
3177        for chunk in chunks {
3178            if window.is_empty() {
3179                window.push(chunk);
3180                continue;
3181            }
3182            let candidate = merged_chunk(window.iter().chain([&chunk]));
3183            if chunk.headings == window[0].headings
3184                && h.count_chunk_tokens(&candidate) <= h.max_tokens()
3185            {
3186                window.push(chunk);
3187            } else {
3188                flush(&mut window, &mut out);
3189                window.push(chunk);
3190            }
3191        }
3192        flush(&mut window, &mut out);
3193        out
3194    }
3195
3196    fn linear_merge<T: ChunkTokenizer>(
3197        h: &HybridChunker<T>,
3198        chunks: Vec<DocChunk>,
3199    ) -> Vec<DocChunk> {
3200        let mut out = Vec::new();
3201        let mut sink = |c| {
3202            out.push(c);
3203            true
3204        };
3205        let mut m = PeerMerger::default();
3206        for c in chunks {
3207            assert!(h.merge_push(&mut m, c, &mut sink));
3208        }
3209        assert!(h.merge_flush(&mut m, &mut sink));
3210        out
3211    }
3212
3213    /// A non-additive "tokenizer": a token per started 4 characters, so the
3214    /// joined text counts differently from the sum of its parts and the
3215    /// delimiter's measured cost is negative — the running estimate is
3216    /// re-anchored and the final window shrunk back.
3217    struct QuadCharTok(usize);
3218    impl ChunkTokenizer for QuadCharTok {
3219        fn count_tokens(&self, text: &str) -> usize {
3220            text.chars().count().div_ceil(4)
3221        }
3222        fn max_tokens(&self) -> usize {
3223            self.0
3224        }
3225    }
3226
3227    /// Pseudo-random chunks: short texts of 1–12 words under one of three
3228    /// heading paths (runs of equal headings, as the walk yields them).
3229    fn random_chunks(seed: u64, n: usize) -> Vec<DocChunk> {
3230        let mut state = seed;
3231        let mut next = move |m: u64| {
3232            state = state
3233                .wrapping_mul(6364136223846793005)
3234                .wrapping_add(1442695040888963407);
3235            (state >> 33) % m
3236        };
3237        let headings = [
3238            None,
3239            Some(vec!["A".to_string()]),
3240            Some(vec!["A".into(), "B".into()]),
3241        ];
3242        let mut current = 0;
3243        (0..n)
3244            .map(|i| {
3245                if next(4) == 0 {
3246                    current = next(3) as usize;
3247                }
3248                let words = 1 + next(12) as usize;
3249                let text = (0..words)
3250                    .map(|w| ["x", "lorem", "ipsum", "dolor", "sit"][(w + i) % 5])
3251                    .collect::<Vec<_>>()
3252                    .join(" ");
3253                DocChunk {
3254                    text,
3255                    headings: headings[current].clone(),
3256                    doc_items: vec![ChunkItem {
3257                        self_ref: format!("#/texts/{i}"),
3258                        kind: ChunkItemKind::Text,
3259                        text: String::new(),
3260                    }],
3261                }
3262            })
3263            .collect()
3264    }
3265
3266    /// #782 (docling-core#823): the linear peer merge gives exactly the
3267    /// chunks of the quadratic one, with an additive and a non-additive
3268    /// tokenizer, over many budgets.
3269    #[test]
3270    fn linear_peer_merge_matches_the_quadratic_one() {
3271        for seed in 0..40 {
3272            let chunks = random_chunks(seed, 60);
3273            for max in [3, 8, 16, 40, 200] {
3274                let h = HybridChunker::new(WordTok(max));
3275                assert_eq!(
3276                    linear_merge(&h, chunks.clone()),
3277                    quadratic_merge(&h, chunks.clone()),
3278                    "words, seed {seed}, max {max}"
3279                );
3280                let h = HybridChunker::new(QuadCharTok(max));
3281                assert_eq!(
3282                    linear_merge(&h, chunks.clone()),
3283                    quadratic_merge(&h, chunks.clone()),
3284                    "chars/4, seed {seed}, max {max}"
3285                );
3286            }
3287        }
3288    }
3289
3290    /// 10k tiny paragraphs at an 8192-token budget — docling-core#823's
3291    /// benchmark. `cargo test -p docling-core --release -- --ignored
3292    /// peer_merge_bench --nocapture` prints both timings.
3293    #[test]
3294    #[ignore]
3295    fn peer_merge_bench() {
3296        let chunks: Vec<DocChunk> = (0..10_000)
3297            .map(|i| DocChunk {
3298                text: format!("Paragraph number {i} is short."),
3299                headings: Some(vec!["Section".into()]),
3300                doc_items: Vec::new(),
3301            })
3302            .collect();
3303        let h = HybridChunker::new(WordTok(8192));
3304        let t = std::time::Instant::now();
3305        let fast = linear_merge(&h, chunks.clone());
3306        let linear = t.elapsed();
3307        let t = std::time::Instant::now();
3308        let slow = quadratic_merge(&h, chunks);
3309        let quadratic = t.elapsed();
3310        assert_eq!(fast, slow);
3311        println!(
3312            "linear {linear:?}, quadratic {quadratic:?}, {} chunks",
3313            fast.len()
3314        );
3315    }
3316
3317    /// A table from first-class cells `(text, row, col, row_span,
3318    /// column_header)`, its grid repeating a spanning cell's text.
3319    fn cell_table(
3320        num_rows: usize,
3321        num_cols: usize,
3322        cells: &[(&str, usize, usize, usize, bool)],
3323    ) -> Table {
3324        let mut rows = vec![vec![String::new(); num_cols]; num_rows];
3325        for &(text, r, c, span, _) in cells {
3326            for row in rows.iter_mut().skip(r).take(span) {
3327                row[c] = text.into();
3328            }
3329        }
3330        Table {
3331            rows,
3332            cells: Some(
3333                cells
3334                    .iter()
3335                    .map(|&(text, r, c, span, ched)| crate::TableCell {
3336                        text: text.into(),
3337                        bbox: None,
3338                        start_row: r,
3339                        start_col: c,
3340                        row_span: span,
3341                        col_span: 1,
3342                        column_header: ched,
3343                        row_header: false,
3344                        row_section: false,
3345                    })
3346                    .collect(),
3347            ),
3348            ..Default::default()
3349        }
3350    }
3351
3352    /// #778 (docling-core#767, 2.102): the Markdown table and the triplet
3353    /// chunk agree on the header rows — upstream's parametrized
3354    /// `test_table_header_rows_in_markdown_and_dataframe`, plus the issue's
3355    /// two tables. Expected texts are docling-core 2.102.0's (compact
3356    /// Markdown, `HierarchicalChunker` chunk text).
3357    #[test]
3358    fn markdown_and_triplets_share_the_header_rows() {
3359        type Case<'a> = (
3360            &'a str,
3361            usize,
3362            usize,
3363            Vec<(&'a str, usize, usize, usize, bool)>,
3364            &'a str,
3365            &'a str,
3366        );
3367        let cases: Vec<Case> = vec![
3368            (
3369                "rows under a row-spanning header stay in the body",
3370                2,
3371                2,
3372                vec![("Price", 0, 0, 1, true), ("Category", 0, 1, 2, true), ("10.00", 1, 0, 1, false)],
3373                "| Price | Category |\n| - | - |\n| 10.00 | Category |",
3374                "10.00, Category = Category",
3375            ),
3376            (
3377                "a row header flagged as column header stays in the body",
3378                3,
3379                3,
3380                vec![
3381                    ("Year", 0, 0, 1, true),
3382                    ("Month", 0, 1, 1, true),
3383                    ("Revenue", 0, 2, 1, true),
3384                    ("2025", 1, 0, 2, true),
3385                    ("January", 1, 1, 1, false),
3386                    ("$134", 1, 2, 1, false),
3387                    ("February", 2, 1, 1, false),
3388                    ("$150", 2, 2, 1, false),
3389                ],
3390                "| Year | Month | Revenue |\n| - | - | - |\n| 2025 | January | $134 |\n| 2025 | February | $150 |",
3391                "2025, Month = January. 2025, Revenue = $134. 2025, Month = February. 2025, Revenue = $150",
3392            ),
3393            (
3394                "stacked header with an unmarked row label",
3395                3,
3396                3,
3397                vec![
3398                    ("", 0, 0, 1, true),
3399                    ("% of Total", 0, 1, 1, true),
3400                    ("% of Total", 0, 2, 1, true),
3401                    ("class label", 1, 0, 1, false),
3402                    ("Train", 1, 1, 1, true),
3403                    ("Test", 1, 2, 1, true),
3404                    ("Caption", 2, 0, 1, false),
3405                    ("2.5", 2, 1, 1, false),
3406                    ("2.4", 2, 2, 1, false),
3407                ],
3408                "| class label | % of Total - Train | % of Total - Test |\n| - | - | - |\n| Caption | 2.5 | 2.4 |",
3409                "Caption, % of Total.Train = 2.5. Caption, % of Total.Test = 2.4",
3410            ),
3411            (
3412                "a partially flagged first row stays the header",
3413                2,
3414                2,
3415                vec![("Name", 0, 0, 1, true), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3416                "| Name | Value |\n| - | - |\n| A | 1 |",
3417                "A, Value = 1",
3418            ),
3419            (
3420                "no flags: Markdown promotes row 0, triplets do not",
3421                2,
3422                2,
3423                vec![("Name", 0, 0, 1, false), ("Value", 0, 1, 1, false), ("A", 1, 0, 1, false), ("1", 1, 1, 1, false)],
3424                "| Name | Value |\n| - | - |\n| A | 1 |",
3425                "Name, 1 = Value. A, 1 = 1",
3426            ),
3427            (
3428                "row headers flagged as column headers stay in the body",
3429                2,
3430                2,
3431                vec![("2025", 0, 0, 1, true), ("$134", 0, 1, 1, false), ("2026", 1, 0, 1, true), ("$150", 1, 1, 1, false)],
3432                "|  |  |\n| - | - |\n| 2025 | $134 |\n| 2026 | $150 |",
3433                "2025, 1 = $134. 2026, 1 = $150",
3434            ),
3435            (
3436                "a form with flagged first-column labels is all data",
3437                3,
3438                2,
3439                vec![
3440                    ("Name", 0, 0, 1, true),
3441                    ("Bob", 0, 1, 1, false),
3442                    ("Age", 1, 0, 1, true),
3443                    ("42", 1, 1, 1, false),
3444                    ("City", 2, 0, 1, true),
3445                    ("Paris", 2, 1, 1, false),
3446                ],
3447                "|  |  |\n| - | - |\n| Name | Bob |\n| Age | 42 |\n| City | Paris |",
3448                "Name, 1 = Bob. Age, 1 = 42. City, 1 = Paris",
3449            ),
3450            (
3451                "a partly flagged row 0 above a stacked header row",
3452                3,
3453                3,
3454                vec![
3455                    ("Region", 0, 0, 1, true),
3456                    ("2025", 0, 1, 1, false),
3457                    ("", 0, 2, 1, false),
3458                    ("", 1, 0, 1, false),
3459                    ("Q1", 1, 1, 1, true),
3460                    ("Q2", 1, 2, 1, true),
3461                    ("North", 2, 0, 1, false),
3462                    ("1", 2, 1, 1, false),
3463                    ("2", 2, 2, 1, false),
3464                ],
3465                "| Region | 2025 - Q1 | Q2 |\n| - | - | - |\n| North | 1 | 2 |",
3466                "North, 2025.Q1 = 1. North, Q2 = 2",
3467            ),
3468        ];
3469        for (name, rows, cols, cells, md, triplets) in cases {
3470            let t = cell_table(rows, cols, &cells);
3471            assert_eq!(
3472                crate::markdown::render_table(&t, true),
3473                md,
3474                "{name}: markdown"
3475            );
3476            assert_eq!(triplet_table_text(&t), triplets, "{name}: triplets");
3477        }
3478    }
3479
3480    /// #777 (docling-core#857, 2.102): a rich header cell spanning two
3481    /// columns repeats in both — upstream's `col_span_rich_table_doc`. Its
3482    /// blocks sit on the anchor only and the covered position's flat text is
3483    /// blank, so LaTeX and the triplets must resolve the anchor themselves.
3484    #[test]
3485    fn a_column_spanning_rich_cell_repeats_in_every_column() {
3486        let mut t = cell_table(
3487            2,
3488            3,
3489            &[
3490                ("", 0, 0, 1, true),
3491                ("Partner", 0, 1, 1, true),
3492                ("Status", 1, 0, 1, false),
3493                ("Done", 1, 1, 1, false),
3494                ("Open", 1, 2, 1, false),
3495            ],
3496        );
3497        if let Some(cells) = t.cells.as_mut() {
3498            cells[1].col_span = 2;
3499        }
3500        let mut blocks = vec![vec![Vec::new(); 3]; 2];
3501        blocks[0][1] = vec![Node::Paragraph {
3502            text: "Partner".into(),
3503        }];
3504        t.cell_blocks = Some(blocks);
3505        assert_eq!(
3506            t.rows[0][2], "",
3507            "the covered position carries no text of its own"
3508        );
3509        assert_eq!(
3510            triplet_table_text(&t),
3511            "Status, Partner = Done. Status, Partner = Open"
3512        );
3513        let latex = crate::latex::render_table(&t);
3514        assert!(
3515            latex.contains(" & Partner & Partner \\\\ \\hline\nStatus & Done & Open \\\\ \\hline"),
3516            "{latex}"
3517        );
3518        // Markdown reads the flat text, which the backends now fill.
3519        t.rows[0][2] = "Partner".into();
3520        assert_eq!(
3521            crate::markdown::render_table(&t, true),
3522            "|  | Partner | Partner |\n| - | - | - |\n| Status | Done | Open |"
3523        );
3524    }
3525
3526    #[test]
3527    fn hybrid_merges_small_peers_and_splits_large() {
3528        let doc = doc_with(vec![
3529            Node::Heading {
3530                level: 2,
3531                text: "S".into(),
3532            },
3533            Node::Paragraph { text: "a b".into() },
3534            Node::Paragraph { text: "c d".into() },
3535        ]);
3536        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3537        assert_eq!(chunks.len(), 1, "peers under one heading merge");
3538        assert_eq!(chunks[0].text, "a b\nc d");
3539
3540        let long = "w ".repeat(40).trim().to_string();
3541        let doc = doc_with(vec![Node::Paragraph { text: long }]);
3542        let chunks = HybridChunker::new(WordTok(16)).chunk(&doc);
3543        assert!(chunks.len() > 1, "oversized paragraph splits");
3544        for c in &chunks {
3545            assert!(WordTok(16).count_tokens(&contextualize(c)) <= 16);
3546        }
3547    }
3548
3549    #[test]
3550    fn semchunk_prefers_newlines_then_sentences() {
3551        let tok = WordTok(4);
3552        let out = semchunk("one two three. four five six\nseven eight", 4, &tok);
3553        assert!(out.iter().all(|c| tok.count_tokens(c) <= 4), "{out:?}");
3554    }
3555
3556    /// #1065: a literal `$` in running text (prices) is not an inline-formula
3557    /// delimiter — the paragraph stays one item, its text verbatim.
3558    #[test]
3559    fn dollar_amounts_are_not_inline_formulas() {
3560        for text in [
3561            "costs $5 and $0.25",
3562            "a bet of $5 riding on the game. The player has just won $6 on the game.",
3563            "pay $10, get $ 3 back",
3564        ] {
3565            assert_eq!(
3566                inline_segments(text),
3567                vec![text.to_string()],
3568                "{text:?} was split"
3569            );
3570            let doc = doc_with(vec![Node::Paragraph { text: text.into() }]);
3571            let chunks = HierarchicalChunker.chunk(&doc);
3572            assert_eq!(chunks.len(), 1);
3573            assert_eq!(chunks[0].text, text);
3574            assert_eq!(chunks[0].doc_items.len(), 1);
3575            assert_eq!(chunks[0].doc_items[0].text, text);
3576        }
3577    }
3578
3579    /// Real inline formulas keep their own item, re-wrapped as `$$…$$`.
3580    #[test]
3581    fn dollar_math_inline_formulas_still_split() {
3582        assert_eq!(
3583            inline_segments("where $E=mc^2$ holds"),
3584            vec!["where", "$$E=mc^2$$", "holds"]
3585        );
3586        assert_eq!(inline_segments("$x$"), vec!["$$x$$"]);
3587    }
3588
3589    /// With structured runs, only a `formula` run's LaTeX is a formula — a
3590    /// price next to a real equation stays plain text.
3591    #[test]
3592    fn formula_runs_decide_inline_formulas() {
3593        let runs = vec![
3594            crate::InlineRun {
3595                text: "costs $5, and".into(),
3596                ..Default::default()
3597            },
3598            crate::InlineRun {
3599                text: "x + 1".into(),
3600                formula: true,
3601                ..Default::default()
3602            },
3603            crate::InlineRun {
3604                text: "is $6".into(),
3605                ..Default::default()
3606            },
3607        ];
3608        let segs: Vec<String> = inline_segments_tagged("costs $5, and $x + 1$ is $6", &runs)
3609            .into_iter()
3610            .map(|(t, _)| t)
3611            .collect();
3612        assert_eq!(segs, vec!["costs $5, and", "$$x + 1$$", "is $6"]);
3613    }
3614}