Skip to main content

docling_pdf/
dp_lines.rs

1//! Port of docling-parse's line-cell sanitizer
2//! (`src/parse/page_item_sanitators/cells.h` → `create_line_cells` /
3//! `contract_cells_into_lines_v1`). It merges per-glyph char cells into line
4//! cells via a 3-pass contraction — left-to-right, right-to-left, then
5//! left-to-right with reverse — using corner-distance adjacency and inserting at
6//! most one space per merge. This reproduces docling-parse's inter-word spacing
7//! (justified double spaces, the space before a `:`, and RTL ordering) that an
8//! ad-hoc gap-heuristic reconstruction can't.
9//!
10//! Geometry uses native PDF coordinates (y increases upward); each cell carries
11//! its four transformed corners r0=bottom-left, r1=bottom-right, r2=top-right,
12//! r3=top-left, exactly like `page_cell.h`.
13
14use std::collections::HashMap;
15
16use crate::pdfium_backend::{Glyph, TextCell};
17
18// config.h: the factors that actually bind for line cells.
19const MERGE: f64 = 1.0; // line_space_width_factor_for_merge (adjacency gate)
20const MERGE_WITH_SPACE: f64 = 0.33; // line_space_width_factor_for_merge_with_space
21
22// create_word_cells: words contract under their own, tighter factors — the
23// adjacency gate is word_space_width_factor_for_merge (0.33) and the space
24// threshold is twice that (2.0 * 0.33), which the 0.33 gate can never exceed,
25// so a word cell never contains an inserted space. Space glyphs are hard
26// word-boundary barriers during the contraction (`applicable`'s
27// `block_spaces`) and are erased only afterwards, as docling-parse does.
28const WORD_MERGE: f64 = 0.33; // word_space_width_factor_for_merge
29const WORD_MERGE_WITH_SPACE: f64 = 2.0 * WORD_MERGE;
30const H_TOL: f64 = 1.0; // horizontal_cell_tolerance (ligature eps_d1 relaxation)
31
32#[derive(Clone)]
33struct Cell {
34    text: String,
35    rx0: f64,
36    ry0: f64, // bottom-left
37    rx1: f64,
38    ry1: f64, // bottom-right
39    rx2: f64,
40    ry2: f64, // top-right
41    rx3: f64,
42    ry3: f64, // top-left
43    ltr: bool,
44    active: bool,
45    lig_carry: bool, // last_merged_cell_was_ligature
46    font: u64,       // hash of docling-parse's font name (for enforce_same_font)
47    // Cached invariants of `text` / the quad, maintained by `build_cells` and
48    // `merge_with`. The contraction is quadratic in merge attempts, and
49    // recomputing these per attempt (trim/char-count/ligature scans over the
50    // *growing* line text, min/max over the quad) dominated large-page
51    // parsing — the caches turn every attempt into flag reads.
52    blank: bool,   // text.trim().is_empty()
53    lig: bool,     // is_ligature(&text)
54    fb: bool,      // any char in U+FB00..=U+FB06 (the range half of is_ligature)
55    nchars: usize, // text.chars().count()
56    b_l: f64,      // bounds(): axis-aligned quad extremes
57    b_r: f64,
58    b_b: f64,
59    b_t: f64,
60    /// The pen's origin and the font size, `[x, y, size]` ([`Glyph::pen`]),
61    /// for the word contraction's baseline test (#921).
62    pen: Option<[f64; 3]>,
63    /// The glyph's font is a math face ([`Glyph::math_font`]).
64    math_font: bool,
65    /// Letter-spaced from the glyph before it ([`Glyph::spaced`]).
66    spaced: bool,
67    /// The clip box in force ([`Glyph::clip`]); a contracted cell keeps it
68    /// only while all its glyphs share it.
69    clip: Option<[f64; 4]>,
70    /// The first glyph's full-precision quad hash ([`Glyph::exact`]).
71    exact: u64,
72}
73
74impl Cell {
75    /// Length of the bottom edge (baseline advance) — `page_cell.h::length`.
76    fn length(&self) -> f64 {
77        ((self.rx1 - self.rx0).powi(2) + (self.ry1 - self.ry0).powi(2)).sqrt()
78    }
79
80    /// Running mean glyph advance over the whole accumulated cell.
81    fn avg_char_width(&self) -> f64 {
82        if self.nchars > 0 {
83            self.length() / self.nchars as f64
84        } else {
85            0.0
86        }
87    }
88
89    /// Distance from this cell's bottom-right corner to `other`'s bottom-left.
90    fn gap(&self, other: &Cell) -> f64 {
91        ((self.rx1 - other.rx0).powi(2) + (self.ry1 - other.ry0).powi(2)).sqrt()
92    }
93
94    /// `is_adjacent_to`: both the bottom-corner gap (`< eps0`) and the top-corner
95    /// gap (`< eps1`) must be small. The vertical component keeps different
96    /// baselines/lines from merging.
97    fn adjacent(&self, other: &Cell, eps0: f64, eps1: f64) -> bool {
98        let d0 = self.gap(other);
99        let d1 = ((self.rx2 - other.rx3).powi(2) + (self.ry2 - other.ry3).powi(2)).sqrt();
100        d0 < eps0 && d1 < eps1
101    }
102
103    /// Punctuation/space cells are bidi-neutral bridges.
104    fn same_orientation(&self, other: &Cell) -> bool {
105        self.ltr == other.ltr || is_punct_or_space(&self.text) || is_punct_or_space(&other.text)
106    }
107
108    /// `merge_with`: absorb `other` (which lies to this cell's right). Insert at
109    /// most one separator space when the gap exceeds `delta`. RTL prepends.
110    ///
111    /// `euclidean` picks the gap measure: docling-parse uses the **Euclidean
112    /// corner distance** `d0` (the same one `is_adjacent_to` uses). The pure-Rust
113    /// parser produces clean advance boxes, so it uses `d0` to match docling
114    /// byte-for-byte. pdfium's loose boxes overhang (an `f` extends left and
115    /// overlaps its neighbour), which a Euclidean distance reads as a false
116    /// positive gap and over-inserts spaces (`Self` → `Sel f`); that path keeps
117    /// the **signed horizontal gap** instead.
118    fn merge_with(&mut self, other: &Cell, delta: f64, euclidean: bool) {
119        let gap = if euclidean {
120            self.gap(other)
121        } else {
122            other.rx0 - self.rx1
123        };
124        let space = delta < gap;
125        if !self.ltr || !other.ltr {
126            if space {
127                self.text.insert(0, ' ');
128            }
129            self.text = format!("{}{}", other.text, self.text);
130            self.ltr = false;
131        } else {
132            if space {
133                self.text.push(' ');
134            }
135            self.text.push_str(&other.text);
136            self.ltr = true;
137        }
138        if clips_differ(self.clip, other.clip) {
139            self.clip = None;
140        }
141        // Extend the right edge to `other`.
142        self.rx1 = other.rx1;
143        self.ry1 = other.ry1;
144        self.rx2 = other.rx2;
145        self.ry2 = other.ry2;
146        // Cache upkeep. Blankness and the ligature char-range scan distribute
147        // over concatenation (the inserted separator is whitespace and not in
148        // the range); the equality patterns ("ff", "fi", …) do NOT — "fi" is a
149        // ligature cell, "fiction" is not — so a short merged text recomputes
150        // exactly and a longer one (which no equality pattern can match) falls
151        // back to the distributed range flag alone.
152        self.blank = self.blank && other.blank;
153        self.nchars += other.nchars + usize::from(space);
154        self.fb = self.fb || other.fb;
155        self.lig = if self.text.len() <= 3 {
156            is_ligature(&self.text)
157        } else {
158            self.fb
159        };
160        let (l, r, b, t) = quad_bounds(self);
161        self.b_l = l;
162        self.b_r = r;
163        self.b_b = b;
164        self.b_t = t;
165    }
166}
167
168/// Axis-aligned bounds of a cell's quad, `(l, r, b, t)` in PDF points (y-up),
169/// from the cache `merge_with` maintains.
170fn bounds(c: &Cell) -> (f64, f64, f64, f64) {
171    (c.b_l, c.b_r, c.b_b, c.b_t)
172}
173
174/// The cached bounds' source of truth: min/max over the quad corners.
175fn quad_bounds(c: &Cell) -> (f64, f64, f64, f64) {
176    let xs = [c.rx0, c.rx1, c.rx2, c.rx3];
177    let ys = [c.ry0, c.ry1, c.ry2, c.ry3];
178    let fold = |it: &[f64], f: fn(f64, f64) -> f64| it.iter().copied().reduce(f).unwrap();
179    (
180        fold(&xs, f64::min),
181        fold(&xs, f64::max),
182        fold(&ys, f64::min),
183        fold(&ys, f64::max),
184    )
185}
186
187/// Is another active cell painted inside the horizontal gap between `i` and
188/// `j`? The contraction walks cells in **stream** order, and a generator that
189/// draws a line's bold runs after its regular text leaves them as later cells
190/// — the space tolerance would then stitch `C.[ ]Zur Wahrung …` straight
191/// across the hole where the bold `6.` sits, and the stranded token ends up at
192/// the line's end ("… wenn Sie die Mitteilung 6."). An occupied gap is not a
193/// gap. Space-only cells never block (they *are* the gap), and the scan is
194/// skipped entirely for glyph-adjacent merges (no room for anything).
195fn gap_occupied(cells: &[Cell], i: usize, j: usize) -> bool {
196    let (al, ar, ab, at) = bounds(&cells[i]);
197    let (bl, br, bb, bt) = bounds(&cells[j]);
198    let (gl, gr) = if ar <= bl { (ar, bl) } else { (br, al) };
199    if gr - gl < 0.5 {
200        return false; // touching or overlapping — nothing fits in between
201    }
202    let (band_b, band_t) = (ab.min(bb), at.max(bt));
203    cells.iter().enumerate().any(|(k, c)| {
204        if k == i || k == j || !c.active || c.blank {
205            return false;
206        }
207        let (cl, cr, cb, ct) = bounds(c);
208        // Vertically on this line: most of the candidate inside the pair's band.
209        let overlap = (ct.min(band_t) - cb.max(band_b)).max(0.0);
210        overlap > 0.5 * (ct - cb).max(f64::EPSILON)
211            // Horizontally: real ink inside the gap interval.
212            && cr.min(gr) - cl.max(gl) > 0.1
213    })
214}
215
216/// `applicable_for_merge`: both active and same reading orientation. A different
217/// font normally blocks the merge (keeps a bold label and its value as separate
218/// line cells). On the clean-box parser path, **punctuation/space cells bridge
219/// fonts** so a sentence period set in a separate punctuation font joins its word
220/// instead of fragmenting (`العمل .` → `العمل.`); letters still enforce the font.
221fn applicable(a: &Cell, b: &Cell, parser: bool, block_spaces: bool) -> bool {
222    if !a.active || !b.active {
223        return false;
224    }
225    // Word mode (`block_spaces`): a space glyph is a hard word-boundary barrier
226    // that never merges in either direction; the space cells themselves are
227    // erased after the contraction (`create_word_cells`).
228    if block_spaces && (is_all_space(&a.text) || is_all_space(&b.text)) {
229        return false;
230    }
231    // A lone punctuation glyph (not a space) set in a separate punctuation font
232    // bridges fonts so it joins its word — but only next to RTL text. In LTR a
233    // different-font punctuation (e.g. a bold `:`) is a real run boundary docling
234    // keeps spaced (`Laboratories :`); in Arabic the sentence period sits in a
235    // Latin punctuation font yet attaches (`العمل.`). Parser path only.
236    let lone_punct = |s: &str| {
237        let mut ch = s.chars();
238        matches!(ch.next(), Some(c) if c != ' ' && is_punct_or_space(&c.to_string()))
239            && ch.next().is_none()
240    };
241    let punct_bridge =
242        parser && ((lone_punct(&a.text) && !b.ltr) || (lone_punct(&b.text) && !a.ltr));
243    let font_neutral = a.lig || b.lig || punct_bridge;
244    if a.font != 0 && b.font != 0 && a.font != b.font && !font_neutral {
245        return false;
246    }
247    a.same_orientation(b)
248}
249
250/// Left-to-right pass: `i` ascending accumulates cells to its right.
251fn pass_ltr(cells: &mut [Cell], allow_reverse: bool, euclidean: bool, p: Factors) {
252    for i in 0..cells.len() {
253        if !cells[i].active {
254            continue;
255        }
256        let mut j = i + 1;
257        while j < cells.len() {
258            if !applicable(&cells[i], &cells[j], euclidean, p.block_spaces) {
259                break;
260            }
261            let i_lig = cells[i].lig || cells[i].lig_carry;
262            let j_lig = cells[j].lig || cells[j].lig_carry;
263            let d0 = cells[i].avg_char_width() * p.merge;
264            let d1 = cells[i].avg_char_width() * p.merge_with_space;
265            let adj_d1 = d0 + if i_lig || j_lig { H_TOL } else { 0.0 };
266            if cells[i].adjacent(&cells[j], d0, adj_d1) && !gap_occupied(cells, i, j) {
267                let other = cells[j].clone();
268                cells[i].merge_with(&other, d1, euclidean);
269                cells[i].lig_carry = other.lig;
270                cells[j].active = false;
271                j += 1; // i keeps absorbing the next cell to its right
272            } else if allow_reverse
273                && cells[j].adjacent(&cells[i], d0, adj_d1)
274                && !gap_occupied(cells, j, i)
275            {
276                let other = cells[i].clone();
277                cells[j].merge_with(&other, d1, euclidean);
278                cells[j].lig_carry = other.lig;
279                cells[i].active = false;
280                break; // i is consumed
281            } else {
282                break;
283            }
284        }
285    }
286}
287
288/// Right-to-left pass: `i` descending; its immediate left neighbour `i-1`
289/// absorbs it (then the outer loop continues leftward through the absorber).
290fn pass_rtl(cells: &mut [Cell], euclidean: bool, p: Factors) {
291    let n = cells.len();
292    for k in 0..n {
293        let i = n - 1 - k;
294        if !cells[i].active || i == 0 {
295            continue;
296        }
297        let j = i - 1;
298        if !applicable(&cells[i], &cells[j], euclidean, p.block_spaces) {
299            continue;
300        }
301        let i_lig = cells[i].lig || cells[i].lig_carry;
302        let j_lig = cells[j].lig || cells[j].lig_carry;
303        let d0 = cells[i].avg_char_width() * p.merge;
304        let d1 = cells[i].avg_char_width() * p.merge_with_space;
305        let adj_d1 = d0 + if i_lig || j_lig { H_TOL } else { 0.0 };
306        if cells[j].adjacent(&cells[i], d0, adj_d1) && !gap_occupied(cells, j, i) {
307            let other = cells[i].clone();
308            cells[j].merge_with(&other, d1, euclidean);
309            cells[j].lig_carry = other.lig;
310            cells[i].active = false;
311        }
312    }
313}
314
315/// The contraction's tuning: the adjacency-gate and space-insertion factors
316/// (per `sanitize_bbox`'s callers) plus the word mode's space barrier.
317#[derive(Clone, Copy)]
318struct Factors {
319    merge: f64,
320    merge_with_space: f64,
321    block_spaces: bool,
322}
323
324const LINE_FACTORS: Factors = Factors {
325    merge: MERGE,
326    merge_with_space: MERGE_WITH_SPACE,
327    block_spaces: false,
328};
329const WORD_FACTORS: Factors = Factors {
330    merge: WORD_MERGE,
331    merge_with_space: WORD_MERGE_WITH_SPACE,
332    block_spaces: true,
333};
334
335/// True when the cell's text is entirely whitespace (`utils::string::is_space`).
336fn is_all_space(s: &str) -> bool {
337    !s.is_empty() && s.chars().all(char::is_whitespace)
338}
339
340fn contract(cells: &mut Vec<Cell>, euclidean: bool, p: Factors) {
341    pass_ltr(cells, false, euclidean, p);
342    cells.retain(|c| c.active);
343    pass_rtl(cells, euclidean, p);
344    cells.retain(|c| c.active);
345    pass_ltr(cells, true, euclidean, p);
346    cells.retain(|c| c.active);
347}
348
349/// Build per-glyph char cells from a page's glyph stream (shared by the line and
350/// word paths): drop degenerate spaces, recompose ligatures, init word segments.
351fn build_cells(glyphs: &[Glyph], euclidean: bool) -> Vec<Cell> {
352    let mut cells: Vec<Cell> = Vec::new();
353    for g in glyphs {
354        // Use the loose box (uniform font ascent/descent + advance) so adjacent
355        // glyphs share a top edge, matching docling-parse's `compute_rect`.
356        if !g.ll.is_finite() {
357            continue;
358        }
359        // The char cell's quad: the loose rectangle for upright text, the
360        // glyph's own rotated quad otherwise (#528) — the contraction below
361        // works on corners and edge lengths, so it reads a 90°/180°/270° line
362        // in its own reading order, exactly like docling-parse.
363        let q = g.quad.map(|q| q.map(f64::from)).unwrap_or_else(|| {
364            let (l, b, r, t) = (g.ll as f64, g.lb as f64, g.lr as f64, g.lt as f64);
365            [l, b, r, b, r, t, l, t]
366        });
367        // Drop *degenerate* space glyphs (zero-width loose box): pdfium's generated
368        // spaces get a zero-width box at the wrong baseline that breaks the
369        // corner-distance adjacency. Without them the inter-word gap drives
370        // `merge_with`'s space insertion. Spaces with a real width are kept (they
371        // carry justified double-space information). The width is the baseline
372        // edge — a rotated glyph's x extent is its em height.
373        if g.ch == ' ' && (q[2] - q[0]).hypot(q[3] - q[1]) < 0.5 {
374            continue;
375        }
376        // Recompose a ligature: pdfium decomposes one font glyph (Latin fi/ffi,
377        // Arabic lam-alef) into several chars at the *same* loose box. Append them
378        // into one cell so the contraction never inserts a space inside it.
379        // "Same box": both baseline corners match as points, upright or
380        // rotated. A ligature's chars share one box, baseline included; glyphs
381        // stacked one under another at the same x (a chart's y-axis ticks
382        // `3`…`8`, each placed by its own `cm`) are separate cells — comparing
383        // the x span alone glued those into one `345678` cell carrying the
384        // first tick's box (#609), where docling-parse keeps six.
385        if let Some(last) = cells.last_mut() {
386            // The window is docling-parse's near-copy tolerance (#1151,
387            // docling-parse#367): 0.5 pt, but never more than half the
388            // earlier glyph's width — in 0.5 pt text a whole advance is under
389            // 0.5 pt, and `Committee`'s doubled `m`/`t`/`e` were taken for
390            // re-stamps of the letter before.
391            let tol = DUP_EPS.min(0.5 * last.length());
392            let near = |ax: f64, ay: f64, bx: f64, by: f64| {
393                let d = (ax - bx).hypot(ay - by);
394                d < tol || d == 0.0
395            };
396            if near(last.rx0, last.ry0, q[0], q[1]) && near(last.rx1, last.ry1, q[2], q[3]) {
397                // Overprint duplicate: the *same* character re-stamped, offset by a
398                // fraction of its width (a kashida/elongation segment re-drawn for
399                // weight). docling-parse drops it; appending over-counts
400                // (right_to_left_02's `قويووووة` vs `قويوووة`). Require a real offset
401                // (> 0.1) so a ligature expansion — which decomposes one glyph into
402                // several chars at the *identical* box (`ff`→`ff`, diff ≈ 0) — is still
403                // recomposed; real doubled letters sit a full advance apart (> 0.5).
404                let offset = match g.quad {
405                    None => (q[0] - last.rx0).abs(),
406                    Some(_) => (q[0] - last.rx0).hypot(q[1] - last.ry0),
407                };
408                if euclidean && offset > 0.1 && last.text.ends_with(g.ch) {
409                    continue;
410                }
411                last.text.push(g.ch);
412                last.ltr = !is_right_to_left(&last.text);
413                last.blank = last.blank && g.ch.is_whitespace();
414                last.nchars += 1;
415                // Recomposed ligature cells stay tiny; recomputing is exact.
416                last.fb = last.fb || (0xFB00..=0xFB06).contains(&(g.ch as u32));
417                last.lig = is_ligature(&last.text);
418                continue;
419            }
420        }
421        let text = g.ch.to_string();
422        let ltr = !is_right_to_left(&text);
423        let blank = g.ch.is_whitespace();
424        let lig = is_ligature(&text);
425        let fb = (0xFB00..=0xFB06).contains(&(g.ch as u32));
426        cells.push(Cell {
427            text,
428            rx0: q[0],
429            ry0: q[1],
430            rx1: q[2],
431            ry1: q[3],
432            rx2: q[4],
433            ry2: q[5],
434            rx3: q[6],
435            ry3: q[7],
436            ltr,
437            active: true,
438            lig_carry: false,
439            font: g.font,
440            blank,
441            lig,
442            fb,
443            nchars: 1,
444            b_l: (g.ll as f64).min(g.lr as f64),
445            b_r: (g.ll as f64).max(g.lr as f64),
446            b_b: (g.lb as f64).min(g.lt as f64),
447            b_t: (g.lb as f64).max(g.lt as f64),
448            pen: g.pen.map(|p| p.map(f64::from)),
449            math_font: g.math_font,
450            spaced: g.spaced,
451            clip: g.clip.map(|c| c.map(f64::from)),
452            exact: g.exact,
453        });
454    }
455    remove_duplicate_cells(&mut cells);
456    cells
457}
458
459/// docling-parse's overprint tolerance, in points (`remove_duplicate_cells`
460/// and `remove_overlapping_text_cells` are both called with 0.5).
461const DUP_EPS: f64 = 0.5;
462
463/// Clip boxes whose edges differ by less than this are one clip
464/// (docling-parse's `CLIP_BBOX_EPS`).
465const CLIP_EPS: f64 = 1e-3;
466
467/// The fraction of a glyph's extent along the writing axis — or of its
468/// nominal text height, whichever is larger — a box must hide before the
469/// glyph counts as cut (docling-parse's `CLIP_HIDDEN_FRACTION`).
470const CLIP_HIDDEN: f64 = 0.2;
471
472/// `clips_differ`: no clip differs from a clip; two clips differ when an
473/// edge moves by more than [`CLIP_EPS`].
474fn clips_differ(a: Option<[f64; 4]>, b: Option<[f64; 4]>) -> bool {
475    match (a, b) {
476        (None, None) => false,
477        (Some(a), Some(b)) => (0..4).any(|k| (a[k] - b[k]).abs() > CLIP_EPS),
478        _ => true,
479    }
480}
481
482/// `cut_by`: `bx` hides more than [`CLIP_HIDDEN`] of the glyph along its
483/// writing axis. A box shorter than the nominal text height along that axis
484/// never cuts — a clip drawn tight around a period's ink, or a sliver under
485/// which a producer repaints a glyph, is no table cell; a glyph cut at its
486/// top or bottom still sits in its word and line.
487fn cut_by(c: &Cell, bx: [f64; 4]) -> bool {
488    let (dx, dy) = (c.rx1 - c.rx0, c.ry1 - c.ry0);
489    let n = dx.hypot(dy);
490    if n <= 1e-9 {
491        return false;
492    }
493    let (ux, uy) = (dx / n, dy / n);
494    let extent = |pts: [(f64, f64); 4]| {
495        pts.iter()
496            .fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), &(x, y)| {
497                let u = x * ux + y * uy;
498                (lo.min(u), hi.max(u))
499            })
500    };
501    let (g_lo, g_hi) = extent([
502        (c.rx0, c.ry0),
503        (c.rx1, c.ry1),
504        (c.rx2, c.ry2),
505        (c.rx3, c.ry3),
506    ]);
507    let (b_lo, b_hi) = extent([
508        (bx[0], bx[1]),
509        (bx[2], bx[1]),
510        (bx[2], bx[3]),
511        (bx[0], bx[3]),
512    ]);
513    let nominal = c
514        .pen
515        .map(|p| p[2])
516        .unwrap_or_else(|| (c.rx3 - c.rx0).hypot(c.ry3 - c.ry0));
517    if b_hi - b_lo < nominal {
518        return false;
519    }
520    let hidden = (b_lo - g_lo).max(0.0) + (g_hi - b_hi).max(0.0);
521    hidden > CLIP_HIDDEN * (g_hi - g_lo).max(nominal).max(1e-6)
522}
523
524/// `clip_hides`: the glyph's own clip cuts it.
525fn clip_hides(c: &Cell) -> bool {
526    c.clip.is_some_and(|bx| cut_by(c, bx))
527}
528
529/// docling-parse 7.26's `clip_boundary` (docling-parse#443, #1150): two
530/// consecutive glyphs fitted into different boxes — a producer that fits
531/// text into a table cell clips it there, and the hidden end runs under the
532/// next cell (`AB-1001-XYZReplacement of …` read as one line). Both clipped:
533/// the clips differ and one of the glyphs is cut by its own. One clipped:
534/// that glyph is cut, and the same box also cuts the other (some producers
535/// clip only the overflowing glyph and draw the rest of the word
536/// unclipped). Glyphs whole under their clips always may join — producers
537/// wrap every run, or every glyph, in a clip that does not cut it.
538fn clip_boundary(lhs: &Cell, rhs: &Cell) -> bool {
539    match (lhs.clip, rhs.clip) {
540        (None, None) => false,
541        (Some(_), Some(_)) => {
542            clips_differ(lhs.clip, rhs.clip) && (clip_hides(lhs) || clip_hides(rhs))
543        }
544        (Some(bx), None) => clip_hides(lhs) && cut_by(rhs, bx),
545        (None, Some(bx)) => clip_hides(rhs) && cut_by(lhs, bx),
546    }
547}
548
549/// docling-parse 7.26's `remove_duplicate_cells` over the char cells, before
550/// any contraction (docling-parse#367, `do_remove_duplicate_cells`, #1151).
551/// A producer paints text twice — a heading over its own shadow at the same
552/// place, a block re-stamped for weight (`1 Tr` then `0 Tr`), a whole page
553/// drawn again — and every copy read twice (`ALPHA BETA GAMMA ALPHA BETA
554/// GAMMA`). Two passes:
555/// - a char equal to an earlier one in text, font and all four corners is
556///   dropped wherever it falls on the page (copies interleaved with other
557///   lines included) — equal at full precision ([`Glyph::exact`]): a
558///   column `newspaper-00` draws again 1e-5 pt off reads twice there, as
559///   in docling-parse, though its `f32` boxes are the same;
560/// - a later char on the same line (the scan stops at the first cell more
561///   than 0.5 pt off the baseline) with the same text and font is dropped
562///   when each corner is within `min(0.5, 0.5 × the earlier char's width)`
563///   of the earlier one's — the half width keeps tiny text's doubled
564///   letters.
565///
566/// A copy shifted further than that, or off its line, is left to the word
567/// and line pass ([`overlapping_copies`]).
568fn remove_duplicate_cells(cells: &mut Vec<Cell>) {
569    let quad = |c: &Cell| [c.rx0, c.ry0, c.rx1, c.ry1, c.rx2, c.ry2, c.rx3, c.ry3];
570    let mut keep = vec![true; cells.len()];
571    // Exact as docling-parse's doubles are: the full-precision quad hash
572    // too, which the `f32` boxes alone would round away.
573    let mut painted: std::collections::HashSet<(&str, u64, u64, [u64; 8])> =
574        std::collections::HashSet::new();
575    for (i, c) in cells.iter().enumerate() {
576        if !painted.insert((c.text.as_str(), c.font, c.exact, quad(c).map(f64::to_bits))) {
577            keep[i] = false;
578        }
579    }
580    for i in 0..cells.len() {
581        if !keep[i] {
582            continue;
583        }
584        let a = &cells[i];
585        let tol = DUP_EPS.min(0.5 * a.length());
586        let close = |d: f64| d < tol || d == 0.0;
587        let (qa, mut dropped) = (quad(a), Vec::new());
588        for (j, b) in cells.iter().enumerate().skip(i + 1) {
589            if (a.ry0 - b.ry0).abs() > DUP_EPS {
590                break;
591            }
592            if !keep[j] || a.font != b.font || a.text != b.text {
593                continue;
594            }
595            let qb = quad(b);
596            if (0..4).all(|k| close((qa[2 * k] - qb[2 * k]).hypot(qa[2 * k + 1] - qb[2 * k + 1]))) {
597                dropped.push(j);
598            }
599        }
600        for j in dropped {
601            keep[j] = false;
602        }
603    }
604    if keep.iter().all(|&k| k) {
605        return;
606    }
607    let mut it = keep.into_iter();
608    cells.retain(|_| it.next().unwrap_or(true));
609}
610
611/// A cell as [`overlapping_copies`] compares it: text, font, left-to-right,
612/// the quad, the clip box.
613type CopyKey<'a> = (&'a str, u64, bool, [f64; 8], Option<[f64; 4]>);
614
615/// docling-parse 7.26's `remove_overlapping_text_cells(…, 0.5)` over the
616/// contracted word cells and line cells (docling-parse#367, #1151): a cell
617/// is a copy of an earlier one with the same text, font and writing
618/// direction whose every corner is closer than `min(0.5, 0.1 × the smallest
619/// width or height of the two)` (0 always counts) — the copy of a line drawn
620/// again after other text, a rotated line stamped twice. The first copy is
621/// kept, the order preserved; a partial match or an overlap alone never
622/// counts. Candidates are bucketed by text, font and a 0.5 pt grid of the
623/// first corner, so a copy is looked for in the 3 × 3 buckets around its
624/// own. The clips must not differ either ([`clips_differ`], #1150): the
625/// same token in two table cells is two tokens. docling-parse also asks
626/// for the same widget state, which glyphs here do not carry. Returns the
627/// keep mask.
628fn overlapping_copies(cells: &[CopyKey]) -> Vec<bool> {
629    let mut keep = vec![true; cells.len()];
630    // (text, font, grid column, grid row) → the earlier cells there, each
631    // with its width and height.
632    type Bucket<'a> = (&'a str, u64, i64, i64);
633    let mut buckets: HashMap<Bucket, Vec<(usize, f64, f64)>> = HashMap::new();
634    for (i, &(text, font, ltr, q, clip)) in cells.iter().enumerate() {
635        if text.is_empty() {
636            continue;
637        }
638        let (col, row) = ((q[0] / DUP_EPS).floor(), (q[1] / DUP_EPS).floor());
639        let w = (q[2] - q[0]).hypot(q[3] - q[1]);
640        let h = (q[6] - q[0]).hypot(q[7] - q[1]);
641        if !(col.is_finite() && row.is_finite() && w.is_finite() && h.is_finite()) {
642            continue;
643        }
644        let (col, row) = (col as i64, row as i64);
645        let copy = (-1..=1).any(|dx| {
646            (-1..=1).any(|dy| {
647                buckets
648                    .get(&(text, font, col + dx, row + dy))
649                    .is_some_and(|earlier| {
650                        earlier.iter().any(|&(k, pw, ph)| {
651                            let (_, _, pltr, p, pclip) = cells[k];
652                            let tol = DUP_EPS.min(0.1 * w.min(h).min(pw).min(ph));
653                            pltr == ltr
654                                && !clips_differ(clip, pclip)
655                                && (0..4).all(|c| {
656                                    let d =
657                                        (q[2 * c] - p[2 * c]).hypot(q[2 * c + 1] - p[2 * c + 1]);
658                                    d < tol || d == 0.0
659                                })
660                        })
661                    })
662            })
663        });
664        if copy {
665            keep[i] = false;
666        } else {
667            buckets
668                .entry((text, font, col, row))
669                .or_default()
670                .push((i, w, h));
671        }
672    }
673    keep
674}
675
676/// Build line cells from a page's glyph stream under the process's word-gap
677/// rule (`DOCLING_RS_PDF_WORD_GAP`, #921).
678pub(crate) fn line_cells(glyphs: &[Glyph], page_h: f32, euclidean: bool) -> Vec<TextCell> {
679    line_and_word_cells_with(glyphs, page_h, euclidean, WordGap::from_env()).0
680}
681
682/// Build **word** cells from a page's glyph stream via docling-parse's
683/// `create_word_cells`: a second contraction over the same char cells under the
684/// word factors — adjacency gate 0.33 (vs the line's 1.0), so a gap wide enough
685/// to become a line-internal space still merges glyphs into one spaceless word
686/// when it stays under the gate (tight-set Korean: line `1군 감염병`, word
687/// `1군감염병`); real space glyphs are hard barriers and are erased afterwards.
688/// These are the per-word tokens TableFormer matches table-grid cells against.
689pub(crate) fn word_cells(glyphs: &[Glyph], page_h: f32, euclidean: bool) -> Vec<TextCell> {
690    line_and_word_cells_with(glyphs, page_h, euclidean, WordGap::from_env()).1
691}
692
693/// Build the line cells **and** the word cells from one shared glyph build
694/// under docling-parse ≤ 6's contraction ([`WordGap::Legacy`]): the char
695/// cells are constructed once and contracted twice, under the line factors
696/// and the word factors respectively — exactly docling-parse's
697/// `create_line_cells` + `create_word_cells` pair. The tests pin the legacy
698/// contraction through it; production goes through the process's rule.
699#[cfg(test)]
700pub(crate) fn line_and_word_cells(
701    glyphs: &[Glyph],
702    page_h: f32,
703    euclidean: bool,
704) -> (Vec<TextCell>, Vec<TextCell>) {
705    line_and_word_cells_with(glyphs, page_h, euclidean, WordGap::Legacy)
706}
707
708/// [`line_and_word_cells`] under the word-gap rule `gap` (#921): the legacy
709/// contraction, or docling-parse ≥ 7's line runs.
710pub(crate) fn line_and_word_cells_with(
711    glyphs: &[Glyph],
712    page_h: f32,
713    euclidean: bool,
714    gap: WordGap,
715) -> (Vec<TextCell>, Vec<TextCell>) {
716    line_and_word_cells_cut(glyphs, page_h, euclidean, gap, zero_advance_run())
717}
718
719/// `DOCLING_RS_PDF_ZERO_ADVANCE_RUN`: off. On, the glyph after a
720/// zero-advance one starts a line run, as in docling-parse ≥ 7 — its
721/// `facing_edge_overlap` takes the writing axis from the left cell's bottom
722/// edge and returns 0 for one of no length. That cuts an Arabic word at its
723/// tanween and sets the pieces apart (`أيضًا` reads `أيض ً`, its tail a clause
724/// away), and docling's groundtruth has it so: the knob is for comparing
725/// against docling, not for reading. Off, the mark stays in its line.
726fn zero_advance_run() -> bool {
727    static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
728    *ON.get_or_init(|| docling_core::env::flag("DOCLING_RS_PDF_ZERO_ADVANCE_RUN"))
729}
730
731/// [`line_and_word_cells_with`] with [`zero_advance_run`] as an argument.
732fn line_and_word_cells_cut(
733    glyphs: &[Glyph],
734    page_h: f32,
735    euclidean: bool,
736    gap: WordGap,
737    zero_advance_run: bool,
738) -> (Vec<TextCell>, Vec<TextCell>) {
739    let built = build_cells(glyphs, euclidean);
740    if gap != WordGap::Legacy {
741        return contract_runs(&built, gap, page_h, zero_advance_run);
742    }
743    let to_text_cell = |c: Cell| {
744        let l = c.rx0.min(c.rx1).min(c.rx2).min(c.rx3) as f32;
745        let r = c.rx0.max(c.rx1).max(c.rx2).max(c.rx3) as f32;
746        let top = c.ry0.max(c.ry1).max(c.ry2).max(c.ry3) as f32;
747        let bot = c.ry0.min(c.ry1).min(c.ry2).min(c.ry3) as f32;
748        TextCell {
749            text: c.text,
750            l,
751            t: page_h - top,
752            r,
753            b: page_h - bot,
754        }
755    };
756    // Word run: docling-parse's `create_word_cells` order — copy the char
757    // cells, contract (`sanitize_bbox`), *then* erase the spaces. The space
758    // glyphs stay in the stream during the contraction, where `applicable`'s
759    // `block_spaces` makes each one a hard word boundary; they are dropped
760    // afterwards by the blank filter below. Filtering them out up front let
761    // the 0.33 gate alone decide word breaks, which glues tight-set Latin
762    // (`MODE` + `to`: 1.8 pt apart under a 2.0 pt gate → `MODEto`) and the
763    // thin-spaced Korean docling-parse ≥ 7 keeps apart (`1군` `감염병`).
764    let mut word_run: Vec<Cell> = built.clone();
765    let mut cells = built;
766    contract(&mut cells, euclidean, LINE_FACTORS);
767    drop_overlapping_cells(&mut cells);
768    let lines = to_text_cells(cells, to_text_cell);
769    contract(&mut word_run, euclidean, WORD_FACTORS);
770    word_run.retain(|c| !c.text.trim().is_empty());
771    drop_overlapping_cells(&mut word_run);
772    let words = to_text_cells(word_run, to_text_cell);
773    (lines, words)
774}
775
776/// [`overlapping_copies`] over contracted [`Cell`]s.
777fn drop_overlapping_cells(cells: &mut Vec<Cell>) {
778    let keys: Vec<_> = cells
779        .iter()
780        .map(|c| {
781            let q = [c.rx0, c.ry0, c.rx1, c.ry1, c.rx2, c.ry2, c.rx3, c.ry3];
782            (c.text.as_str(), c.font, c.ltr, q, c.clip)
783        })
784        .collect();
785    let keep = overlapping_copies(&keys);
786    let mut it = keep.into_iter();
787    cells.retain(|_| it.next().unwrap_or(true));
788}
789
790/// Map the contracted cells into a freshly allocated, exactly sized vector.
791///
792/// A plain `into_iter().map(..).collect()` would take std's in-place-collect
793/// path and hand back the *input's* allocation: one ~150-byte [`Cell`] slot per
794/// glyph of the page, reinterpreted as ~4× as many 40-byte [`TextCell`] slots,
795/// while the contraction leaves a few glyphs per cell. Callers keep these
796/// vectors for the whole document (the text-layer path holds every page), so
797/// the dead capacity added up to ~30× the cells' real size — gigabytes on a
798/// long table-heavy PDF.
799fn to_text_cells(cells: Vec<Cell>, f: impl Fn(Cell) -> TextCell) -> Vec<TextCell> {
800    let mut out = Vec::with_capacity(cells.len());
801    out.extend(cells.into_iter().map(f));
802    out
803}
804
805fn is_rtl_char(c: char) -> bool {
806    let ch = c as u32;
807    (0x0600..=0x06FF).contains(&ch)
808        || (0x0750..=0x077F).contains(&ch)
809        || (0x08A0..=0x08FF).contains(&ch)
810        || (0xFB50..=0xFDFF).contains(&ch)
811        || (0xFE70..=0xFEFF).contains(&ch)
812        || (0x0590..=0x05FF).contains(&ch)
813        || (0xFB1D..=0xFB4F).contains(&ch)
814        || (0x0700..=0x074F).contains(&ch)
815        || (0x0780..=0x07BF).contains(&ch)
816        || (0x07C0..=0x07FF).contains(&ch)
817}
818
819/// All codepoints are RTL-script (matches `string.h::is_right_to_left`).
820fn is_right_to_left(s: &str) -> bool {
821    !s.is_empty() && s.chars().all(is_rtl_char)
822}
823
824/// A single-codepoint punctuation/space cell (matches `string.h`).
825fn is_punct_or_space(s: &str) -> bool {
826    let mut chars = s.chars();
827    let (Some(c), None) = (chars.next(), chars.next()) else {
828        return false;
829    };
830    if matches!(
831        c,
832        ' ' | '\t'
833            | '\n'
834            | '\r'
835            | '\u{0c}'
836            | '\u{0b}'
837            | '.'
838            | ','
839            | ';'
840            | ':'
841            | '!'
842            | '?'
843            | '('
844            | ')'
845            | '['
846            | ']'
847            | '{'
848            | '}'
849            | '\''
850            | '"'
851            | '`'
852            | '\u{2018}'
853            | '\u{2019}'
854            | '\u{201c}'
855            | '\u{201d}'
856            | '-'
857            | '\u{2013}'
858            | '\u{2014}'
859            | '_'
860            | '/'
861            | '\\'
862            | '|'
863            | '@'
864            | '#'
865            | '%'
866            | '&'
867            | '*'
868            | '+'
869            | '='
870            | '<'
871            | '>'
872    ) {
873        return true;
874    }
875    let ch = c as u32;
876    (0x2000..=0x206F).contains(&ch)
877        || (0x3000..=0x303F).contains(&ch)
878        || (0xFE50..=0xFE6F).contains(&ch)
879        || (0xFF00..=0xFF0F).contains(&ch)
880        || (0xFF1A..=0xFF1F).contains(&ch)
881        || (0xFF3B..=0xFF5E).contains(&ch)
882}
883
884/// Ligature glyph or its ASCII spelling (matches `string.h::is_ligature`).
885fn is_ligature(s: &str) -> bool {
886    matches!(s, "ff" | "fi" | "fl" | "ffi" | "ffl")
887        || s.chars().any(|c| (0xFB00..=0xFB06).contains(&(c as u32)))
888}
889
890// ------------------------------------------------------------ word gaps (#921)
891
892/// How a word boundary is decided where the PDF draws no space glyph — a
893/// word set apart only by moving the text cursor (#921).
894///
895/// [`WordGap::Adaptive`], the default, and [`WordGap::Factor`] follow
896/// docling-parse ≥ 7's contractor (`cells.h::contract`, 2026-09, PR #351 —
897/// what docling ≥ 2.142 runs on, `docling-parse>=7.22`): glyphs are grouped
898/// into line runs by geometry alone (no font boundary), every gap between
899/// two visible glyphs is normalized by the mean advance of those two
900/// glyphs, and a normalized gap above the threshold starts a new word; an
901/// explicit space glyph is always a boundary. Line cells are the run's
902/// words joined by single spaces. Letter spacing is detected first
903/// ([`tracked_gaps`]) — our addition, where docling-parse cuts letter-spaced
904/// words mid-word.
905///
906/// [`WordGap::Legacy`] is the contraction above: the docling-parse ≤ 6 rule
907/// this port started from, where a gap splits two words when it exceeds
908/// 0.33 × the running mean advance of the cell accumulated so far — a cell
909/// that restarts at every font change, so the threshold drifts along a line
910/// (`und dem` in a second font resource read `unddem`: 1.955 pt against
911/// 0.33 × 5.925 pt, the mean of `und` alone).
912#[derive(Clone, Copy, Debug, Default, PartialEq)]
913pub enum WordGap {
914    /// docling-parse ≤ 6's running-mean contraction.
915    Legacy,
916    /// A fixed normalized threshold for every line.
917    Factor(f64),
918    /// docling-parse ≥ 7's line-local threshold: a two-cluster k-means over
919    /// the line's normalized gaps (character spacing vs word spacing), at
920    /// least 0.18, capped at 0.35, 0.25 when the gaps do not separate.
921    #[default]
922    Adaptive,
923}
924
925impl WordGap {
926    /// The accepted spellings, for error messages.
927    pub const ACCEPTED: &'static str = "legacy, adaptive, or a factor in (0, 4]";
928
929    /// `legacy` / `adaptive` / a positive factor up to 4 (case-insensitive);
930    /// `Err` with the reason for anything else.
931    pub fn parse(s: &str) -> Result<Self, String> {
932        let t = s.trim().to_ascii_lowercase();
933        match t.as_str() {
934            "legacy" => Ok(WordGap::Legacy),
935            "adaptive" | "auto" | "default" => Ok(WordGap::Adaptive),
936            _ => match t.parse::<f64>() {
937                Ok(f) if f.is_finite() && f > 0.0 && f <= 4.0 => Ok(WordGap::Factor(f)),
938                _ => Err(format!(
939                    "pdf_word_gap must be {}, got {s:?}",
940                    WordGap::ACCEPTED
941                )),
942            },
943        }
944    }
945
946    /// `DOCLING_RS_PDF_WORD_GAP`, or the default ([`WordGap::Adaptive`])
947    /// when it is unset (an unreadable value warns once and keeps the
948    /// default).
949    pub fn from_env() -> Self {
950        let Some(v) = docling_core::env::nonempty("DOCLING_RS_PDF_WORD_GAP") else {
951            return WordGap::default();
952        };
953        WordGap::parse(&v).unwrap_or_else(|e| {
954            static WARNED: std::sync::Once = std::sync::Once::new();
955            WARNED.call_once(|| {
956                eprintln!("docling-pdf: DOCLING_RS_PDF_WORD_GAP: {e}; using adaptive")
957            });
958            WordGap::default()
959        })
960    }
961}
962
963/// The bottom-edge length at or under which a glyph gives no writing axis:
964/// docling-parse's own bound in `facing_edge_overlap`. ([`RunCell::scale`]'s
965/// 1e-6 is its `cell_space_width`'s, a different question — whether the
966/// advance can normalize a gap.)
967const NO_AXIS: f64 = 1e-9;
968
969/// One glyph cell of a line run, with its writing axis precomputed.
970struct RunCell<'a> {
971    cell: &'a Cell,
972    /// Unit vector along the bottom edge (the writing direction).
973    ux: f64,
974    uy: f64,
975    /// Bottom-edge length: the advance the glyph's loose box spans.
976    advance: f64,
977    height: f64,
978    space: bool,
979}
980
981impl<'a> RunCell<'a> {
982    fn new(cell: &'a Cell) -> Self {
983        let (dx, dy) = (cell.rx1 - cell.rx0, cell.ry1 - cell.ry0);
984        let advance = dx.hypot(dy);
985        let (ux, uy) = if advance > NO_AXIS {
986            (dx / advance, dy / advance)
987        } else {
988            (1.0, 0.0)
989        };
990        let h0 = (cell.rx3 - cell.rx0).hypot(cell.ry3 - cell.ry0);
991        let h1 = (cell.rx2 - cell.rx1).hypot(cell.ry2 - cell.ry1);
992        RunCell {
993            cell,
994            ux,
995            uy,
996            advance,
997            height: 0.5 * (h0 + h1),
998            space: cell.blank,
999        }
1000    }
1001
1002    /// The normalization length of a gap next to this glyph: its advance,
1003    /// else half its height (docling-parse's `cell_space_width` fallback).
1004    fn scale(&self) -> f64 {
1005        if self.advance > 1e-6 {
1006            self.advance
1007        } else {
1008            (0.5 * self.height).max(1e-6)
1009        }
1010    }
1011}
1012
1013/// Signed distance along `lhs`'s writing direction from where its pen
1014/// advance ends to where `rhs`'s starts (`forward_gap`, the
1015/// `has_text_placement` form docling-parse takes for every rendered glyph).
1016/// Our quads run in pen order — `r0 → r1` is the advance — so this is the
1017/// trailing edge of `lhs` to the leading edge of `rhs` whatever the script:
1018/// right-to-left text drawn in visual order still advances along `+u`, and
1019/// flipping the axis for it (the geometric fallback) read every Arabic or
1020/// Hebrew glyph pair as a step back of two advances, a new line each.
1021fn forward_gap(lhs: &RunCell, rhs: &RunCell) -> f64 {
1022    let (l, r) = (lhs.cell, rhs.cell);
1023    let (tx, ty) = (0.5 * (l.rx1 + l.rx2), 0.5 * (l.ry1 + l.ry2));
1024    let (hx, hy) = (0.5 * (r.rx0 + r.rx3), 0.5 * (r.ry0 + r.ry3));
1025    (hx - tx) * lhs.ux + (hy - ty) * lhs.uy
1026}
1027
1028/// Overlap, across the writing direction, of `lhs`'s trailing edge and
1029/// `rhs`'s leading edge — positive for glyphs on one text line.
1030fn facing_edge_overlap(lhs: &RunCell, rhs: &RunCell, zero_advance_run: bool) -> f64 {
1031    let (l, r) = (lhs.cell, rhs.cell);
1032    // docling-parse takes the axis from `lhs`'s bottom edge and gives up on
1033    // one of no length: nothing overlaps a zero-advance glyph's trailing
1034    // edge, so the glyph after it starts a run. We do so only when asked
1035    // ([`zero_advance_run`]) and otherwise measure along the x axis.
1036    if zero_advance_run && lhs.advance <= NO_AXIS {
1037        return 0.0;
1038    }
1039    let (ux, uy) = if l.ltr {
1040        (lhs.ux, lhs.uy)
1041    } else {
1042        (-lhs.ux, -lhs.uy)
1043    };
1044    let (nx, ny) = (-uy, ux);
1045    let proj = |x: f64, y: f64| x * nx + y * ny;
1046    let (a0, a1) = if l.ltr {
1047        (proj(l.rx1, l.ry1), proj(l.rx2, l.ry2))
1048    } else {
1049        (proj(l.rx0, l.ry0), proj(l.rx3, l.ry3))
1050    };
1051    let (b0, b1) = if l.ltr {
1052        (proj(r.rx0, r.ry0), proj(r.rx3, r.ry3))
1053    } else {
1054        (proj(r.rx1, r.ry1), proj(r.rx2, r.ry2))
1055    };
1056    a0.max(a1).min(b0.max(b1)) - a0.min(a1).max(b0.min(b1))
1057}
1058
1059/// A glyph of a mathematical layout by its symbols — the symbol half of
1060/// `has_math_positioning_semantics`; the font-name half is
1061/// [`Glyph::math_font`].
1062fn is_math_glyph(text: &str) -> bool {
1063    const MATH: &str = "∑∏∫√∞∈∉≠≤≥⊂⊃⊆⊇⊥∪∩⎛⎜⎝⎞⎟⎠⎡⎢⎣⎤⎥⎦";
1064    text.chars().any(|c| MATH.contains(c))
1065}
1066
1067/// A sub- or superscript placed by moving the cursor next to its base in a
1068/// mathematical context (`is_local_positioned_attachment`).
1069fn is_local_attachment(lhs: &RunCell, rhs: &RunCell) -> bool {
1070    let scale = lhs.scale().max(rhs.scale());
1071    if forward_gap(lhs, rhs) > 0.10 * scale {
1072        return false;
1073    }
1074    let (off, (lh, rh)) = baseline_offset(lhs, rhs);
1075    let math = |c: &RunCell| c.cell.math_font || is_math_glyph(&c.cell.text);
1076    off <= 2.0 * lh.max(rh).max(1e-6) && (math(lhs) || math(rhs))
1077}
1078
1079/// How far `rhs` sits from `lhs`'s baseline, across `lhs`'s writing axis,
1080/// and the two glyphs' nominal heights: the pens' origins and the font sizes
1081/// when the parser knows them (docling-parse's `text_origin` /
1082/// `nominal_text_height`), else the loose boxes' bottom corners and heights.
1083/// The boxes overstate a size change — a superscript's box bottom sits only
1084/// its own, smaller descent below a raised baseline — so `Lysak` + its ORCID
1085/// read as two words where docling-parse 7 keeps one.
1086fn baseline_offset(lhs: &RunCell, rhs: &RunCell) -> (f64, (f64, f64)) {
1087    let (nx, ny) = (-lhs.uy, lhs.ux);
1088    match (lhs.cell.pen, rhs.cell.pen) {
1089        (Some(a), Some(b)) => (
1090            ((b[0] - a[0]) * nx + (b[1] - a[1]) * ny).abs(),
1091            (a[2], b[2]),
1092        ),
1093        _ => (
1094            ((rhs.cell.rx0 - lhs.cell.rx0) * nx + (rhs.cell.ry0 - lhs.cell.ry0) * ny).abs(),
1095            (lhs.height, rhs.height),
1096        ),
1097    }
1098}
1099
1100/// Whether `rhs` continues `lhs`'s text line (`continues_line`): the same
1101/// writing direction, facing edges that overlap across it, and a cursor
1102/// move between a step back and four advances forward.
1103fn continues_line(lhs: &RunCell, rhs: &RunCell, zero_advance_run: bool) -> bool {
1104    if lhs.ux * rhs.ux + lhs.uy * rhs.uy < 0.985 {
1105        return false;
1106    }
1107    let scale = lhs.scale().max(rhs.scale());
1108    let gap = forward_gap(lhs, rhs);
1109    if facing_edge_overlap(lhs, rhs, zero_advance_run) <= 1e-6 && !is_local_attachment(lhs, rhs) {
1110        return false;
1111    }
1112    -scale <= gap && gap <= 4.0 * scale
1113}
1114
1115/// Whether two glyphs sit on one baseline (`word_baselines_compatible`): a
1116/// baseline shift beyond 0.35 × the smaller height starts a new word,
1117/// unless it is a mathematical attachment.
1118fn baselines_compatible(lhs: &RunCell, rhs: &RunCell) -> bool {
1119    let (off, (lh, rh)) = baseline_offset(lhs, rhs);
1120    off <= 0.35 * lh.min(rh).max(1e-6) || is_local_attachment(lhs, rhs)
1121}
1122
1123/// The gap between two visible glyphs over their mean advance.
1124fn normalized_gap(lhs: &RunCell, rhs: &RunCell) -> f64 {
1125    forward_gap(lhs, rhs).max(0.0) / (0.5 * (lhs.scale() + rhs.scale())).max(1e-6)
1126}
1127
1128/// What a glyph is to the letter-spacing detector.
1129#[derive(Clone, Copy, PartialEq)]
1130enum TrackClass {
1131    /// Letters and digits — what letter-spaced (Sperrsatz) words are set in.
1132    Letter,
1133    /// Leader dots.
1134    Dot,
1135    Other,
1136}
1137
1138fn track_class(text: &str) -> TrackClass {
1139    if matches!(text, "." | "·" | "…") {
1140        TrackClass::Dot
1141    } else if !text.is_empty() && text.chars().all(char::is_alphanumeric) {
1142        TrackClass::Letter
1143    } else {
1144        TrackClass::Other
1145    }
1146}
1147
1148/// Points two letter-spacing gaps may differ by and still be one tracking:
1149/// producers set a letter-spaced word with one constant cursor move (#921's
1150/// fixtures: within 0.17 pt), which rounding and kerning blur slightly.
1151fn tracking_tolerance(gap: f64) -> f64 {
1152    (0.08 * gap).max(0.25)
1153}
1154
1155/// Letter spacing (Sperrsatz, tracked capitals, leader dots) in a line run
1156/// (#921): `true` at index `i` when the gap from the previous visible glyph
1157/// to `run[i]` is tracking inside one word rather than a word boundary.
1158///
1159/// docling-parse ≥ 7 judges each gap by its width over the flanking glyphs'
1160/// mean advance, and a letter-spaced word defeats that: its gaps are one
1161/// constant cursor move in points, but divided by the advances of `i`, `l`
1162/// or `t` beside `M` or `D` they spread over 0.25–0.75, straddling any
1163/// threshold, so the word is cut mid-word (`Di ens tk lasse`, `Heimarbei
1164/// tstari f`). Constancy in points is the signal instead: a chain of three
1165/// or more consecutive gaps between letters that are open (≥ 0.1 of an
1166/// advance), at most one advance wide (not table columns) and equal within
1167/// [`tracking_tolerance`] is tracking — when nothing on either side of it is
1168/// tighter. That last test is what tells it from justified prose, whose
1169/// word gaps are equal along a line too and chain up across one-letter
1170/// words (`Peter W J Staar`, `Abs 1 Z 3 UrlG`): there the chain is flanked
1171/// by abutting letters, while a letter-spaced word starts and ends at the
1172/// line's ends, a space glyph or a wider gap; and one character repeated
1173/// (`C C C C`, a figure's token row) is no word. Once a run has such a chain,
1174/// shorter stretches at the same tracking with the same open flanks join
1175/// it: the short words of the heading (`für`, `und`, `II`) and closing
1176/// punctuation (`:`). Four or more dots in a row, each within an advance of
1177/// the last, are one leader whatever their spacing.
1178fn tracked_gaps(run: &[RunCell]) -> Vec<bool> {
1179    struct Gap {
1180        left: usize,
1181        right: usize,
1182        pt: f64,
1183        n: f64,
1184        left_class: TrackClass,
1185        right_class: TrackClass,
1186    }
1187    let mut gaps: Vec<Gap> = Vec::new();
1188    let mut prev: Option<usize> = None;
1189    let mut crossed_space = false;
1190    for (i, c) in run.iter().enumerate() {
1191        if c.space {
1192            crossed_space = true;
1193            continue;
1194        }
1195        if let (Some(p), false) = (prev, crossed_space) {
1196            gaps.push(Gap {
1197                left: p,
1198                right: i,
1199                pt: forward_gap(&run[p], c),
1200                n: normalized_gap(&run[p], c),
1201                left_class: track_class(&run[p].cell.text),
1202                right_class: track_class(&c.cell.text),
1203            });
1204        }
1205        prev = Some(i);
1206        crossed_space = false;
1207    }
1208    // `gaps[k]` and `gaps[k + 1]` share a glyph — no space glyph between.
1209    let joined = |k: usize| gaps[k + 1].left == gaps[k].right;
1210    // The longest stretch from `k` of joined gaps that `fits`, as its end.
1211    let stretch = |k: usize, fits: &dyn Fn(&Gap) -> bool| {
1212        let mut end = k;
1213        while end < gaps.len() && fits(&gaps[end]) && (end == k || joined(end - 1)) {
1214            end += 1;
1215        }
1216        end
1217    };
1218    // No gap right before or after `k..end` tighter than `floor` points.
1219    let flanks_open = |k: usize, end: usize, floor: f64| {
1220        let before = k > 0 && joined(k - 1) && gaps[k - 1].pt < floor;
1221        let after = end < gaps.len() && joined(end - 1) && gaps[end].pt < floor;
1222        !before && !after
1223    };
1224
1225    let mut tracked = vec![false; run.len()];
1226    // A gap the text parser already settled: the letters were set apart
1227    // with a space glyph between them, which it took out (#1139).
1228    for g in &gaps {
1229        tracked[g.right] = run[g.right].cell.spaced;
1230    }
1231    let mut leader = vec![false; run.len()];
1232    let mut letter_tracking: Vec<f64> = Vec::new();
1233    let mut k = 0;
1234    while k < gaps.len() {
1235        let dots = |g: &Gap| {
1236            g.left_class == TrackClass::Dot && g.right_class == TrackClass::Dot && g.n <= 1.0
1237        };
1238        let end = stretch(k, &dots);
1239        if end - k >= 3 {
1240            for g in &gaps[k..end] {
1241                tracked[g.right] = true;
1242                leader[g.left] = true;
1243                leader[g.right] = true;
1244            }
1245            k = end;
1246            continue;
1247        }
1248        let first = &gaps[k];
1249        let letters = |g: &Gap| {
1250            g.left_class == TrackClass::Letter
1251                && g.right_class == TrackClass::Letter
1252                && (0.1..=1.0).contains(&g.n)
1253        };
1254        if !letters(first) {
1255            k += 1;
1256            continue;
1257        }
1258        let (mut lo, mut hi) = (first.pt, first.pt);
1259        let mut end = k + 1;
1260        while end < gaps.len()
1261            && joined(end - 1)
1262            && letters(&gaps[end])
1263            && hi.max(gaps[end].pt) - lo.min(gaps[end].pt) <= tracking_tolerance(lo)
1264        {
1265            lo = lo.min(gaps[end].pt);
1266            hi = hi.max(gaps[end].pt);
1267            end += 1;
1268        }
1269        // One character repeated (`C C C C` in a figure, `x x x x`) is a row
1270        // of tokens, not a word.
1271        let one_char = gaps[k..end]
1272            .iter()
1273            .all(|g| run[g.right].cell.text == run[first.left].cell.text);
1274        if end - k >= 3 && !one_char && flanks_open(k, end, lo - tracking_tolerance(lo)) {
1275            for g in &gaps[k..end] {
1276                tracked[g.right] = true;
1277            }
1278            letter_tracking.push(0.5 * (lo + hi));
1279            k = end;
1280        } else {
1281            k += 1;
1282        }
1283    }
1284
1285    for &t in &letter_tracking {
1286        let tol = tracking_tolerance(t);
1287        let same = |g: &Gap| {
1288            (g.left_class == TrackClass::Letter || g.right_class == TrackClass::Letter)
1289                && g.left_class != TrackClass::Dot
1290                && g.right_class != TrackClass::Dot
1291                && g.n <= 1.0
1292                && (g.pt - t).abs() <= tol
1293        };
1294        let mut k = 0;
1295        while k < gaps.len() {
1296            let end = stretch(k, &same);
1297            if end == k {
1298                k += 1;
1299                continue;
1300            }
1301            if flanks_open(k, end, t - tol) && !gaps[k..end].iter().any(|g| leader[g.left]) {
1302                for g in &gaps[k..end] {
1303                    tracked[g.right] = true;
1304                }
1305            }
1306            k = end;
1307        }
1308    }
1309    tracked
1310}
1311
1312/// Where a gap enters [`infer_word_gap`]'s k-means at most. A gap this wide
1313/// is a word boundary under any threshold the rule can pick (it caps at
1314/// 0.35), so its exact width carries no information — but one wide gap
1315/// after a comma or before a column (0.8–5 advances) dragged the high
1316/// cluster's mean up until the midpoint hit the 0.35 cap, and the line's
1317/// real word gaps (0.31–0.33 in tight justified text) fell under it:
1318/// `jedochwerdenweiterlaufendeQuartierkosten`, `KhurramAzeemHashmi`.
1319/// **Divergence** from docling-parse 7, which glues those (#921: 68 → 7
1320/// glues on the EVU agreement, measured against `pdftotext`'s words).
1321const GAP_CLUSTER_CLIP: f64 = 0.5;
1322
1323/// docling-parse ≥ 7's `infer_word_gap`: the line's normalized gaps (not
1324/// across an explicit space) split by an eight-step two-cluster k-means;
1325/// 0.25 when there are fewer than two or they do not separate, else the
1326/// midpoint of the two cluster means, at least 0.18. Letter-spacing gaps
1327/// (`tracked`, #921) stay out of the sample: they are settled already, and
1328/// their spread would drag the low cluster up into the word gaps. Each gap
1329/// enters at most [`GAP_CLUSTER_CLIP`] wide.
1330fn infer_word_gap(run: &[RunCell], tracked: &[bool]) -> f64 {
1331    let mut gaps = Vec::new();
1332    let mut prev: Option<&RunCell> = None;
1333    let mut crossed_space = false;
1334    for (i, c) in run.iter().enumerate() {
1335        if c.space {
1336            crossed_space = true;
1337            continue;
1338        }
1339        if let (Some(p), false, false) = (prev, crossed_space, tracked[i]) {
1340            gaps.push(normalized_gap(p, c).min(GAP_CLUSTER_CLIP));
1341        }
1342        prev = Some(c);
1343        crossed_space = false;
1344    }
1345    if gaps.len() < 2 {
1346        return 0.25;
1347    }
1348    let mut low = gaps.iter().copied().fold(f64::INFINITY, f64::min);
1349    let mut high = gaps.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1350    if high < 0.18 || high - low < 0.08 {
1351        return 0.25;
1352    }
1353    for _ in 0..8 {
1354        let mid = 0.5 * (low + high);
1355        let (mut ls, mut ln, mut hs, mut hn) = (0.0, 0usize, 0.0, 0usize);
1356        for &g in &gaps {
1357            if g <= mid {
1358                ls += g;
1359                ln += 1;
1360            } else {
1361                hs += g;
1362                hn += 1;
1363            }
1364        }
1365        if ln == 0 || hn == 0 {
1366            return 0.25;
1367        }
1368        low = ls / ln as f64;
1369        high = hs / hn as f64;
1370    }
1371    if high < 0.18 || high - low < 0.08 {
1372        return 0.25;
1373    }
1374    (0.5 * (low + high)).max(0.18)
1375}
1376
1377/// A word or line being assembled: its text and its rotation-aligned box.
1378struct Agg {
1379    text: String,
1380    ltr: bool,
1381    q: [f64; 8],
1382    /// A word that starts only because its first glyph sits on another
1383    /// baseline than the glyph before it, with no horizontal gap between
1384    /// them, *inside a bracket* — a raised footnote marker after `(`, the
1385    /// `)` after it, a citation's `]` — joins the line text without a space
1386    /// (#992, a deliberate divergence from docling-parse's `( 1 )`; the
1387    /// word cell is still its own).
1388    glued: bool,
1389    /// The first glyph's font — a contracted cell's `font_name` in
1390    /// docling-parse, which the duplicate pass compares.
1391    font: u64,
1392    /// The clip box all its glyphs share, else `None` (#1150).
1393    clip: Option<[f64; 4]>,
1394}
1395
1396impl Agg {
1397    fn of(c: &Cell, glued: bool) -> Self {
1398        Agg {
1399            text: c.text.clone(),
1400            ltr: c.ltr,
1401            q: [c.rx0, c.ry0, c.rx1, c.ry1, c.rx2, c.ry2, c.rx3, c.ry3],
1402            glued,
1403            font: c.font,
1404            clip: c.clip,
1405        }
1406    }
1407
1408    /// `append_cell`: the text in reading order (an RTL piece prepends), and
1409    /// the smallest rectangle aligned with the writing direction holding
1410    /// both boxes.
1411    fn append(&mut self, text: &str, ltr: bool, q: &[f64; 8], space: bool, clip: Option<[f64; 4]>) {
1412        // A word or line keeps the clip box all its glyphs share (#1150).
1413        if clips_differ(self.clip, clip) {
1414            self.clip = None;
1415        }
1416        if self.ltr && ltr {
1417            if space {
1418                self.text.push(' ');
1419            }
1420            self.text.push_str(text);
1421        } else {
1422            let sep = if space { " " } else { "" };
1423            self.text = format!("{text}{sep}{}", self.text);
1424            self.ltr = false;
1425        }
1426        let (mut ux, mut uy) = (self.q[2] - self.q[0], self.q[3] - self.q[1]);
1427        if ux.hypot(uy) <= 1e-9 {
1428            (ux, uy) = (q[2] - q[0], q[3] - q[1]);
1429        }
1430        let n = ux.hypot(uy);
1431        if n <= 1e-9 {
1432            return;
1433        }
1434        let (ux, uy) = (ux / n, uy / n);
1435        let (nx, ny) = (-uy, ux);
1436        let (mut u0, mut u1, mut n0, mut n1) = (
1437            f64::INFINITY,
1438            f64::NEG_INFINITY,
1439            f64::INFINITY,
1440            f64::NEG_INFINITY,
1441        );
1442        for k in 0..4 {
1443            for (x, y) in [(self.q[2 * k], self.q[2 * k + 1]), (q[2 * k], q[2 * k + 1])] {
1444                let (u, v) = (x * ux + y * uy, x * nx + y * ny);
1445                u0 = u0.min(u);
1446                u1 = u1.max(u);
1447                n0 = n0.min(v);
1448                n1 = n1.max(v);
1449            }
1450        }
1451        let pt = |u: f64, v: f64| (u * ux + v * nx, u * uy + v * ny);
1452        let (a, b, c, d) = (pt(u0, n0), pt(u1, n0), pt(u1, n1), pt(u0, n1));
1453        self.q = [a.0, a.1, b.0, b.1, c.0, c.1, d.0, d.1];
1454    }
1455
1456    fn into_cell(self, page_h: f32) -> TextCell {
1457        let xs = [self.q[0], self.q[2], self.q[4], self.q[6]];
1458        let ys = [self.q[1], self.q[3], self.q[5], self.q[7]];
1459        let (l, r) = (
1460            xs.iter().copied().fold(f64::INFINITY, f64::min),
1461            xs.iter().copied().fold(f64::NEG_INFINITY, f64::max),
1462        );
1463        let (b, t) = (
1464            ys.iter().copied().fold(f64::INFINITY, f64::min),
1465            ys.iter().copied().fold(f64::NEG_INFINITY, f64::max),
1466        );
1467        TextCell {
1468            text: self.text,
1469            l: l as f32,
1470            t: page_h - t as f32,
1471            r: r as f32,
1472            b: page_h - b as f32,
1473        }
1474    }
1475}
1476
1477/// Whether the page's producer draws its word spaces as glyphs: at least
1478/// half of the lines long enough to hold several words (eight glyphs or
1479/// more) carry a space glyph. Producers are consistent about it — a TeX or
1480/// Arbortext page has none, a Word or EUR-Lex page has them on every line —
1481/// so this tells a space-less line on a spaced page (a lone word) from the
1482/// cursor-move pages #921 is about.
1483fn page_draws_spaces(runs: &[Vec<RunCell>]) -> bool {
1484    let long = |r: &&Vec<RunCell>| r.iter().filter(|c| !c.space).count() >= 8;
1485    let lines = runs.iter().filter(long).count();
1486    let spaced = runs
1487        .iter()
1488        .filter(long)
1489        .filter(|r| r.iter().any(|c| c.space))
1490        .count();
1491    lines > 0 && 2 * spaced >= lines
1492}
1493
1494/// Whether one of the page's space glyphs sits in a gap between two
1495/// consecutive glyphs of `run` (its middle inside the gap along the run's
1496/// writing direction, most of its height within the band of the two glyphs
1497/// beside it). Such a line draws its
1498/// word spaces, only not between its letters: LibreOffice sets an Arabic
1499/// line's spaces first and then its letters in visual order, so the spaces
1500/// fall to the run open before them and this run has none of its own.
1501/// `spaces` are the page's space cells by the middle of their height.
1502fn spaces_drawn_apart(run: &[RunCell], spaces: &[(f64, &Cell)]) -> bool {
1503    let mut visible = run.iter().filter(|c| !c.space);
1504    let Some(first) = visible.next() else {
1505        return false;
1506    };
1507    // The spaces inside the run's extent; most runs have none.
1508    let (mut l, mut r, mut b, mut t) = bounds(first.cell);
1509    for c in visible.clone() {
1510        let (cl, cr, cb, ct) = bounds(c.cell);
1511        (l, r, b, t) = (l.min(cl), r.max(cr), b.min(cb), t.max(ct));
1512    }
1513    let (lo, hi) = (
1514        spaces.partition_point(|&(y, _)| y < b),
1515        spaces.partition_point(|&(y, _)| y <= t),
1516    );
1517    let inside: Vec<&Cell> = spaces[lo..hi]
1518        .iter()
1519        .map(|&(_, c)| c)
1520        .filter(|c| (l..=r).contains(&(0.5 * (c.b_l + c.b_r))))
1521        .collect();
1522    if inside.is_empty() {
1523        return false;
1524    }
1525    let (ux, uy) = (first.ux, first.uy);
1526    let along = |x: f64, y: f64| x * ux + y * uy;
1527    let across = |c: &Cell| {
1528        let v = [
1529            c.rx0 * -uy + c.ry0 * ux,
1530            c.rx1 * -uy + c.ry1 * ux,
1531            c.rx2 * -uy + c.ry2 * ux,
1532            c.rx3 * -uy + c.ry3 * ux,
1533        ];
1534        let lo = v.iter().copied().fold(f64::INFINITY, f64::min);
1535        let hi = v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
1536        (lo, hi)
1537    };
1538    // The open gaps, as (trailing edge, leading edge, the band of the two
1539    // glyphs beside the gap: an Arabic mark's box can be shorter than the
1540    // space after it).
1541    let mut gaps = Vec::new();
1542    let mut prev = first;
1543    for c in visible {
1544        let (lhs, rhs) = (prev.cell, c.cell);
1545        let tail = along(0.5 * (lhs.rx1 + lhs.rx2), 0.5 * (lhs.ry1 + lhs.ry2));
1546        let head = along(0.5 * (rhs.rx0 + rhs.rx3), 0.5 * (rhs.ry0 + rhs.ry3));
1547        if head > tail {
1548            let ((l0, l1), (r0, r1)) = (across(lhs), across(rhs));
1549            gaps.push((tail, head, (l0.min(r0), l1.max(r1))));
1550        }
1551        prev = c;
1552    }
1553    inside.iter().any(|c| {
1554        let mid = along(0.5 * (c.rx0 + c.rx2), 0.5 * (c.ry0 + c.ry2));
1555        let (s0, s1) = across(c);
1556        gaps.iter().any(|&(tail, head, (b0, b1))| {
1557            tail <= mid && mid <= head && s1.min(b1) - s0.max(b0) > 0.5 * (s1 - s0)
1558        })
1559    })
1560}
1561
1562/// docling-parse ≥ 7's contraction (`cells.h::contract`) over our char
1563/// cells, with the word threshold `gap` picks: the line runs, their words,
1564/// and the lines as the words joined by single spaces.
1565fn contract_runs(
1566    cells: &[Cell],
1567    gap: WordGap,
1568    page_h: f32,
1569    zero_advance_run: bool,
1570) -> (Vec<TextCell>, Vec<TextCell>) {
1571    // Line runs, in source order. Explicit spaces belong to the open run as
1572    // boundary markers and take no part in the geometry test.
1573    let mut runs: Vec<Vec<RunCell>> = Vec::new();
1574    for c in cells.iter().filter(|c| !c.text.is_empty()) {
1575        let rc = RunCell::new(c);
1576        if rc.space {
1577            match runs.last_mut() {
1578                Some(run) => run.push(rc),
1579                None => runs.push(vec![rc]),
1580            }
1581            continue;
1582        }
1583        // A clip border that cuts a glyph separates the lines (#1150,
1584        // docling-parse#443's `continues_line`); with the runs cut there,
1585        // no two glyphs of one run straddle one, and the word and gap tests
1586        // below need no clip test of their own.
1587        let starts = match runs.last().and_then(|r| r.iter().rev().find(|c| !c.space)) {
1588            Some(prev) => {
1589                clip_boundary(prev.cell, rc.cell) || !continues_line(prev, &rc, zero_advance_run)
1590            }
1591            None => runs.is_empty(),
1592        };
1593        if starts {
1594            runs.push(Vec::new());
1595        }
1596        runs.last_mut().expect("a run is open").push(rc);
1597    }
1598
1599    let (mut words_out, mut lines_out) = (Vec::new(), Vec::new());
1600    let page_spaced = page_draws_spaces(&runs);
1601    let mut spaces: Vec<(f64, &Cell)> = Vec::new();
1602    if page_spaced {
1603        spaces.extend(
1604            runs.iter()
1605                .flatten()
1606                .filter(|c| c.space)
1607                .map(|c| (0.5 * (c.cell.b_b + c.cell.b_t), c.cell)),
1608        );
1609        spaces.sort_by(|a, b| a.0.total_cmp(&b.0));
1610    }
1611    for run in &runs {
1612        // A line on a page whose producer draws its word spaces as glyphs is
1613        // judged like a line that draws them (below), even when it has none
1614        // of its own: a lone word in a table cell or a heading carries no
1615        // space glyph, and its only open gap is kerning — EUR-Lex's
1616        // `Offenlegungspf|lichten` at 0.22–0.25, cut by the line-local
1617        // threshold of 0.18 (docling-parse 7 cuts it too; #921). Not a line
1618        // whose spaces were drawn apart from its letters: it is no lone word,
1619        // and like docling-parse we infer its gap — under the cap its word
1620        // gaps of a third of an advance stayed glued (`علىشراء`).
1621        let has_spaces =
1622            run.iter().any(|c| c.space) || (page_spaced && !spaces_drawn_apart(run, &spaces));
1623        let tracked = tracked_gaps(run);
1624        // A line that draws its word spaces as glyphs marks its boundaries
1625        // itself; docling-parse 7 splits an unmarked gap there only above
1626        // 0.35 (`min(0.35, 1.0)`). A fixed factor keeps that floor: its job
1627        // is the space-less lines (#921), and below it a spaced line's
1628        // loosely kerned pairs fall apart — EUR-Lex's `f|l` at 0.24 read
1629        // `Verpf lichtungen` under 0.2.
1630        let threshold = match gap {
1631            WordGap::Factor(f) if has_spaces => f.max(0.35),
1632            WordGap::Factor(f) => f,
1633            _ => (if has_spaces {
1634                1.0
1635            } else {
1636                infer_word_gap(run, &tracked)
1637            })
1638            .min(0.35),
1639        };
1640        let mut words: Vec<Agg> = Vec::new();
1641        let mut prev: Option<&RunCell> = None;
1642        let mut boundary = false;
1643        for (i, c) in run.iter().enumerate() {
1644            if c.space {
1645                boundary = true;
1646                continue;
1647            }
1648            let mut starts = words.is_empty() || boundary;
1649            let mut glued = false;
1650            // A TOC leader may omit the boundary before its first dot while
1651            // spacing every later one: keep that dot with the leader.
1652            if !starts
1653                && c.cell.text == "."
1654                && i + 4 < run.len()
1655                && run[i + 1].space
1656                && run[i + 2].cell.text == "."
1657                && run[i + 3].space
1658                && run[i + 4].cell.text == "."
1659                && prev.is_some_and(|p| p.cell.text != ".")
1660            {
1661                starts = true;
1662            }
1663            if let (false, Some(p)) = (starts, prev) {
1664                let shifted = !baselines_compatible(p, c);
1665                let gapped = !tracked[i] && normalized_gap(p, c) > threshold;
1666                starts = shifted || gapped;
1667                // A baseline shift with the glyphs touching, inside a
1668                // bracket: docling-parse starts a word
1669                // (`word_baselines_compatible`) and its line text then reads
1670                // `Richtlinie 2003/71/EG ( 1 )` for a raised footnote marker
1671                // where the page shows `(1)` and pdftotext / pdfium read it
1672                // so (#992). The word stays its own cell; the line text
1673                // joins it as the page does. Only after an opening bracket
1674                // or before a closing one: elsewhere docling's space is the
1675                // more useful reading — `SynthTabNet 1 .`, `1 https://…`,
1676                // `상해 1) 나`, the `1 /4` fraction — and joining them cost
1677                // five groundtruth files when this rule had no bracket test.
1678                let opens = |s: &str| matches!(s.chars().last(), Some('(' | '[' | '{'));
1679                let closes = |s: &str| matches!(s.chars().next(), Some(')' | ']' | '}'));
1680                glued = shifted
1681                    && !gapped
1682                    && (words.last().is_some_and(|w| opens(&w.text)) || closes(&c.cell.text));
1683            }
1684            if starts {
1685                words.push(Agg::of(c.cell, glued));
1686            } else {
1687                let q = [
1688                    c.cell.rx0, c.cell.ry0, c.cell.rx1, c.cell.ry1, c.cell.rx2, c.cell.ry2,
1689                    c.cell.rx3, c.cell.ry3,
1690                ];
1691                words.last_mut().expect("a word is open").append(
1692                    &c.cell.text,
1693                    c.cell.ltr,
1694                    &q,
1695                    false,
1696                    c.cell.clip,
1697                );
1698            }
1699            prev = Some(c);
1700            boundary = false;
1701        }
1702        let mut it = words.into_iter();
1703        let Some(first) = it.next() else {
1704            continue;
1705        };
1706        let mut line = Agg {
1707            text: first.text.clone(),
1708            ltr: first.ltr,
1709            q: first.q,
1710            glued: false,
1711            font: first.font,
1712            clip: first.clip,
1713        };
1714        words_out.push(first);
1715        for w in it {
1716            line.append(&w.text, w.ltr, &w.q, !w.glued, w.clip);
1717            words_out.push(w);
1718        }
1719        lines_out.push(line);
1720    }
1721    let cells = |aggs: Vec<Agg>| {
1722        let keys: Vec<_> = aggs
1723            .iter()
1724            .map(|a| (a.text.as_str(), a.font, a.ltr, a.q, a.clip))
1725            .collect();
1726        let keep = overlapping_copies(&keys);
1727        aggs.into_iter()
1728            .zip(keep)
1729            .filter_map(|(a, k)| k.then(|| a.into_cell(page_h)))
1730            .collect::<Vec<_>>()
1731    };
1732    (cells(lines_out), cells(words_out))
1733}
1734
1735#[cfg(test)]
1736mod tests {
1737    use super::*;
1738
1739    fn glyph(ch: char, l: f32, r: f32) -> Glyph {
1740        Glyph {
1741            ch,
1742            l,
1743            b: 100.0,
1744            r,
1745            t: 110.0,
1746            ll: l,
1747            lb: 98.0,
1748            lr: r,
1749            lt: 110.0,
1750            font: 0,
1751            quad: None,
1752            pen: None,
1753            math_font: false,
1754            invisible: false,
1755            spaced: false,
1756            clip: None,
1757            exact: 0,
1758        }
1759    }
1760
1761    /// The exact-overprint pass compares quads at full precision (#1151):
1762    /// two glyphs whose `f32` boxes are equal but whose `f64` quads differ
1763    /// (`newspaper-00`'s column drawn again 1e-5 pt off, other lines
1764    /// between the copies) are two glyphs, as in docling-parse; a
1765    /// bit-identical redraw is one.
1766    #[test]
1767    fn exact_overprints_compare_at_full_precision() {
1768        let at = |ch: char, y: f32, exact: u64| Glyph {
1769            b: y + 2.0,
1770            lb: y,
1771            t: y + 12.0,
1772            lt: y + 12.0,
1773            exact,
1774            ..glyph(ch, 100.0, 106.0)
1775        };
1776        let n = |e: u64| {
1777            build_cells(
1778                &[at('e', 100.0, 1), at('x', 80.0, 9), at('e', 100.0, e)],
1779                true,
1780            )
1781            .iter()
1782            .filter(|c| c.text == "e")
1783            .count()
1784        };
1785        assert_eq!(n(2), 2);
1786        assert_eq!(n(1), 1);
1787    }
1788
1789    /// Tight-set Latin (a table cell in a born-digital manual): the gap between
1790    /// `MODE` and `to` (1.84 pt) is under the 0.33 × average-width word gate (2.0 pt), so
1791    /// only the space glyph between them keeps the words apart. docling-parse
1792    /// erases spaces after the word contraction, not before.
1793    #[test]
1794    fn space_glyph_separates_tight_words() {
1795        let glyphs = [
1796            glyph('M', 137.66, 143.74),
1797            glyph('O', 143.74, 149.82),
1798            glyph('D', 149.82, 155.90),
1799            glyph('E', 155.90, 161.98),
1800            glyph(' ', 161.84, 164.09),
1801            glyph('t', 163.82, 166.60),
1802            glyph('o', 166.60, 171.60),
1803        ];
1804        let (lines, words) = line_and_word_cells(&glyphs, 792.0, true);
1805        let words: Vec<&str> = words.iter().map(|w| w.text.as_str()).collect();
1806        assert_eq!(words, ["MODE", "to"]);
1807        assert_eq!(lines.len(), 1);
1808        assert_eq!(lines[0].text, "MODE to");
1809    }
1810
1811    /// #609: a chart's y-axis ticks set one under another at the same x (each
1812    /// tick placed by its own `cm`, same `Tm`) are six line cells with their
1813    /// own boxes, as in docling-parse — not one `345678` cell with the first
1814    /// tick's box. A ligature decomposed at one box still recomposes.
1815    #[test]
1816    fn stacked_glyphs_at_one_x_stay_separate_cells() {
1817        let at = |ch: char, b: f32| Glyph {
1818            lb: b,
1819            lt: b + 10.0,
1820            b,
1821            t: b + 10.0,
1822            ..glyph(ch, 98.0, 103.0)
1823        };
1824        let ticks: Vec<Glyph> = "345678"
1825            .chars()
1826            .enumerate()
1827            .map(|(k, ch)| at(ch, 316.0 + 25.92 * k as f32))
1828            .collect();
1829        let lines = line_cells(&ticks, 792.0, true);
1830        let texts: Vec<&str> = lines.iter().map(|c| c.text.as_str()).collect();
1831        assert_eq!(texts, ["3", "4", "5", "6", "7", "8"]);
1832        assert!(lines.windows(2).all(|w| w[0].t > w[1].t));
1833
1834        let lig = [glyph('f', 10.0, 16.0), glyph('i', 10.0, 16.0)];
1835        let lines = line_cells(&lig, 792.0, true);
1836        assert_eq!(lines.len(), 1);
1837        assert_eq!(lines[0].text, "fi");
1838    }
1839
1840    /// The returned vectors own no more than their cells. Collecting straight
1841    /// from the per-glyph `Cell` buffer reused its allocation (std's in-place
1842    /// collect), so a page kept ~4 slots per *glyph* — on a dense table page,
1843    /// 30× the cells' size, for every page the text-layer path held.
1844    #[test]
1845    fn cells_do_not_keep_the_glyph_buffer() {
1846        // Ten rows of `777 777 …`: abutting glyphs, words split by space glyphs.
1847        let glyphs: Vec<Glyph> = (0..400)
1848            .map(|i| {
1849                let x = (i % 40) as f32 * 6.0;
1850                let ch = if i % 4 == 3 { ' ' } else { '7' };
1851                let mut g = glyph(ch, x, x + 6.0);
1852                let row = (i / 40) as f32 * 14.0;
1853                (g.b, g.t, g.lb, g.lt) = (100.0 + row, 110.0 + row, 98.0 + row, 110.0 + row);
1854                g
1855            })
1856            .collect();
1857        let (lines, words) = line_and_word_cells(&glyphs, 792.0, true);
1858        assert_eq!((lines.len(), words.len()), (10, 100));
1859        assert_eq!(lines.capacity(), lines.len());
1860        assert_eq!(words.capacity(), words.len());
1861    }
1862
1863    /// #921, page 8 of the reporter's collective agreement: `und dem` sits in
1864    /// a second font resource between runs of the body font, word gaps are
1865    /// cursor moves (no space glyph). Glyph boxes as the parser reads them.
1866    fn und_dem_line() -> Vec<Glyph> {
1867        let at = |ch: char, l: f32, r: f32, font: u64| Glyph {
1868            ch,
1869            l,
1870            b: 682.056,
1871            r,
1872            t: 691.05,
1873            ll: l,
1874            lb: 682.056,
1875            lr: r,
1876            lt: 691.05,
1877            font,
1878            quad: None,
1879            pen: None,
1880            math_font: false,
1881            invisible: false,
1882            spaced: false,
1883            clip: None,
1884            exact: 0,
1885        };
1886        let mut g = Vec::new();
1887        let mut run = |text: &str, edges: &[f32], font: u64| {
1888            for (i, ch) in text.chars().enumerate() {
1889                g.push(at(ch, edges[i], edges[i + 1], font));
1890            }
1891        };
1892        run(
1893            "schaft",
1894            &[
1895                328.976, 333.216, 338.572, 344.325, 350.486, 353.920, 357.248,
1896            ],
1897            1,
1898        );
1899        run("und", &[359.261, 365.121, 370.875, 377.035], 2);
1900        run("dem", &[378.990, 385.151, 390.701, 399.287], 2);
1901        run("Öst", &[401.214, 409.092, 413.332, 416.660], 1);
1902        g
1903    }
1904
1905    #[test]
1906    fn legacy_rule_keeps_the_borderline_und_dem_glued() {
1907        // The baselines' rule: the cell restarts at the font change, so the
1908        // threshold is 0.33 × the mean advance of `und` alone (1.9553 pt)
1909        // and the 1.9550 pt gap stays inside the word.
1910        let (lines, words) = line_and_word_cells(&und_dem_line(), 792.0, true);
1911        assert!(lines.iter().any(|c| c.text == "unddem"), "{lines:?}");
1912        assert!(words.iter().any(|c| c.text == "unddem"), "{words:?}");
1913    }
1914
1915    #[test]
1916    fn line_local_word_gaps_split_und_dem() {
1917        for gap in [WordGap::Adaptive, WordGap::Factor(0.2)] {
1918            let (lines, words) = line_and_word_cells_with(&und_dem_line(), 792.0, true, gap);
1919            let texts: Vec<&str> = lines.iter().map(|c| c.text.as_str()).collect();
1920            assert_eq!(texts, ["schaft und dem Öst"], "{gap:?}");
1921            let texts: Vec<&str> = words.iter().map(|c| c.text.as_str()).collect();
1922            assert_eq!(texts, ["schaft", "und", "dem", "Öst"], "{gap:?}");
1923            // The word boxes are the glyphs' own extent.
1924            assert!((words[1].l - 359.261).abs() < 1e-3 && (words[1].r - 377.035).abs() < 1e-3);
1925        }
1926        // A factor above the normalized gaps (0.234 … 0.438) keeps them all.
1927        let (lines, _) =
1928            line_and_word_cells_with(&und_dem_line(), 792.0, true, WordGap::Factor(0.5));
1929        assert_eq!(lines[0].text, "schaftunddemÖst");
1930    }
1931
1932    #[test]
1933    fn a_superscript_attaches_by_pen_origin_and_math_face() {
1934        // `Lysak` at 10 pt, then `[0000` at 7 pt raised `rise` pt with no gap.
1935        // The baseline test reads the pens' origins and font sizes, as
1936        // docling-parse 7 does (`pen: None` falls back to the loose boxes).
1937        let at = |ch: char, l: f32, y: f32, size: f32, math: bool, pen: bool| Glyph {
1938            lb: y - 0.2 * size,
1939            lt: y + 0.8 * size,
1940            b: y - 0.2 * size,
1941            t: y + 0.8 * size,
1942            pen: pen.then_some([l, y, size]),
1943            math_font: math,
1944            ..glyph(ch, l, l + 0.5 * size)
1945        };
1946        let line = |rise: f32, math: bool, pen: bool| {
1947            let mut g: Vec<Glyph> = "Lysak"
1948                .chars()
1949                .enumerate()
1950                .map(|(k, ch)| at(ch, 100.0 + 5.0 * k as f32, 600.0, 10.0, math, pen))
1951                .collect();
1952            g.extend(
1953                "[0000"
1954                    .chars()
1955                    .enumerate()
1956                    .map(|(k, ch)| at(ch, 125.0 + 3.5 * k as f32, 600.0 + rise, 7.0, math, pen)),
1957            );
1958            let (lines, words) = line_and_word_cells_with(&g, 792.0, true, WordGap::Adaptive);
1959            (
1960                lines[0].text.clone(),
1961                words.iter().map(|w| w.text.clone()).collect::<Vec<_>>(),
1962            )
1963        };
1964        let one = |s: &str| (s.to_string(), vec![s.to_string()]);
1965        let two = |s: &str| {
1966            (
1967                s.to_string(),
1968                vec!["Lysak".to_string(), "[0000".to_string()],
1969            )
1970        };
1971        // 2305.03393v1's ORCID: 3.6 pt up is more than 0.35 × 7 pt, a new word
1972        // unless it is a local attachment, which a TeX face (`cmr`) makes it.
1973        // Not a math face: two words, spaced — the raised run *opens* a
1974        // bracket, which is not the #992 join (that is for a run after an
1975        // opening bracket or before a closing one).
1976        assert_eq!(line(3.6, true, true), one("Lysak[0000"));
1977        assert_eq!(line(3.6, false, true), two("Lysak [0000"));
1978        // 2 pt up: on the pens 2.0 ≤ 0.35 × 7, one word; the boxes' bottoms
1979        // differ by the descents too (2.6 pt), which read it as two.
1980        assert_eq!(line(2.0, false, true), one("Lysak[0000"));
1981        assert_eq!(line(2.0, false, false), two("Lysak [0000"));
1982    }
1983
1984    /// #992: a raised footnote marker between parentheses — `(`, a 6.8 pt
1985    /// `1` 3.5 pt up, `)` — is three word cells (the baseline rule) but the
1986    /// line reads `(1)` as the page does; with a real gap before the marker
1987    /// (`EG (1)`) the space is the gap's, as before. The same raised `1`
1988    /// right after a letter keeps docling's space (`EG 1`): only a bracket
1989    /// joins.
1990    #[test]
1991    fn a_touching_superscript_joins_the_line_text_inside_brackets_only() {
1992        let at = |ch: char, l: f32, w: f32, y: f32, size: f32| Glyph {
1993            lb: y - 0.2 * size,
1994            lt: y + 0.8 * size,
1995            b: y - 0.2 * size,
1996            t: y + 0.8 * size,
1997            pen: Some([l, y, size]),
1998            ..glyph(ch, l, l + w)
1999        };
2000        let g = [
2001            at('E', 100.0, 6.0, 600.0, 10.5),
2002            at('G', 106.0, 6.9, 600.0, 10.5),
2003            at('(', 115.3, 3.2, 600.0, 10.5),
2004            at('1', 118.5, 3.1, 603.5, 6.8),
2005            at(')', 121.6, 3.2, 600.0, 10.5),
2006            at('e', 127.2, 5.0, 600.0, 10.5),
2007        ];
2008        let (lines, words) = line_and_word_cells_with(&g, 792.0, true, WordGap::Adaptive);
2009        assert_eq!(lines[0].text, "EG (1) e");
2010        let words: Vec<&str> = words.iter().map(|w| w.text.as_str()).collect();
2011        assert_eq!(words, ["EG", "(", "1", ")", "e"]);
2012        // `EG` then the raised `1` touching the `G`: docling's `EG 1`.
2013        let g = [
2014            at('E', 100.0, 6.0, 600.0, 10.5),
2015            at('G', 106.0, 6.9, 600.0, 10.5),
2016            at('1', 112.9, 3.1, 603.5, 6.8),
2017        ];
2018        let (lines, _) = line_and_word_cells_with(&g, 792.0, true, WordGap::Adaptive);
2019        assert_eq!(lines[0].text, "EG 1");
2020    }
2021
2022    #[test]
2023    fn a_factor_keeps_docling_parse_s_floor_on_lines_with_space_glyphs() {
2024        // `Verpf` + `lichtungen` 0.6 pt apart (0.24 of the flanking advances)
2025        // on a line whose word spaces are glyphs: below the 0.35 floor
2026        // docling-parse 7 keeps for such lines, so it is not a boundary even
2027        // under a factor of 0.2. The same gap on a space-less line splits.
2028        let mut g = Vec::new();
2029        let mut x = 100.0f32;
2030        let put = |g: &mut Vec<Glyph>, s: &str, x: &mut f32| {
2031            for ch in s.chars() {
2032                g.push(glyph(ch, *x, *x + 2.5));
2033                *x += 2.5;
2034            }
2035        };
2036        put(&mut g, "Die", &mut x);
2037        g.push(glyph(' ', x, x + 2.5));
2038        x += 2.5;
2039        put(&mut g, "Verpf", &mut x);
2040        x += 0.6;
2041        put(&mut g, "lichtungen", &mut x);
2042        let (lines, _) = line_and_word_cells_with(&g, 792.0, true, WordGap::Factor(0.2));
2043        assert_eq!(lines[0].text, "Die Verpflichtungen");
2044        let spaceless: Vec<Glyph> = g.into_iter().filter(|c| c.ch != ' ').collect();
2045        let (lines, _) = line_and_word_cells_with(&spaceless, 792.0, true, WordGap::Factor(0.2));
2046        assert_eq!(lines[0].text, "Die Verpf lichtungen");
2047    }
2048
2049    #[test]
2050    fn right_to_left_glyphs_in_visual_order_stay_one_line() {
2051        // Arabic drawn in visual order (the pen moves left to right, as most
2052        // producers store it): the gap runs along the pen, not against the
2053        // script — reversed, every glyph pair read as a step back of two
2054        // advances and each glyph became a line of its own.
2055        let mut g = Vec::new();
2056        let mut x = 100.0f32;
2057        for (k, word) in [
2058            "\u{0631}\u{0627}\u{0632}\u{0627}\u{0628}",
2059            "\u{0631}\u{062f}",
2060        ]
2061        .iter()
2062        .enumerate()
2063        {
2064            if k > 0 {
2065                x += 3.0;
2066            }
2067            for ch in word.chars() {
2068                g.push(glyph(ch, x, x + 5.0));
2069                x += 5.0;
2070            }
2071        }
2072        for gap in [WordGap::Adaptive, WordGap::Factor(0.2)] {
2073            let (lines, words) = line_and_word_cells_with(&g, 792.0, true, gap);
2074            assert_eq!(
2075                lines.len(),
2076                1,
2077                "{gap:?}: {:?}",
2078                lines.iter().map(|c| &c.text).collect::<Vec<_>>()
2079            );
2080            assert_eq!(words.len(), 2, "{gap:?}");
2081        }
2082    }
2083
2084    /// The line cells of `glyphs` under the adaptive rule, with
2085    /// `DOCLING_RS_PDF_ZERO_ADVANCE_RUN` as given.
2086    fn line_texts(glyphs: &[Glyph], zero_advance_run: bool) -> Vec<String> {
2087        line_and_word_cells_cut(glyphs, 792.0, true, WordGap::Adaptive, zero_advance_run)
2088            .0
2089            .into_iter()
2090            .map(|c| c.text)
2091            .collect()
2092    }
2093
2094    /// Glyphs set one after the other from x = 100, each with its advance.
2095    fn set(chars: &[(char, f32)]) -> Vec<Glyph> {
2096        let mut x = 100.0f32;
2097        chars
2098            .iter()
2099            .map(|&(ch, w)| {
2100                let g = glyph(ch, x, x + w);
2101                x += w;
2102                g
2103            })
2104            .collect()
2105    }
2106
2107    #[test]
2108    fn a_zero_advance_glyph_cuts_the_line_only_when_asked() {
2109        // An Arabic mark drawn before its base, as LibreOffice writes a
2110        // cluster: the mark has no advance, so docling-parse finds no
2111        // trailing edge for the base to face and starts a run there — a
2112        // word in two cells, which its line sort then sets apart. We keep
2113        // the line, and cut it as docling-parse does under the knob.
2114        let line = |mark_advance: f32| {
2115            set(&[
2116                ('\u{0627}', 3.0),
2117                ('\u{064b}', mark_advance),
2118                ('\u{0645}', 6.0),
2119                ('\u{0626}', 3.0),
2120                ('\u{0627}', 3.0),
2121                ('\u{062f}', 5.0),
2122            ])
2123        };
2124        let whole = "\u{062f}\u{0627}\u{0626}\u{0645}\u{064b}\u{0627}";
2125        assert_eq!(line_texts(&line(0.0), false), [whole]);
2126        assert_eq!(
2127            line_texts(&line(0.0), true),
2128            ["\u{064b}\u{0627}", "\u{062f}\u{0627}\u{0626}\u{0645}"]
2129        );
2130        // With any advance at all the mark is no cut for either.
2131        assert_eq!(line_texts(&line(0.5), true), [whole]);
2132    }
2133
2134    #[test]
2135    fn zero_advance_glyphs_of_other_scripts_stay_in_their_line() {
2136        // A decomposed Latin accent (`e` + U+0301, the mark with no advance):
2137        // one line by default; under the knob the line breaks after the
2138        // accent, as in docling-parse.
2139        let accent = set(&[
2140            ('c', 5.0),
2141            ('a', 5.0),
2142            ('f', 3.0),
2143            ('e', 5.0),
2144            ('\u{0301}', 0.0),
2145            ('s', 4.0),
2146        ]);
2147        assert_eq!(line_texts(&accent, false), ["cafe\u{0301}s"]);
2148        assert_eq!(line_texts(&accent, true), ["cafe\u{0301}", "s"]);
2149        // A font whose `/Widths` are all zero, every glyph on the one spot:
2150        // `build_cells` already joins them into one cell (glyphs sharing a
2151        // box are a decomposed ligature), so the line runs never see a
2152        // zero-advance pair and the knob changes nothing.
2153        let one_spot = set(&[('a', 0.0), ('b', 0.0), ('c', 0.0)]);
2154        assert_eq!(line_texts(&one_spot, false), ["abc"]);
2155        assert_eq!(line_texts(&one_spot, true), ["abc"]);
2156        // The same widths with the glyphs set apart by `TJ` kerning: each
2157        // a cell of no advance, so here the line runs do see the pairs. By
2158        // default the x-axis fallback keeps one line (three words: with no
2159        // advance, a 3 pt gap is measured against half the glyph height);
2160        // under the knob every glyph starts a run, as docling-parse has it —
2161        // which is why the knob stays off.
2162        let set_apart = vec![
2163            glyph('a', 100.0, 100.0),
2164            glyph('b', 103.0, 103.0),
2165            glyph('c', 106.0, 106.0),
2166        ];
2167        assert_eq!(line_texts(&set_apart, false), ["a b c"]);
2168        assert_eq!(line_texts(&set_apart, true), ["a", "b", "c"]);
2169    }
2170
2171    #[test]
2172    fn letter_spacing_stays_one_word_under_the_adaptive_rule() {
2173        // Sperrsatz: every letter 1.5 pt apart, the words 6 pt apart. The
2174        // line's gaps form two clusters, so the letters stay together.
2175        let mut g = Vec::new();
2176        let mut x = 100.0f32;
2177        for (k, word) in ["Allgemeine", "Bestimmungen"].iter().enumerate() {
2178            if k > 0 {
2179                x += 6.0;
2180            }
2181            for ch in word.chars() {
2182                g.push(glyph(ch, x, x + 5.0));
2183                x += 5.0 + 1.5;
2184            }
2185            x -= 1.5;
2186        }
2187        let (lines, _) = line_and_word_cells_with(&g, 792.0, true, WordGap::Adaptive);
2188        assert_eq!(lines[0].text, "Allgemeine Bestimmungen");
2189    }
2190
2191    /// Glyphs 2.5 pt wide on a line at `y`, each `(text, gap before)` piece
2192    /// set after the previous one; `' '` pieces are space glyphs.
2193    fn set_line(pieces: &[(&str, f32)], y: f32) -> Vec<Glyph> {
2194        let mut g = Vec::new();
2195        let mut x = 100.0f32;
2196        for (text, gap) in pieces {
2197            x += gap;
2198            for ch in text.chars() {
2199                g.push(Glyph {
2200                    b: y,
2201                    t: y + 10.0,
2202                    lb: y - 2.0,
2203                    lt: y + 10.0,
2204                    ..glyph(ch, x, x + 2.5)
2205                });
2206                x += 2.5;
2207            }
2208        }
2209        g
2210    }
2211
2212    #[test]
2213    fn one_wide_gap_does_not_raise_the_line_s_word_gap() {
2214        // #921, EVU p. 3: word gaps of 0.32 advances in tight justified text
2215        // and one gap of 3.2 before a tab stop. Unclipped, the wide gap is
2216        // the high cluster alone, the midpoint caps at 0.35 and the line
2217        // reads `jedochwerdenweiterlaufende`.
2218        let g = set_line(
2219            &[
2220                ("jedoch", 0.0),
2221                ("werden", 0.8),
2222                ("weiterlaufende", 0.8),
2223                ("Quartierkosten", 8.0),
2224            ],
2225            600.0,
2226        );
2227        let (_, words) = line_and_word_cells_with(&g, 792.0, true, WordGap::Adaptive);
2228        let texts: Vec<&str> = words.iter().map(|c| c.text.as_str()).collect();
2229        assert_eq!(
2230            texts,
2231            ["jedoch", "werden", "weiterlaufende", "Quartierkosten"]
2232        );
2233    }
2234
2235    #[test]
2236    fn a_lone_word_on_a_page_that_draws_spaces_keeps_its_kerning() {
2237        // #921, EUR-Lex: `Offenlegungspf` + `lichten` 0.8 pt apart (0.32
2238        // advances) in a one-word table cell. On a page whose lines carry
2239        // space glyphs the gap is kerning, not a word boundary; on a
2240        // space-less page (TeX, Arbortext) the same line splits.
2241        let lone = || set_line(&[("Offenlegungspf", 0.0), ("lichten", 0.8)], 500.0);
2242        let spaced = |y| {
2243            set_line(
2244                &[
2245                    ("Die", 0.0),
2246                    (" ", 0.0),
2247                    ("Taxonomie", 0.0),
2248                    (" ", 0.0),
2249                    ("gilt", 0.0),
2250                ],
2251                y,
2252            )
2253        };
2254        let mut page = lone();
2255        page.extend(spaced(600.0));
2256        page.extend(spaced(620.0));
2257        let texts = |g: &[Glyph]| {
2258            let (lines, _) = line_and_word_cells_with(g, 792.0, true, WordGap::Adaptive);
2259            lines.into_iter().map(|c| c.text).collect::<Vec<_>>()
2260        };
2261        assert!(texts(&page).contains(&"Offenlegungspflichten".to_string()));
2262        assert_eq!(texts(&lone()), ["Offenlegungspf lichten"]);
2263    }
2264
2265    #[test]
2266    fn a_line_whose_spaces_are_drawn_before_its_letters_infers_its_gap() {
2267        // LibreOffice's Arabic: the line's space glyphs first, then its
2268        // letters in visual order, the words 1.7 pt apart (0.34 advances).
2269        // The spaces fall to the run before, so the Arabic run has none of
2270        // its own; judged as a lone word on a spaced page, the 0.35 cap
2271        // glued every word, where docling-parse infers the line's gap.
2272        let mut page = set_line(&[("The", 0.0), (" ", 0.0), ("manual", 0.0)], 600.0);
2273        page.extend(set_line(
2274            &[("For", 0.0), (" ", 0.0), ("safety", 0.0)],
2275            620.0,
2276        ));
2277        let words = ["نشكرك", "على", "شراء"];
2278        let (mut spaces, mut letters) = (Vec::new(), Vec::new());
2279        let mut x = 100.0f32;
2280        for (k, word) in words.iter().rev().enumerate() {
2281            if k > 0 {
2282                spaces.push(glyph(' ', x, x + 1.7));
2283                x += 1.7;
2284            }
2285            for ch in word.chars().rev() {
2286                letters.push(glyph(ch, x, x + 5.0));
2287                x += 5.0;
2288            }
2289        }
2290        page.extend(spaces);
2291        page.extend(letters);
2292        let (lines, _) = line_and_word_cells_with(&page, 792.0, true, WordGap::Adaptive);
2293        let texts: Vec<&str> = lines.iter().map(|c| c.text.as_str()).collect();
2294        assert!(texts.contains(&"نشكرك على شراء"), "{texts:?}");
2295    }
2296
2297    #[test]
2298    fn a_lone_word_beside_another_line_s_space_keeps_its_kerning() {
2299        // #921's one-word cell on a spaced page, with a space glyph of
2300        // another line drawn near it but in none of its gaps: after the
2301        // word's end on its own height, or under its kerning gap with half
2302        // its height below the line. The word stays whole. The same glyph in
2303        // the gap, on the line, makes the line one whose spaces were drawn
2304        // apart, and its gap is inferred as docling-parse infers it.
2305        let spaced = |y| {
2306            set_line(
2307                &[
2308                    ("Die", 0.0),
2309                    (" ", 0.0),
2310                    ("Taxonomie", 0.0),
2311                    (" ", 0.0),
2312                    ("gilt", 0.0),
2313                ],
2314                y,
2315            )
2316        };
2317        // `Offenlegungspf` ends at 135, `lichten` starts at 135.8.
2318        let lone = || set_line(&[("Offenlegungspf", 0.0), ("lichten", 0.8)], 500.0);
2319        let space = |l: f32, r: f32, y: f32| Glyph {
2320            b: y,
2321            t: y + 10.0,
2322            lb: y - 2.0,
2323            lt: y + 10.0,
2324            ..glyph(' ', l, r)
2325        };
2326        let line_with = |stray: Glyph| {
2327            let mut page = spaced(600.0);
2328            page.extend(spaced(620.0));
2329            page.push(stray);
2330            page.extend(lone());
2331            let (lines, _) = line_and_word_cells_with(&page, 792.0, true, WordGap::Adaptive);
2332            lines
2333                .into_iter()
2334                .map(|c| c.text)
2335                .find(|t| t.starts_with("Offen"))
2336                .expect("the lone word's line")
2337        };
2338        assert_eq!(
2339            line_with(space(154.0, 155.7, 500.0)),
2340            "Offenlegungspflichten"
2341        );
2342        assert_eq!(
2343            line_with(space(135.0, 135.8, 494.0)),
2344            "Offenlegungspflichten"
2345        );
2346        assert_eq!(
2347            line_with(space(135.0, 135.8, 500.0)),
2348            "Offenlegungspf lichten"
2349        );
2350    }
2351
2352    #[test]
2353    fn a_space_drawn_apart_is_judged_on_both_glyphs_beside_it() {
2354        // A raised mark's box (104–110) is half the height of the space
2355        // after it (98–110): on the mark's band alone the space was not on
2356        // the line; with the letter after the gap it is.
2357        let mark = Glyph {
2358            lb: 104.0,
2359            ..glyph('\u{064b}', 100.0, 103.0)
2360        };
2361        let cells = build_cells(
2362            &[
2363                mark,
2364                glyph('\u{0644}', 105.0, 110.0),
2365                glyph(' ', 103.2, 104.8),
2366            ],
2367            true,
2368        );
2369        let run: Vec<RunCell> = cells[..2].iter().map(RunCell::new).collect();
2370        let spaces = [(0.5 * (cells[2].b_b + cells[2].b_t), &cells[2])];
2371        assert!(spaces_drawn_apart(&run, &spaces));
2372    }
2373
2374    #[test]
2375    fn word_gap_spellings() {
2376        assert_eq!(WordGap::parse("adaptive"), Ok(WordGap::Adaptive));
2377        assert_eq!(WordGap::parse(" Legacy "), Ok(WordGap::Legacy));
2378        assert_eq!(WordGap::parse("0.2"), Ok(WordGap::Factor(0.2)));
2379        for bad in ["0", "-1", "5", "nan", "wide"] {
2380            assert!(WordGap::parse(bad).is_err(), "{bad}");
2381        }
2382    }
2383}