pdfsift 0.1.0

PDF to structured Markdown for LLM agents. Heuristics only: no AI model, no network.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
//! Table detection (stage 6, achados 002, 006 and 013): finds the blocks of a page
//! that form a table and rebuilds its grid, or, when the grid is uncertain, keeps the
//! text laid out by x position so a reader still sees the alignment.
//!
//! A pure function over the grouped [`Page`]: no PDFium here.
//!
//! 1. **Candidates.** Grouping (stage 3) already puts table cells in different blocks:
//!    cell gaps are wider than `LINE_SPLIT_GAP` (achado 002), except LibreOffice's
//!    right-aligned numbers 0.35 em before the next column. So a table shows up as
//!    blocks *side by side* (lines of two blocks on one row), which prose never does:
//!    a justified line is one line of one block (`JUSTIFIED_RATIO`) and page columns are
//!    separate regions. Side-by-side blocks are linked into groups, nearby groups are
//!    merged and blocks inside the group's extent are absorbed (a centred rowspan cell).
//! 2. **Columns** are the x-ranges empty on every physical row of the candidate (the
//!    empty-stripe rule, achado 002), at least [`MIN_GUTTER`] wide.
//! 3. **Logical rows** (achado 006, finding 7): when cells wrap with a line pitch
//!    clearly smaller than the row pitch (Typst, Chrome), cells are chained per column
//!    and rows are the vertical overlaps of the cells; otherwise (LaTeX, LibreOffice:
//!    same pitch) every physical row is a row, and a row is a continuation of the one
//!    above when its first column is empty, it only has text under cells of the row above
//!    and none of its cells is a number (achado 006, finding 5).
//! 4. **Validation**, variant C of achado 006: a column boundary needs [`MIN_BOTH`]
//!    rows with text on both sides and one of the two columns aligned (left, right or
//!    centre) on an inner edge. Alignment at the block's outer margins alone (first
//!    column only left, last column only right) is a river in justified text.
//! 5. A **grid** is emitted only when no boundary was rejected and no cell holds two
//!    words further apart than `LINE_SPLIT_GAP` on one line (a boundary the empty-stripe
//!    rule missed, e.g. under a column-spanning cell). Otherwise the candidate is a
//!    **layout** (pre-formatted text by x position, like `pdftotext -layout`).

use crate::layout::group::{BASELINE_TOL, LINE_SPLIT_GAP};
use crate::layout::{Block, Page, Word};

/// Vertical core of a line for the side-by-side test, in em above and below the
/// baseline (0.9 em in all). Loose boxes cannot be used: LaTeX's are 1.41 em tall and
/// overlap the next line (achado 002, finding 7). Row pitches are 1.15 em (LibreOffice,
/// 13.8/12) or more, so the cores of two rows never overlap, while a cell centred half a
/// line off its neighbours (Chrome, 0.56 em; LaTeX rowspan, 0.60 em: achado 006,
/// finding 7) still overlaps them by ≥ 0.3 em.
pub const CORE_ASCENT: f32 = 0.7;
pub const CORE_DESCENT: f32 = 0.2;

/// Minimum vertical overlap of two line cores (em of the smaller size) to call them
/// one row.
pub const ROW_OVERLAP: f32 = 0.1;

/// Two side-by-side groups are one table when the vertical gap between their cores is
/// at most this (em). Single-line rows of a padded table are separate groups. Measured
/// on the corpus (achado 013): groups of one table are 0.18–0.85 em apart (Chrome
/// 0.60–0.79, Typst 0.85, LaTeX 0.30–0.80, LibreOffice 0.25, Word 0.47–0.68), separate
/// tables of a page 4.79 em or more.
pub const MERGE_GAP: f32 = 1.5;

/// A one-line block right below a table joins it as a wrapped cell's last line when
/// its core is at most this far below the table (em; LibreOffice's 13.8 pt pitch at
/// 12 pt leaves 0.25 em between cores) and its left edge is within [`CONT_ALIGN`] of a
/// line start of the table (lines of one cell start at the same x, achado 002).
pub const CONT_GAP: f32 = 0.5;
pub const CONT_ALIGN: f32 = 0.1;

/// A candidate needs this many physical rows with text from two blocks or more
/// (achado 002: 3 rows minimum, the smallest table of the corpus has 6).
pub const MIN_MULTI_ROWS: usize = 3;

/// Narrowest column gutter (em). LibreOffice's right-aligned number column is 0.35 em
/// from the next column; a spurious 0.07 pt stripe was seen between two cells (achado
/// 002, finding 4; achado 006, finding 10).
pub const MIN_GUTTER: f32 = 0.3;

/// Alignment tolerance: spread of the cell edges of one column, max(0.5 pt, 0.05 em).
/// Measured spreads: 0.00–0.05 pt (achado 002, finding 4; achado 006, finding 2).
pub const ALIGN_EM: f32 = 0.05;
pub const ALIGN_MIN_PT: f32 = 0.5;

/// Rows with text on both sides of a column boundary (variant C of achado 006: rejects
/// every river of the justified paragraphs).
pub const MIN_BOTH: usize = 3;

/// Cells wrap with a pitch clearly below the row pitch when the median line step of a
/// column exceeds the smallest one by this factor (Typst 19.24 / 14.39 = 1.34, Chrome
/// 18 / 13.5 = 1.33; LaTeX and LibreOffice 1.00: achado 006, finding 5).
pub const GAPPED_RATIO: f32 = 1.2;

/// Line steps inside a column below this (em) are ignored: physical rows are already
/// [`BASELINE_TOL`] apart, and a step this small is a script or a stray glyph, not a
/// line pitch (the smallest pitch seen in tables is 1.15 em, LibreOffice).
pub const MIN_STEP: f32 = 0.5;

/// Lines of one column belong to the same cell when their step is at most this factor
/// times the smallest step (the line pitch inside a cell).
pub const CELL_CHAIN: f32 = 1.15;

/// Safety bound for the pairwise side-by-side test (lines per region).
const MAX_LINES: usize = 4000;

/// Column alignment, from the cell edges.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Align {
    Left,
    Right,
    Center,
}

/// One cell: its lines, top to bottom, each a run of words left to right.
pub type Cell = Vec<Vec<Word>>;

/// What a detected table becomes.
#[derive(Clone, Debug, PartialEq)]
pub enum Body {
    /// A grid: one alignment per column; rows of cells (the first row is the header).
    Grid {
        align: Vec<Align>,
        rows: Vec<Vec<Cell>>,
    },
    /// The grid is uncertain: the physical rows, each a run of words left to right.
    Layout { rows: Vec<Vec<Word>> },
}

/// A table found on a page.
#[derive(Clone, Debug, PartialEq)]
pub struct Table {
    /// Indices into [`Page::blocks`] that the table replaces, ascending.
    pub blocks: Vec<usize>,
    pub body: Body,
}

/// Finds the tables of a page. `eligible(i)` tells whether block `i` may be part of a
/// table (the caller excludes headings, figure text and code).
pub fn detect(page: &Page, eligible: impl Fn(usize) -> bool) -> Vec<Table> {
    let mut out = Vec::new();
    for r in 0..page.regions.len().max(1) {
        let ids: Vec<usize> = (0..page.blocks.len())
            .filter(|&i| page.blocks[i].region == r && eligible(i))
            .collect();
        for blocks in candidates(&page.blocks, &ids) {
            let lines: Vec<(usize, &crate::layout::Line)> = blocks
                .iter()
                .flat_map(|&b| page.blocks[b].lines.iter().map(move |l| (b, l)))
                .collect();
            if let Some(body) = analyze(&lines) {
                out.push(Table { blocks, body });
            }
        }
    }
    out.sort_by_key(|t| t.blocks.first().copied());
    out
}

// ---------------------------------------------------------------- candidates

#[derive(Clone, Copy)]
struct LineBox {
    block: usize,
    top: f32,
    bottom: f32,
    left: f32,
    right: f32,
    size: f32,
}

fn core(l: &crate::layout::Line) -> (f32, f32) {
    (
        l.baseline - CORE_ASCENT * l.size,
        l.baseline + CORE_DESCENT * l.size,
    )
}

fn v_overlap(a: (f32, f32), b: (f32, f32)) -> f32 {
    a.1.min(b.1) - a.0.max(b.0)
}

fn find(parent: &mut [usize], mut i: usize) -> usize {
    while parent[i] != i {
        parent[i] = parent[parent[i]];
        i = parent[i];
    }
    i
}

/// Groups of block indices (ascending) that may form a table.
fn candidates(blocks: &[Block], ids: &[usize]) -> Vec<Vec<usize>> {
    let boxes: Vec<LineBox> = ids
        .iter()
        .flat_map(|&b| {
            blocks[b].lines.iter().map(move |l| {
                let (top, bottom) = core(l);
                LineBox {
                    block: b,
                    top,
                    bottom,
                    left: l.bbox.left,
                    right: l.bbox.right,
                    size: l.size,
                }
            })
        })
        .collect();
    if boxes.len() > MAX_LINES {
        return Vec::new();
    }
    // Union-find over positions in `ids`.
    let pos = |b: usize| ids.iter().position(|&x| x == b).unwrap_or(0);
    let mut parent: Vec<usize> = (0..ids.len()).collect();
    for (i, a) in boxes.iter().enumerate() {
        for b in &boxes[i + 1..] {
            if a.block == b.block {
                continue;
            }
            let min = a.size.min(b.size);
            let disjoint = a.right <= b.left || b.right <= a.left;
            if disjoint && v_overlap((a.top, a.bottom), (b.top, b.bottom)) > ROW_OVERLAP * min {
                let (x, y) = (
                    find(&mut parent, pos(a.block)),
                    find(&mut parent, pos(b.block)),
                );
                parent[x.max(y)] = x.min(y);
            }
        }
    }
    // Groups with two blocks or more, with their extent.
    struct Group {
        blocks: Vec<usize>,
        top: f32,
        bottom: f32,
        left: f32,
        right: f32,
        size: f32,
    }
    let mut groups: Vec<Group> = Vec::new();
    for root in 0..ids.len() {
        let members: Vec<usize> = (0..ids.len())
            .filter(|&k| find(&mut parent, k) == root)
            .map(|k| ids[k])
            .collect();
        if members.len() < 2 {
            continue;
        }
        let bx = boxes.iter().filter(|b| members.contains(&b.block));
        let mut g = Group {
            blocks: members.clone(),
            top: f32::INFINITY,
            bottom: f32::NEG_INFINITY,
            left: f32::INFINITY,
            right: f32::NEG_INFINITY,
            size: 0.0,
        };
        for b in bx {
            g.top = g.top.min(b.top);
            g.bottom = g.bottom.max(b.bottom);
            g.left = g.left.min(b.left);
            g.right = g.right.max(b.right);
            g.size = g.size.max(b.size);
        }
        groups.push(g);
    }
    groups.sort_by(|a, b| a.top.total_cmp(&b.top));
    // Merge groups that follow each other closely and overlap horizontally.
    let mut merged: Vec<Group> = Vec::new();
    for g in groups {
        if let Some(m) = merged.last_mut()
            && g.top - m.bottom <= MERGE_GAP * m.size.max(g.size)
            && g.left < m.right
            && m.left < g.right
        {
            m.blocks.extend(g.blocks);
            m.top = m.top.min(g.top);
            m.bottom = m.bottom.max(g.bottom);
            m.left = m.left.min(g.left);
            m.right = m.right.max(g.right);
            m.size = m.size.max(g.size);
            continue;
        }
        merged.push(g);
    }
    // Absorb the other blocks lying inside a group's extent (a rowspan cell centred on
    // its own baseline, a lone continuation line).
    let mut out = Vec::new();
    for mut g in merged {
        for &b in ids {
            if g.blocks.contains(&b) {
                continue;
            }
            let inside = boxes.iter().filter(|x| x.block == b).all(|x| {
                x.top >= g.top - ROW_OVERLAP * g.size
                    && x.bottom <= g.bottom + ROW_OVERLAP * g.size
                    && x.left >= g.left - ROW_OVERLAP * g.size
                    && x.right <= g.right + ROW_OVERLAP * g.size
            });
            if inside {
                g.blocks.push(b);
            }
        }
        // A wrapped cell's last line can fall below every other row (LibreOffice
        // kitchen-sink: `HTML` under `Impressão de página`): take a block right below
        // the group, starting where a line of the group starts, but not in the first
        // column (a caption or the next paragraph starts at the table's left edge).
        loop {
            let next = ids.iter().copied().find(|&b| {
                let mut bx = boxes.iter().filter(|x| x.block == b);
                !g.blocks.contains(&b)
                    && bx.clone().count() == 1
                    && bx.next().is_some_and(|x| {
                        let tol = CONT_ALIGN * x.size;
                        x.top >= g.bottom - ROW_OVERLAP * x.size
                            && x.top - g.bottom <= CONT_GAP * x.size
                            && x.left > g.left + tol
                            && x.right <= g.right + tol
                            && boxes.iter().any(|y| {
                                g.blocks.contains(&y.block) && (y.left - x.left).abs() <= tol
                            })
                    })
            });
            let Some(b) = next else { break };
            g.blocks.push(b);
            if let Some(x) = boxes.iter().find(|x| x.block == b) {
                g.bottom = g.bottom.max(x.bottom);
            }
        }
        g.blocks.sort_unstable();
        g.blocks.dedup();
        out.push(g.blocks);
    }
    out
}

// ---------------------------------------------------------------- grid

/// A physical row: lines on one baseline (several blocks), words left to right.
struct Phys {
    baseline: f32,
    words: Vec<Word>,
    /// Gaps (left, right) between side-by-side lines of different blocks on this row:
    /// where grouping split the row.
    splits: Vec<(f32, f32)>,
}

fn phys_rows(lines: &[(usize, &crate::layout::Line)]) -> Vec<Phys> {
    let mut ls: Vec<&(usize, &crate::layout::Line)> = lines.iter().collect();
    ls.sort_by(|a, b| a.1.baseline.total_cmp(&b.1.baseline));
    let mut rows: Vec<(f32, Vec<&(usize, &crate::layout::Line)>)> = Vec::new();
    for x in ls {
        match rows.last_mut() {
            Some((base, v)) if x.1.baseline - *base <= BASELINE_TOL * x.1.size => v.push(x),
            _ => rows.push((x.1.baseline, vec![x])),
        }
    }
    rows.into_iter()
        .map(|(baseline, mut v)| {
            v.sort_by(|a, b| a.1.bbox.left.total_cmp(&b.1.bbox.left));
            let splits = v
                .windows(2)
                .filter(|p| p[0].0 != p[1].0 && p[0].1.bbox.right <= p[1].1.bbox.left)
                .map(|p| (p[0].1.bbox.right, p[1].1.bbox.left))
                .collect();
            let mut words: Vec<Word> = v.iter().flat_map(|x| x.1.words.iter().cloned()).collect();
            words.sort_by(|a, b| a.bbox.left.total_cmp(&b.bbox.left));
            Phys {
                baseline,
                words,
                splits,
            }
        })
        .collect()
}

/// Dominant size, weighted by characters.
fn dominant_size(rows: &[Phys]) -> f32 {
    let mut sizes: Vec<(f32, usize)> = Vec::new();
    for w in rows.iter().flat_map(|r| &r.words) {
        match sizes.iter_mut().find(|(s, _)| (s - w.size).abs() < 0.05) {
            Some((_, n)) => *n += w.len.max(1),
            None => sizes.push((w.size, w.len.max(1))),
        }
    }
    sizes
        .iter()
        .max_by(|a, b| a.1.cmp(&b.1).then(b.0.total_cmp(&a.0)))
        .map_or(0.0, |(s, _)| *s)
}

/// x-ranges free of ink on every row, at least `min` wide: (left, right) of each gap.
fn gutters(rows: &[Phys], min: f32) -> Vec<(f32, f32)> {
    let mut spans: Vec<(f32, f32)> = rows
        .iter()
        .flat_map(|r| &r.words)
        .filter(|w| !w.text.trim().is_empty())
        .map(|w| (w.bbox.left, w.bbox.right))
        .collect();
    spans.sort_by(|a, b| a.0.total_cmp(&b.0));
    let mut out = Vec::new();
    let mut reach = f32::NEG_INFINITY;
    for (l, r) in spans {
        if reach.is_finite() && l - reach >= min {
            out.push((reach, l));
        }
        reach = reach.max(r);
    }
    out
}

/// Column index of a word: boundaries are the gutter middles.
fn column_of(w: &Word, bounds: &[f32]) -> usize {
    let x = w.bbox.center_x();
    bounds.iter().take_while(|&&b| x > b).count()
}

/// Physical rows split into columns: `cells[row][col]` = words left to right.
fn split_cols(rows: &[Phys], bounds: &[f32]) -> Vec<Vec<Vec<Word>>> {
    rows.iter()
        .map(|r| {
            let mut cols = vec![Vec::new(); bounds.len() + 1];
            for w in &r.words {
                cols[column_of(w, bounds)].push(w.clone());
            }
            cols
        })
        .collect()
}

fn is_numeric(words: &[Word]) -> bool {
    let mut digit = false;
    for c in words.iter().flat_map(|w| w.text.chars()) {
        if c.is_ascii_digit() {
            digit = true;
        } else if !".,%+-−()$€R/".contains(c) {
            return false;
        }
    }
    digit
}

/// Baselines of the physical rows with text in column `c`.
fn filled<'a>(
    rows: &'a [Phys],
    cols: &'a [Vec<Vec<Word>>],
    c: usize,
) -> impl Iterator<Item = f32> + 'a {
    rows.iter()
        .zip(cols)
        .filter(move |(_, cs)| cs.get(c).is_some_and(|ws| !ws.is_empty()))
        .map(|(r, _)| r.baseline)
}

/// Logical rows as ranges of physical rows.
fn logical_rows(rows: &[Phys], cols: &[Vec<Vec<Word>>], size: f32) -> Vec<(usize, usize)> {
    let ncols = cols.first().map_or(0, Vec::len);
    // Line steps inside each column.
    let mut steps = Vec::new();
    for c in 0..ncols {
        let mut prev: Option<f32> = None;
        for b in filled(rows, cols, c) {
            if let Some(p) = prev
                && b - p > MIN_STEP * size
            {
                steps.push(b - p);
            }
            prev = Some(b);
        }
    }
    steps.sort_by(f32::total_cmp);
    let (Some(&s_min), Some(&s_med)) = (steps.first(), steps.get(steps.len() / 2)) else {
        return (0..rows.len()).map(|r| (r, r)).collect();
    };
    if s_med > GAPPED_RATIO * s_min {
        // Cells: per column, lines chained at the in-cell pitch; rows: overlaps.
        let mut spans: Vec<(f32, f32)> = Vec::new();
        for c in 0..ncols {
            let mut cur: Option<(f32, f32)> = None;
            for b in filled(rows, cols, c) {
                cur = match cur {
                    Some((t, e)) if b - e <= CELL_CHAIN * s_min => Some((t, b)),
                    Some(span) => {
                        spans.push(span);
                        Some((b, b))
                    }
                    None => Some((b, b)),
                };
            }
            spans.extend(cur);
        }
        let mut cores: Vec<(f32, f32)> = spans
            .iter()
            .map(|(t, e)| (t - CORE_ASCENT * size, e + CORE_DESCENT * size))
            .collect();
        cores.sort_by(|a, b| a.0.total_cmp(&b.0));
        let mut bands: Vec<(f32, f32)> = Vec::new();
        for c in cores {
            match bands.last_mut() {
                Some(b) if c.0 < b.1 => b.1 = b.1.max(c.1),
                _ => bands.push(c),
            }
        }
        let mut out: Vec<(usize, usize)> = Vec::new();
        for (r, row) in rows.iter().enumerate() {
            let band = bands
                .iter()
                .position(|b| row.baseline >= b.0 && row.baseline <= b.1);
            match (out.last_mut(), band) {
                (Some(last), Some(k)) if band_of(&bands, rows, last.0) == Some(k) => last.1 = r,
                _ => out.push((r, r)),
            }
        }
        return out;
    }
    // Same pitch everywhere: continuation rows join the row above.
    let mut out: Vec<(usize, usize)> = Vec::new();
    for r in 0..rows.len() {
        let cont = out.last().is_some_and(|&(a, b)| {
            let here = &cols[r];
            let filled = |c: usize| (a..=b).any(|k| !cols[k][c].is_empty());
            here.first().is_some_and(Vec::is_empty)
                && here
                    .iter()
                    .enumerate()
                    .all(|(c, ws)| ws.is_empty() || filled(c) && !is_numeric(ws))
        });
        match out.last_mut() {
            Some(last) if cont => last.1 = r,
            _ => out.push((r, r)),
        }
    }
    out
}

fn band_of(bands: &[(f32, f32)], rows: &[Phys], r: usize) -> Option<usize> {
    let b = rows.get(r)?.baseline;
    bands.iter().position(|x| b >= x.0 && b <= x.1)
}

/// Cells of the logical rows: `grid[row][col]` = lines of words.
fn cells(cols: &[Vec<Vec<Word>>], logical: &[(usize, usize)]) -> Vec<Vec<Cell>> {
    let ncols = cols.first().map_or(0, Vec::len);
    logical
        .iter()
        .map(|&(a, b)| {
            (0..ncols)
                .map(|c| {
                    (a..=b)
                        .filter(|&r| !cols[r][c].is_empty())
                        .map(|r| cols[r][c].clone())
                        .collect()
                })
                .collect()
        })
        .collect()
}

/// Left, right and centre edges of a non-empty cell.
fn cell_edges(cell: &Cell) -> Option<(f32, f32)> {
    let ws = cell.iter().flatten();
    let l = ws.clone().map(|w| w.bbox.left).reduce(f32::min)?;
    let r = ws.map(|w| w.bbox.right).reduce(f32::max)?;
    Some((l, r))
}

#[derive(Clone, Copy, Default, Debug)]
struct Aligned {
    left: bool,
    right: bool,
    center: bool,
}

fn alignment(grid: &[Vec<Cell>], c: usize, tol: f32) -> Aligned {
    let edges: Vec<(f32, f32)> = grid
        .iter()
        .filter_map(|row| row.get(c).and_then(cell_edges))
        .collect();
    if edges.len() < 2 {
        return Aligned::default();
    }
    let spread = |f: &dyn Fn(&(f32, f32)) -> f32| {
        let (mut lo, mut hi) = (f32::INFINITY, f32::NEG_INFINITY);
        for e in &edges {
            lo = lo.min(f(e));
            hi = hi.max(f(e));
        }
        hi - lo
    };
    Aligned {
        left: spread(&|e| e.0) <= tol,
        right: spread(&|e| e.1) <= tol,
        center: spread(&|e| (e.0 + e.1) / 2.0) <= tol,
    }
}

/// Rows with text in both columns `c` and `c + 1`.
fn both(grid: &[Vec<Cell>], c: usize) -> usize {
    grid.iter()
        .filter(|row| {
            row.get(c).is_some_and(|x| !x.is_empty())
                && row.get(c + 1).is_some_and(|x| !x.is_empty())
        })
        .count()
}

/// Whether the boundary between columns `c` and `c + 1` is supported (variant C).
fn supported(grid: &[Vec<Cell>], c: usize, ncols: usize, tol: f32) -> bool {
    if both(grid, c) < MIN_BOTH {
        return false;
    }
    let a = alignment(grid, c, tol);
    let b = alignment(grid, c + 1, tol);
    a.right || a.center || a.left && c > 0 || b.left || b.center || b.right && c + 1 < ncols - 1
}

/// A cell line holds two words farther apart than a cell gap: a column boundary that
/// some spanning row hides from the empty-stripe rule.
fn has_inner_gap(cell: &Cell) -> bool {
    cell.iter().any(|line| {
        line.windows(2)
            .any(|p| p[1].bbox.left - p[0].bbox.right > LINE_SPLIT_GAP * p[0].size.max(p[1].size))
    })
}

fn analyze(lines: &[(usize, &crate::layout::Line)]) -> Option<Body> {
    let rows = phys_rows(lines);
    if rows.iter().filter(|r| !r.splits.is_empty()).count() < MIN_MULTI_ROWS {
        return None;
    }
    let size = dominant_size(&rows);
    if size <= 0.0 {
        return None;
    }
    let tol = (ALIGN_EM * size).max(ALIGN_MIN_PT);
    let mut gaps = gutters(&rows, MIN_GUTTER * size);
    // Grouping split the rows of a table at its cell gaps, so the splits fall in the
    // empty stripes. Prose with fragments split off justified lines has its splits
    // anywhere (arXiv 2509.23299 references: `“Tf-gridnet:` 1.4 em after `Watanabe,`,
    // while the only stripe is the hanging indent of the labels).
    let in_gutter = |s: &(f32, f32)| gaps.iter().any(|g| s.0 < g.1 && g.0 < s.1);
    if rows
        .iter()
        .filter(|r| r.splits.iter().any(in_gutter))
        .count()
        < MIN_MULTI_ROWS
    {
        return None;
    }
    let mut rejected = false;
    let grid = loop {
        let bounds: Vec<f32> = gaps.iter().map(|(l, r)| (l + r) / 2.0).collect();
        let cols = split_cols(&rows, &bounds);
        let logical = logical_rows(&rows, &cols, size);
        let grid = cells(&cols, &logical);
        let ncols = bounds.len() + 1;
        // The weakest unsupported boundary goes first (fewest rows with text on both
        // sides, then the narrowest).
        let bad = (0..bounds.len())
            .filter(|&c| !supported(&grid, c, ncols, tol))
            .min_by(|&x, &y| {
                both(&grid, x)
                    .cmp(&both(&grid, y))
                    .then((gaps[x].1 - gaps[x].0).total_cmp(&(gaps[y].1 - gaps[y].0)))
            });
        match bad {
            Some(c) => {
                gaps.remove(c);
                rejected = true;
            }
            None => break grid,
        }
    };
    let ncols = gaps.len() + 1;
    let certain = !rejected
        && ncols >= 2
        && grid.len() >= MIN_MULTI_ROWS
        && !grid.iter().flatten().any(has_inner_gap);
    if certain {
        let align = (0..ncols)
            .map(|c| {
                let a = alignment(&grid, c, tol);
                let numeric = grid
                    .iter()
                    .skip(1)
                    .filter_map(|row| row.get(c))
                    .filter(|x| !x.is_empty())
                    .all(|x| x.iter().all(|l| is_numeric(l)));
                match (a.left, a.right, a.center) {
                    (_, true, _) if numeric => Align::Right,
                    (true, _, _) => Align::Left,
                    (false, true, _) => Align::Right,
                    (false, false, true) => Align::Center,
                    _ if numeric => Align::Right,
                    _ => Align::Left,
                }
            })
            .collect();
        return Some(Body::Grid { align, rows: grid });
    }
    Some(Body::Layout {
        rows: rows.into_iter().map(|r| r.words).collect(),
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::{Line, Rect, Region, Style};

    const SIZE: f32 = 10.0;

    /// Words of `text` from `x` on `base`: glyphs 0.5 em wide, spaces 0.25 em.
    fn words(text: &str, x: f32, base: f32) -> Vec<Word> {
        let mut out = Vec::new();
        let mut x = x;
        for t in text.split(' ') {
            let w = 0.5 * SIZE * t.chars().count() as f32;
            out.push(Word {
                text: t.into(),
                bbox: Rect::new(x, base - 0.9 * SIZE, x + w, base + 0.25 * SIZE),
                baseline: base,
                size: SIZE,
                font: "Serif".into(),
                style: Style::default(),
                glued: false,
                len: t.chars().count(),
                chars: 0..0,
                figure: None,
            });
            x += w + 0.25 * SIZE;
        }
        out
    }

    fn line(text: &str, x: f32, base: f32) -> Line {
        let ws = words(text, x, base);
        let bbox = ws.iter().skip(1).fold(ws[0].bbox, |a, w| a.union(&w.bbox));
        Line {
            words: ws,
            bbox,
            baseline: base,
            size: SIZE,
            style: Style::default(),
        }
    }

    /// A block from (text, x, baseline) lines.
    fn block(lines: &[(&str, f32, f32)]) -> Block {
        let lines: Vec<Line> = lines.iter().map(|&(t, x, b)| line(t, x, b)).collect();
        let bbox = lines
            .iter()
            .skip(1)
            .fold(lines[0].bbox, |a, l| a.union(&l.bbox));
        Block {
            lines,
            bbox,
            size: SIZE,
            style: Style::default(),
            region: 0,
        }
    }

    fn page(blocks: Vec<Block>) -> Page {
        Page {
            number: 1,
            width: 600.0,
            height: 800.0,
            regions: vec![Region {
                rect: Rect::new(50.0, 50.0, 550.0, 750.0),
                band: 0,
                column: 0,
                columns: 1,
            }],
            blocks,
            furniture: Vec::new(),
            chars: Vec::new(),
        }
    }

    fn texts(cell: &Cell) -> String {
        cell.iter()
            .flatten()
            .map(|w| w.text.as_str())
            .collect::<Vec<_>>()
            .join(" ")
    }

    /// x of a right-aligned text ending at `right`.
    fn r(text: &str, right: f32) -> f32 {
        right - 0.5 * SIZE * text.chars().count() as f32
    }

    /// Rows 12 pt apart (1.2 em, the LaTeX pitch), from y = 100.
    fn y(i: usize) -> f32 {
        100.0 + 12.0 * i as f32
    }

    fn grid(t: &Table) -> (&[Align], Vec<Vec<String>>) {
        match &t.body {
            Body::Grid { align, rows } => (
                align,
                rows.iter()
                    .map(|row| row.iter().map(texts).collect())
                    .collect(),
            ),
            Body::Layout { .. } => panic!("expected a grid, got a layout"),
        }
    }

    fn column(v: &[&str], x: impl Fn(&str) -> f32) -> Block {
        let ls: Vec<(&str, f32, f32)> = v
            .iter()
            .enumerate()
            .map(|(i, t)| (*t, x(t), y(i)))
            .collect();
        block(&ls)
    }

    #[test]
    fn three_columns_left_right_left() {
        // Name | number (right-aligned) | note, one block per column, as grouping
        // makes them.
        let p = page(vec![
            column(&["Item", "Cimento", "Areia", "Brita", "Tijolo"], |_| 50.0),
            column(&["Qtd", "120", "18", "22", "9.500"], |t| r(t, 200.0)),
            column(&["Unidade", "sacos", "m3", "m3", "unidades"], |_| 220.0),
        ]);
        let ts = detect(&p, |_| true);
        assert_eq!(ts.len(), 1);
        assert_eq!(ts[0].blocks, vec![0, 1, 2]);
        let (align, rows) = grid(&ts[0]);
        assert_eq!(align, [Align::Left, Align::Right, Align::Left]);
        assert_eq!(rows[0], ["Item", "Qtd", "Unidade"]);
        assert_eq!(rows[4], ["Tijolo", "9.500", "unidades"]);
    }

    #[test]
    fn justified_paragraph_is_not_a_table() {
        let p = page(vec![block(&[
            (
                "Responsabilidades extraordinariamente desproporcionais",
                50.0,
                y(0),
            ),
            (
                "inconstitucionalidades procedimentos administrativos",
                50.0,
                y(1),
            ),
            (
                "otorrinolaringologista paralelepipedos desenvolvimento",
                50.0,
                y(2),
            ),
            ("superintendencia regional fundamentalmente", 50.0, y(3)),
        ])]);
        assert!(detect(&p, |_| true).is_empty());
    }

    #[test]
    fn fragments_split_off_prose_lines_are_not_a_table() {
        // Full lines with a word split off at a wide justified gap on three rows, at
        // different x: the splits fall in no empty stripe (arXiv references).
        let bs = vec![
            block(&[
                ("aaaa bbbb cccc dddd", 50.0, y(0)),
                ("aaaa bbbb cccc dddd eeee ffff gggg hhhh", 50.0, y(1)),
                ("aaaa bbbb", 50.0, y(2)),
                ("aaaa bbbb cccc dddd eeee ffff gggg hhhh", 50.0, y(3)),
                ("aaaa bbbb cccc", 50.0, y(4)),
            ]),
            block(&[("xx", 170.0, y(0))]),
            block(&[("yy", 120.0, y(2))]),
            block(&[("zz", 140.0, y(4))]),
        ];
        assert!(detect(&page(bs), |_| true).is_empty());
    }

    #[test]
    fn continuation_rows_join_but_empty_first_cells_with_numbers_do_not() {
        // Uniform pitch (LaTeX, LibreOffice). The `Goias` row has an empty first cell
        // and a number: a row of its own. The `x` row only has text under a filled
        // cell of the row above: a continuation.
        let p = page(vec![
            block(&[
                ("Regiao", 50.0, y(0)),
                ("Sul", 50.0, y(1)),
                ("Norte", 50.0, y(4)),
            ]),
            block(&[
                ("Estado", 120.0, y(0)),
                ("Parana", 120.0, y(1)),
                ("Goias", 120.0, y(2)),
                ("Bahia", 120.0, y(4)),
            ]),
            block(&[
                ("Total", r("Total", 260.0), y(0)),
                ("10", r("10", 260.0), y(1)),
                ("20", r("20", 260.0), y(2)),
                ("40", r("40", 260.0), y(4)),
            ]),
            block(&[
                ("Nota", 280.0, y(0)),
                ("Documento de", 280.0, y(1)),
                ("escritorio", 280.0, y(2)),
                ("x", 280.0, y(3)),
                ("fim", 280.0, y(4)),
            ]),
        ]);
        let ts = detect(&p, |_| true);
        assert_eq!(ts.len(), 1);
        let (_, rows) = grid(&ts[0]);
        assert_eq!(rows.len(), 4);
        assert_eq!(rows[2], ["", "Goias", "20", "escritorio x"]);
        assert_eq!(rows[3], ["Norte", "Bahia", "40", "fim"]);
    }

    #[test]
    fn wrapped_cells_with_a_smaller_pitch_make_one_row() {
        // Chrome: lines inside a cell 13.5 pt apart, rows 30 pt apart, the short cells
        // centred vertically on the wrapped one (half a line off its baselines).
        let first = block(&[
            ("Etapa", 50.0, 100.0),
            ("1", 50.0, 136.75),
            ("2", 50.0, 170.0),
            ("3", 50.0, 200.0),
        ]);
        let second = block(&[
            ("Descricao", 100.0, 100.0),
            ("Levantamento dos", 100.0, 130.0),
            ("documentos antigos", 100.0, 143.5),
            ("Digitalizacao", 100.0, 170.0),
            ("Publicacao", 100.0, 200.0),
        ]);
        let third = block(&[
            ("Prazo", 250.0, 100.0),
            ("15 dias", 250.0, 136.75),
            ("30 dias", 250.0, 170.0),
            ("5 dias", 250.0, 200.0),
        ]);
        let ts = detect(&page(vec![first, second, third]), |_| true);
        assert_eq!(ts.len(), 1);
        let (_, rows) = grid(&ts[0]);
        assert_eq!(rows.len(), 4);
        assert_eq!(
            rows[1],
            ["1", "Levantamento dos documentos antigos", "15 dias"]
        );
    }

    #[test]
    fn a_cell_spanning_a_boundary_gives_a_layout() {
        // `sem investimento` covers the gutter between two number columns: that stripe
        // is gone, and the other rows hide a cell gap inside one column.
        let a = |t: &str| r(t, 150.0);
        let b = |t: &str| r(t, 210.0);
        let p = page(vec![
            column(
                &["Indicador", "Receita", "Despesa", "Investimento", "Margem"],
                |_| 50.0,
            ),
            block(&[("2023", a("2023"), y(0)), ("1.240,5", a("1.240,5"), y(1))]),
            block(&[("2024", b("2024"), y(0)), ("1.318,2", b("1.318,2"), y(1))]),
            block(&[("980,1", a("980,1"), y(2))]),
            block(&[("1.002,7", b("1.002,7"), y(2))]),
            block(&[("sem investimento", b("sem investimento"), y(3))]),
            block(&[("21,0", a("21,0"), y(4))]),
            block(&[("23,9", b("23,9"), y(4))]),
        ]);
        let ts = detect(&p, |_| true);
        assert_eq!(ts.len(), 1);
        let Body::Layout { rows } = &ts[0].body else {
            panic!("expected a layout");
        };
        assert_eq!(rows.len(), 5);
        assert_eq!(ts[0].blocks.len(), 8);
    }

    #[test]
    fn ineligible_blocks_are_left_alone() {
        let p = page(vec![
            column(&["a", "b", "c"], |_| 50.0),
            column(&["1", "2", "3"], |_| 100.0),
        ]);
        assert_eq!(detect(&p, |_| true).len(), 1);
        assert!(detect(&p, |i| i != 1).is_empty());
    }
}