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
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
//! Column detection and reading order (docs/arquitetura.md, part 2, stage 4;
//! docs/achados/005-colunas-ordem-de-leitura.md).
//!
//! Runs on words, **before** line formation, so that no line can cross a column
//! gutter. A fixed gap threshold cannot find gutters: justified word gaps reach
//! 20–31 pt while real gutters are 8–15 pt (finding 003, finding 5). What a gutter has
//! and a wide word gap does not is **vertical consistency**: the same x-range is empty
//! in every text row over a long run of rows, with text on both sides.
//!
//! The algorithm:
//! 1. Rows: words clustered by baseline (page-wide, so the two columns of LaTeX's
//!    aligned baselines share a row; rows with text on only one side are fine).
//! 2. Stripes: sweep the rows top to bottom keeping the x-intervals that are empty in
//!    every row so far (an interval narrows as rows are added and dies when a word
//!    crosses it). Every free interval of a row at least [`MIN_GUTTER`] wide starts or
//!    continues a stripe.
//! 3. A stripe is *consistent* when, after dropping the leading rows that have text on
//!    only one side, it still has [`MIN_ROWS`] rows with text on each side.
//! 4. A consistent stripe is a *gutter* when the columns it separates look like prose:
//!    each one at least [`MIN_COLUMN_WIDTH`] wide and typically filled
//!    ([`MIN_FILL`]). Columns are bounded by neighbouring consistent stripes, so a
//!    table (several narrow, ragged columns) is never split into page-level columns:
//!    being conservative here only leaves a borderless table to the table stage.
//!    Figure text counts as one block per figure, list-marker slices do not bound a
//!    column, and rows passing the column's justified edge or crossed by a horizontal
//!    rule cut the gutter (achado 012).
//! 5. Regions: a recursive XY-cut along the longest gutter first (rows above, left
//!    side, right side, rows below). With gutters over the same rows this is "bands
//!    top to bottom, columns left to right" (achado 005); on nested layouts a column
//!    that runs past a full-width part of its neighbours is read whole (achado 012).
//!
//! Pure functions over our own types, unit-tested with synthetic words.

use std::cmp::Ordering;

use super::group::{BASELINE_TOL, MAX_LEADING, is_marker};
use super::{Rect, Word};

/// Minimum width of a gutter, in em of the page's body size. Measured gutters, as the
/// band left empty by every row of the column run (finding 005): LaTeX 0.75–0.80 em
/// (7.5–8 pt at 10 pt, narrower than the nominal 10 pt `\columnsep`), Typst
/// 1.12–1.16, LibreOffice 1.19–1.21, Chrome 1.42. It must stay above the list
/// marker → text gap (at most 0.59 em, finding 004, finding 7), which is empty in every
/// row of a list with hanging indent. The margin on the LaTeX side is small (0.05 em).
pub const MIN_GUTTER: f32 = 0.7;

/// Minimum number of rows with text on EACH side of a stripe. Rivers (word gaps of
/// loose justified lines that line up) of at least [`MIN_GUTTER`] last at most 8
/// page rows in the corpus (Chrome, which justifies without hyphenating; about 4
/// lines of one column, since Chrome's two columns do not share baselines); real
/// columns have 20–55 rows per page. Tables of the kitchen-sink document have 5–6.
pub const MIN_ROWS: usize = 6;

/// Minimum width of a text column, in em of the body size. Columns of the A5 corpus
/// measure 13.3 em (LibreOffice, 12 pt) to 16.5 em (LaTeX). A river splits a
/// 16 em column into halves of at most 7.5 em; kitchen-sink table columns are
/// 4.7–13.3 em but always have neighbouring stripes (see [`NEIGHBOR_OVERLAP`]).
pub const MIN_COLUMN_WIDTH: f32 = 10.0;

/// Minimum median fill of a text column: median width of a row's text on that side,
/// divided by the column width. Justified prose: 0.97–1.00 in the corpus; the lowest
/// is 0.59 (LibreOffice page 1, where an indented abstract and a 28 pt title broken
/// over 4 lines fill column 1). Table columns without neighbours were not observed
/// yet (the kitchen-sink tables measure 0.29–1.00 but are rejected by their
/// neighbours); this guard is for two-column tables with short cells.
pub const MIN_FILL: f32 = 0.5;

/// Another empty stripe (consistent or not) bounds a column when it overlaps at least
/// this fraction of the stripe's rows, so a table is seen as several narrow columns (and rejected)
/// while a small table inside one text column does not shrink that column.
pub const NEIGHBOR_OVERLAP: f32 = 0.5;

/// One region of the page in reading order: a full-width band (`columns == 1`) or one
/// column of a multi-column band.
#[derive(Clone, Debug, PartialEq)]
pub struct Region {
    /// Union of the boxes of the words assigned to the region.
    pub rect: Rect,
    /// Index of the band (top to bottom).
    pub band: usize,
    /// 0-based column inside the band (left to right).
    pub column: usize,
    /// Number of columns of the band.
    pub columns: usize,
}

/// A detected column gutter: an x-range empty in every row of a run of rows.
#[derive(Clone, Debug, PartialEq)]
pub struct Gutter {
    pub left: f32,
    pub right: f32,
    /// Row indices (see [`rows`]) covered by the gutter, inclusive.
    pub first_row: usize,
    pub last_row: usize,
}

/// Words sharing a baseline across the whole page (no x splitting).
#[derive(Clone, Debug, PartialEq)]
pub struct Row {
    /// Indices into the word slice, left to right.
    pub words: Vec<usize>,
    pub baseline: f32,
    /// Merged x-intervals covered by the words, left to right.
    pub spans: Vec<(f32, f32)>,
    /// x-extents of the words that are list markers ([`is_marker`]), left to right.
    pub markers: Vec<(f32, f32)>,
    /// Some word of the row belongs to a figure ([`Word::figure`]).
    pub figure: bool,
}

impl Row {
    fn left(&self) -> f32 {
        self.spans.first().map_or(f32::INFINITY, |s| s.0)
    }
    fn right(&self) -> f32 {
        self.spans.last().map_or(f32::NEG_INFINITY, |s| s.1)
    }
    /// Leftmost and rightmost covered x strictly inside `(lo, hi)`.
    fn extent_in(&self, lo: f32, hi: f32) -> Option<(f32, f32)> {
        let mut out: Option<(f32, f32)> = None;
        for &(a, b) in &self.spans {
            if a >= lo && b <= hi {
                out = Some(out.map_or((a, b), |(l, r)| (l.min(a), r.max(b))));
            }
        }
        out
    }
}

fn finite(w: &Word) -> bool {
    w.bbox.left.is_finite()
        && w.bbox.right.is_finite()
        && w.baseline.is_finite()
        && w.size.is_finite()
        && w.size > 0.0
}

/// Dominant size of the words (by characters, 0.1 pt buckets; ties → larger).
pub fn body_size(words: &[Word]) -> f32 {
    let mut buckets: Vec<(i64, usize)> = Vec::new();
    for w in words.iter().filter(|w| finite(w)) {
        let k = (w.size * 10.0).round() as i64;
        match buckets.iter_mut().find(|(b, _)| *b == k) {
            Some((_, c)) => *c += w.len,
            None => buckets.push((k, w.len)),
        }
    }
    buckets
        .into_iter()
        .max_by(|a, b| a.1.cmp(&b.1).then(a.0.cmp(&b.0)))
        .map_or(0.0, |(k, _)| k as f32 / 10.0)
}

/// A figure word counts as placed when its centre lies inside its form's rectangle,
/// expanded by this many em of the word's size. Type3 emojis of the arXiv 2509.23299
/// figure (p. 2) come out of PDFium in form-local coordinates, hundreds of points away
/// from the form (achado 010, finding 6); real labels sit inside it.
const FIGURE_RECT_TOL: f32 = 0.5;

/// x-extent that each word occupies for gutter detection. Ordinary words: their own.
/// Words of a figure (a form XObject smaller than half the page, [`Word::figure`]):
/// the union of the figure's placed words, so the gaps between the boxes of a diagram
/// never look like page gutters (Word 2509.09931 p. 2: a 2.9 em gap inside the
/// diagram bounded column 1 and cancelled the page gutter, achado 012), while a
/// full-width figure still crosses, and cuts, the gutter. Misplaced figure words
/// (outside their form, see [`FIGURE_RECT_TOL`]) occupy nothing.
fn occupied(words: &[Word]) -> Vec<Option<(f32, f32)>> {
    let placed = |w: &Word| {
        w.figure.is_some_and(|f| {
            let tol = FIGURE_RECT_TOL * w.size;
            let (cx, cy) = (w.bbox.center_x(), (w.bbox.top + w.bbox.bottom) / 2.0);
            cx >= f.rect.left - tol
                && cx <= f.rect.right + tol
                && cy >= f.rect.top - tol
                && cy <= f.rect.bottom + tol
        })
    };
    // Figure object -> union of its placed words (few figures per page: linear scan).
    let mut extents: Vec<(u32, f32, f32)> = Vec::new();
    for w in words.iter().filter(|w| finite(w) && placed(w)) {
        let Some(f) = w.figure else { continue };
        match extents.iter_mut().find(|e| e.0 == f.object) {
            Some(e) => {
                e.1 = e.1.min(w.bbox.left);
                e.2 = e.2.max(w.bbox.right);
            }
            None => extents.push((f.object, w.bbox.left, w.bbox.right)),
        }
    }
    words
        .iter()
        .map(|w| match w.figure {
            None => Some((w.bbox.left, w.bbox.right)),
            Some(f) if placed(w) => extents.iter().find(|e| e.0 == f.object).map(|e| (e.1, e.2)),
            Some(_) => None,
        })
        .collect()
}

/// Clusters the (finite) words into page-wide rows by baseline, top to bottom. Row
/// spans are the x-extents the words occupy for gutter detection ([`occupied`]).
pub fn rows(words: &[Word]) -> Vec<Row> {
    let occ = occupied(words);
    let mut idx: Vec<usize> = (0..words.len()).filter(|&i| finite(&words[i])).collect();
    idx.sort_by(|&a, &b| {
        cmp(words[a].baseline, words[b].baseline)
            .then(cmp(words[a].bbox.left, words[b].bbox.left))
            .then(a.cmp(&b))
    });
    let mut clusters: Vec<Vec<usize>> = Vec::new();
    for i in idx {
        if let Some(c) = clusters.last_mut() {
            let first = &words[c[0]];
            let size = first.size.min(words[i].size);
            if (words[i].baseline - first.baseline).abs() <= BASELINE_TOL * size {
                c.push(i);
                continue;
            }
        }
        clusters.push(vec![i]);
    }
    clusters
        .into_iter()
        .map(|mut c| {
            c.sort_by(|&a, &b| cmp(words[a].bbox.left, words[b].bbox.left).then(a.cmp(&b)));
            let mut ext: Vec<(f32, f32)> = c.iter().filter_map(|&i| occ[i]).collect();
            ext.sort_by(|a, b| cmp(a.0, b.0).then(cmp(a.1, b.1)));
            let mut spans: Vec<(f32, f32)> = Vec::new();
            for (l, r) in ext {
                match spans.last_mut() {
                    Some(s) if l <= s.1 => s.1 = s.1.max(r),
                    _ => spans.push((l, r)),
                }
            }
            let markers = c
                .iter()
                .filter(|&&i| is_marker(&words[i].text))
                .map(|&i| (words[i].bbox.left, words[i].bbox.right))
                .collect();
            let figure = c.iter().any(|&i| words[i].figure.is_some());
            Row {
                baseline: words[c[0]].baseline,
                words: c,
                spans,
                markers,
                figure,
            }
        })
        .collect()
}

/// A run of rows sharing an empty x-interval.
#[derive(Clone, Copy, Debug, PartialEq)]
struct Stripe {
    lo: f32,
    hi: f32,
    first: usize,
    last: usize,
}

/// Maximum number of stripes followed at once (see [`stripes`]).
const MAX_ACTIVE: usize = 256;

/// Sweeps the rows and returns every maximal stripe at least `min_gap` wide.
fn stripes(rows: &[Row], min_gap: f32) -> Vec<Stripe> {
    let x0 = rows.iter().map(Row::left).fold(f32::INFINITY, f32::min) - 1.0;
    let x1 = rows
        .iter()
        .map(Row::right)
        .fold(f32::NEG_INFINITY, f32::max)
        + 1.0;
    let mut active: Vec<Stripe> = Vec::new();
    let mut closed: Vec<Stripe> = Vec::new();
    for (i, row) in rows.iter().enumerate() {
        // Free intervals of the row, including the outer ones (a row with text on one
        // side only does not cross a gutter on the other side).
        let mut free = Vec::new();
        let mut x = x0;
        for &(a, b) in &row.spans {
            if a - x >= min_gap {
                free.push((x, a));
            }
            x = x.max(b);
        }
        if x1 - x >= min_gap {
            free.push((x, x1));
        }
        let mut next: Vec<Stripe> = Vec::new();
        for s in active {
            let mut alive = false;
            for &(a, b) in &free {
                let (lo, hi) = (s.lo.max(a), s.hi.min(b));
                if hi - lo >= min_gap {
                    next.push(Stripe {
                        lo,
                        hi,
                        first: s.first,
                        last: i,
                    });
                    alive = true;
                }
            }
            if !alive {
                closed.push(s);
            }
        }
        // Several stripes can narrow to the same interval: keep the oldest (longest).
        next.sort_by(|a, b| {
            cmp(a.lo, b.lo)
                .then(cmp(a.hi, b.hi))
                .then(a.first.cmp(&b.first))
        });
        next.dedup_by(|b, a| a.lo == b.lo && a.hi == b.hi);
        // A free interval starts a new stripe unless a live stripe already spans all of
        // it: a narrower live stripe (say, the page margin) does not represent the
        // wider empty band that starts here (the gutter under a full-width title).
        for &(a, b) in &free {
            if !next.iter().any(|s| s.lo == a && s.hi == b) {
                next.push(Stripe {
                    lo: a,
                    hi: b,
                    first: i,
                    last: i,
                });
            }
        }
        // Bound the work on pathological pages (thousands of scattered glyphs): keep
        // the oldest stripes, which are the ones that can become gutters.
        if next.len() > MAX_ACTIVE {
            next.sort_by(|a, b| a.first.cmp(&b.first).then(cmp(a.lo, b.lo)));
            closed.extend(next.drain(MAX_ACTIVE..));
        }
        active = next;
    }
    closed.extend(active);
    closed.sort_by(|a, b| a.first.cmp(&b.first).then(cmp(a.lo, b.lo)));
    closed
}

/// A stripe with text on both sides over enough rows. Leading rows that only have
/// text on the LEFT and sit more than [`MAX_LEADING`] above the first row with text
/// on the right are dropped from it: they are read first in any case, and leaving
/// them to the band above keeps a full-width paragraph whose short last line stops
/// before the gutter in one piece (Chrome abstract: 3.8 em above column 2, finding
/// 005). Closer left-only rows are the top of the left column when the columns do not
/// share baselines, and stay. Leading rows with text only on the right are always
/// kept: they are the top of the right column when its first baseline is higher
/// (LibreOffice page 1, Typst page 3), and moving them up would read them before the
/// left column.
fn consistent(s: &Stripe, rows: &[Row], body: f32) -> Option<Stripe> {
    let has_left = |r: &Row| r.left() < s.lo;
    let has_right = |r: &Row| r.right() > s.hi;
    let first_right = s.first + rows[s.first..=s.last].iter().position(has_right)?;
    let limit = rows[first_right].baseline - MAX_LEADING * body;
    let start = (s.first..first_right)
        .find(|&i| rows[i].baseline >= limit)
        .unwrap_or(first_right);
    let span = &rows[start..=s.last];
    let left_rows = span.iter().filter(|r| has_left(r)).count();
    let right_rows = span.iter().filter(|r| has_right(r)).count();
    (left_rows >= MIN_ROWS && right_rows >= MIN_ROWS).then_some(Stripe { first: start, ..*s })
}

/// Widest slice between a gutter candidate and a neighbouring stripe that can be the
/// marker column of a hanging-indent list, in em. InDesign (USGS fs20243057 p. 1,
/// achado 010, finding 3): `•` 3.3 pt wide right after the gutter, then a 0.70 em
/// marker -> text stripe (= `MIN_GUTTER`) that bounded column 3 to 0.4 em. Three-digit
/// markers (`10.`) are about 1.2 em wide.
pub const LIST_INDENT_MAX: f32 = 1.5;

/// The neighbouring stripe `d` is the marker -> text gap of a hanging-indent list
/// right next to `c`: the slice between them is narrower than [`LIST_INDENT_MAX`] and
/// every word in it, over their common rows, is a list marker (at least one). Such a
/// stripe does not bound the column on the right of `c`.
fn hanging_indent(rows: &[Row], c: &Stripe, d: &Stripe, body: f32) -> bool {
    // Only to the right of `c`: markers precede their text (left-to-right scripts).
    // Applied to the left, the real gutter next to a marker column would stop bounding
    // the marker -> text stripe, which then became a gutter itself (USGS p. 1).
    if d.lo < c.hi {
        return false;
    }
    let (lo, hi) = (c.hi, d.lo);
    if hi - lo >= LIST_INDENT_MAX * body {
        return false;
    }
    let (first, last) = (c.first.max(d.first), c.last.min(d.last));
    if first > last {
        return false;
    }
    let mut markers = 0;
    for r in &rows[first..=last] {
        let inside = |&(a, b): &(f32, f32)| a < hi && b > lo;
        for sp in r.spans.iter().filter(|s| inside(s)) {
            // Each covered span must be one marker word (a span merged from a marker
            // and its text is not a marker column).
            if !r.markers.iter().any(|m| m.0 <= sp.0 && m.1 >= sp.1) {
                return false;
            }
            markers += 1;
        }
    }
    markers > 0
}

/// Width and median fill of the text in `(lo, hi)` over the rows `first..=last`.
fn column_shape(rows: &[Row], first: usize, last: usize, lo: f32, hi: f32) -> (f32, f32) {
    let extents: Vec<(f32, f32)> = rows[first..=last]
        .iter()
        .filter_map(|r| r.extent_in(lo, hi))
        .collect();
    let left = extents.iter().map(|e| e.0).fold(f32::INFINITY, f32::min);
    let right = extents
        .iter()
        .map(|e| e.1)
        .fold(f32::NEG_INFINITY, f32::max);
    let width = right - left;
    if extents.is_empty() || width <= 0.0 {
        return (0.0, 0.0);
    }
    let mut fills: Vec<f32> = extents.iter().map(|e| (e.1 - e.0) / width).collect();
    fills.sort_by(|a, b| cmp(*a, *b));
    (width, fills[fills.len() / 2])
}

/// Detects the column gutters of a page. `rows` must come from [`rows`] on the same
/// words; `body` is the body font size ([`body_size`]).
pub fn gutters(rows: &[Row], rules: &[Rect], body: f32) -> Vec<Gutter> {
    if rows.is_empty() || !body.is_finite() || body <= 0.0 {
        return Vec::new();
    }
    let all = stripes(rows, MIN_GUTTER * body);
    let cands: Vec<Stripe> = all
        .iter()
        .filter(|s| s.last + 1 - s.first >= MIN_ROWS)
        .filter_map(|s| consistent(s, rows, body))
        .collect();
    let mut out = Vec::new();
    for c in &cands {
        let Some((lbound, _)) = columns_of(c, &all, rows, body) else {
            continue;
        };
        // Rows that intrude into the gutter (a `table*` whose cells pass the column
        // edge) cut it; each remaining piece must stand as a gutter on its own.
        let pieces = cut_intrusions(c, rows, lbound, rules, body);
        let whole = pieces.len() == 1 && pieces[0] == *c;
        for p in pieces {
            let p = if whole {
                Some(p)
            } else {
                consistent(&p, rows, body).filter(|p| columns_of(p, &all, rows, body).is_some())
            };
            if let Some(p) = p {
                out.push(Gutter {
                    left: p.lo,
                    right: p.hi,
                    first_row: p.first,
                    last_row: p.last,
                });
            }
        }
    }
    merge(out)
}

/// Bounds `(left, right)` of the two columns of candidate `c` when both look like
/// prose (width and fill), None otherwise.
fn columns_of(c: &Stripe, all: &[Stripe], rows: &[Row], body: f32) -> Option<(f32, f32)> {
    let span = &rows[c.first..=c.last];
    let has_left: Vec<bool> = span.iter().map(|r| r.left() < c.lo).collect();
    let has_right: Vec<bool> = span.iter().map(|r| r.right() > c.hi).collect();
    let (nl, nr) = (
        has_left.iter().filter(|&&b| b).count(),
        has_right.iter().filter(|&&b| b).count(),
    );
    // Rows of `c` with text on that side that `d` also covers.
    let covered = |d: &Stripe, side: &[bool]| {
        (d.first.max(c.first)..=d.last.min(c.last))
            .filter(|&i| side[i - c.first])
            .count() as f32
    };
    // Any empty stripe counts, not only consistent ones: inside a table the cell
    // gaps are empty over all of its rows even when a column has fewer than
    // MIN_ROWS filled cells (LibreOffice kitchen-sink table: 5 body rows). A
    // stripe overlapping `c` in x is the same gutter and bounds nothing.
    // The overlap is counted on the rows with text on the neighbour's side: page rows
    // also hold the other column's baselines (a table in column 1 of arXiv 2509.23299
    // p. 4 spans 29 page rows but 12 rows of column 1, achado 012).
    let mut lbound = f32::NEG_INFINITY;
    let mut rbound = f32::INFINITY;
    for d in all {
        if d.first > c.last || d.last < c.first {
            continue;
        }
        if d.hi <= c.lo {
            if covered(d, &has_left) >= NEIGHBOR_OVERLAP * nl as f32 {
                lbound = lbound.max(d.hi);
            }
        } else if d.lo >= c.hi
            && covered(d, &has_right) >= NEIGHBOR_OVERLAP * nr as f32
            && !hanging_indent(rows, c, d, body)
        {
            rbound = rbound.min(d.lo);
        }
    }
    let (lw, lf) = column_shape(rows, c.first, c.last, lbound, c.lo);
    let (rw, rf) = column_shape(rows, c.first, c.last, c.hi, rbound);
    let wide = lw >= MIN_COLUMN_WIDTH * body && rw >= MIN_COLUMN_WIDTH * body;
    (wide && lf >= MIN_FILL && rf >= MIN_FILL).then_some((lbound, rbound))
}

/// Share of a column's rows that must end (or start) at the same x, within
/// [`EDGE_TOL`], for that x to be the column's justified edge. Justified prose: most
/// rows (paragraph last lines and headings are the exceptions); ragged-right text has
/// no such edge and is never cut.
pub const EDGE_SHARE: f32 = 0.3;

/// Rows ending at the same justified edge agree within this many em: 0.1 pt on the
/// arXiv papers (achado 010, finding 1), and ±0.05 pt on the generated corpus
/// (finding 002).
pub const EDGE_TOL: f32 = 0.05;

/// A row intrudes into a gutter when its text passes the column's justified edge by
/// more than this many em. arXiv 2509.23299 p. 4: the `table*` cells pass the edge of
/// column 1 by 0.58 em (298.2 -> 304.0), where justified rows end within 0.01 em.
/// Small enough to keep microtype's margin kerning (hanging punctuation, about 0.1–0.2
/// em) inside the column.
pub const INTRUSION: f32 = 0.3;

/// The justified right edge of a column: the x where at least [`EDGE_SHARE`] of the
/// rows (and [`MIN_ROWS`]) end, within [`EDGE_TOL`]. The most populated cluster wins
/// (ties: the rightmost); its right end is the edge.
fn justified_edge(mut xs: Vec<f32>, body: f32) -> Option<f32> {
    xs.sort_by(|a, b| cmp(*a, *b));
    let need = ((EDGE_SHARE * xs.len() as f32).ceil() as usize).max(MIN_ROWS);
    let tol = EDGE_TOL * body;
    // (count, edge) of the best window [xs[j], xs[i]] no wider than 2 tol.
    let mut best: Option<(usize, f32)> = None;
    let mut j = 0;
    for i in 0..xs.len() {
        while xs[i] - xs[j] > 2.0 * tol {
            j += 1;
        }
        let n = i + 1 - j;
        if n >= need && best.is_none_or(|(bn, _)| n >= bn) {
            best = Some((n, xs[i]));
        }
    }
    best.map(|b| b.1)
}

/// A horizontal rule cuts a gutter when it reaches this many em into both columns.
/// arXiv 2509.23299 p. 4: the booktabs rules of the `table*` run x = 59…554 across a
/// gutter at 298…315 (achado 010, finding 1); their data rows end exactly at the column
/// edge, so only the rules (and the header row's intrusion) show the table.
pub const RULE_REACH: f32 = 2.0;

/// Splits candidate `c` at the rows whose text crosses the justified right edge of its
/// left column (bounded by `lbound`) by more than [`INTRUSION`]. Prose never passes its
/// own justified edge; a full-width table whose inner column gap happens to sit on the
/// page gutter does (arXiv `table*`, achado 010, finding 1). A ragged column (no
/// justified edge) cuts nothing.
///
/// The right column's left edge is not used: hanging reference labels (`[12]`, ACM
/// p. 5–6), list markers and outdented headings legitimately start before the edge of
/// most rows, and cutting there removed the columns of whole reference pages.
///
/// It is also split (without losing rows) between two rows separated by a horizontal
/// `rules` line that crosses it ([`RULE_REACH`]).
fn cut_intrusions(c: &Stripe, rows: &[Row], lbound: f32, rules: &[Rect], body: f32) -> Vec<Stripe> {
    let span = &rows[c.first..=c.last];
    // Figure rows carry the figure's extent, not a text edge (Word 2509.09931 p. 2: a
    // diagram filling most of column 1 made its own right side the "edge").
    let lefts: Vec<Option<(f32, f32)>> = span
        .iter()
        .map(|r| (!r.figure).then(|| r.extent_in(lbound, c.lo)).flatten())
        .collect();
    let edge = justified_edge(lefts.iter().flatten().map(|e| e.1).collect(), body);
    let intrudes =
        |k: usize| edge.is_some_and(|e| lefts[k].is_some_and(|x| x.1 > e + INTRUSION * body));
    let reach = RULE_REACH * body;
    let crossing: Vec<f32> = rules
        .iter()
        .filter(|r| r.left < c.lo - reach && r.right > c.hi + reach)
        .map(|r| (r.top + r.bottom) / 2.0)
        .collect();
    // A rule between rows k - 1 and k breaks the stripe before row k.
    let ruled = |k: usize| {
        k > 0 && {
            let (a, b) = (span[k - 1].baseline, span[k].baseline);
            crossing.iter().any(|&y| y > a && y < b)
        }
    };
    let mut out = Vec::new();
    let mut start = c.first;
    for k in 0..span.len() {
        let i = c.first + k;
        let cut = intrudes(k);
        if cut || ruled(k) {
            if i > start {
                out.push(Stripe {
                    first: start,
                    last: i - 1,
                    ..*c
                });
            }
            start = if cut { i + 1 } else { i };
        }
    }
    if start <= c.last {
        out.push(Stripe { first: start, ..*c });
    }
    out
}

/// Stripes that start at different rows can narrow onto the same gutter (each row
/// whose free interval is wider than the live stripe starts one). Gutters that
/// overlap both in x and in rows are one gutter: rows united, x intersected.
fn merge(mut gs: Vec<Gutter>) -> Vec<Gutter> {
    gs.sort_by(|a, b| a.first_row.cmp(&b.first_row).then(cmp(a.left, b.left)));
    let mut out: Vec<Gutter> = Vec::new();
    for g in gs {
        let same = out
            .iter_mut()
            .find(|m| m.left < g.right && g.left < m.right && g.first_row <= m.last_row + 1);
        match same {
            Some(m) => {
                m.left = m.left.max(g.left);
                m.right = m.right.min(g.right);
                m.last_row = m.last_row.max(g.last_row);
            }
            None => out.push(g),
        }
    }
    out
}

/// A box of the recursive decomposition: rows `first..end`, x in `[left, right)`.
#[derive(Clone, Copy, Debug)]
struct Leaf {
    first: usize,
    end: usize,
    left: f32,
    right: f32,
}

/// Maximum recursion depth of [`xy_cut`] (each level consumes one gutter; pages have a
/// handful).
const MAX_CUT_DEPTH: usize = 64;

/// Recursive XY-cut over the detected gutters (achado 012, item 5): inside the box,
/// cut along the gutter that covers the most rows; the rows above it, its left side,
/// its right side and the rows below it are then decomposed the same way, in that
/// order. A box without a gutter is a leaf (one region).
///
/// On pages whose gutters all cover the same rows this is the band model of achado 005
/// (full-width parts top to bottom, columns left to right). It differs on nested
/// layouts: USGS fs20243057 p. 1 has column 3 running from below the title to the
/// foot, next to a lead paragraph that sits above columns 1 and 2. The 2|3 gutter is
/// the longest, so column 3 is read whole after the lead paragraph and columns 1 and
/// 2, instead of being cut in two bands (achado 010, finding 4).
fn xy_cut(b: Leaf, gs: &[Gutter], out: &mut Vec<Leaf>, depth: usize) {
    if b.first >= b.end {
        return;
    }
    let rows_in = |g: &Gutter| {
        (g.last_row + 1)
            .min(b.end)
            .saturating_sub(g.first_row.max(b.first))
    };
    let best = gs
        .iter()
        .filter(|g| {
            let mid = (g.left + g.right) / 2.0;
            mid > b.left && mid < b.right && rows_in(g) > 0
        })
        .max_by(|x, y| rows_in(x).cmp(&rows_in(y)).then(cmp(y.left, x.left)));
    let Some(g) = best.filter(|_| depth < MAX_CUT_DEPTH) else {
        out.push(b);
        return;
    };
    let mid = (g.left + g.right) / 2.0;
    let (f, e) = (g.first_row.max(b.first), (g.last_row + 1).min(b.end));
    xy_cut(Leaf { end: f, ..b }, gs, out, depth + 1);
    xy_cut(
        Leaf {
            first: f,
            end: e,
            right: mid,
            ..b
        },
        gs,
        out,
        depth + 1,
    );
    xy_cut(
        Leaf {
            first: f,
            end: e,
            left: mid,
            ..b
        },
        gs,
        out,
        depth + 1,
    );
    xy_cut(Leaf { first: e, ..b }, gs, out, depth + 1);
}

/// Splits the page's words into regions in reading order. Returns each region with
/// its words (in their original relative order). A page without gutters is one
/// full-width region. Words with non-finite geometry go to the last region, so
/// nothing is lost.
///
/// Regions come from [`xy_cut`]. A region's `columns` is the number of columns at its
/// middle row (1 + the gutters covering that row) and `column` its index among them;
/// `band` numbers the runs of consecutive regions whose rows overlap.
pub fn split(words: Vec<Word>, rules: &[Rect]) -> Vec<(Region, Vec<Word>)> {
    let rs = rows(&words);
    let gs = gutters(&rs, rules, body_size(&words));
    let mut leaves = Vec::new();
    xy_cut(
        Leaf {
            first: 0,
            end: rs.len(),
            left: f32::NEG_INFINITY,
            right: f32::INFINITY,
        },
        &gs,
        &mut leaves,
        0,
    );

    // Leaf of each word.
    let mut slot: Vec<Option<usize>> = vec![None; words.len()];
    for (li, l) in leaves.iter().enumerate() {
        for row in &rs[l.first..l.end] {
            for &wi in &row.words {
                let cx = words[wi].bbox.center_x();
                if cx >= l.left && cx < l.right {
                    slot[wi] = Some(li);
                }
            }
        }
    }
    let mut used: Vec<usize> = slot.iter().flatten().copied().collect();
    used.sort_unstable();
    used.dedup();

    // Bands: regions linked by overlapping rows (union-find; a page has few regions).
    let mut root: Vec<usize> = (0..used.len()).collect();
    fn find(root: &mut [usize], mut i: usize) -> usize {
        while root[i] != i {
            root[i] = root[root[i]];
            i = root[i];
        }
        i
    }
    for i in 0..used.len() {
        for j in i + 1..used.len() {
            let (x, y) = (leaves[used[i]], leaves[used[j]]);
            if x.first < y.end && y.first < x.end {
                let (ri, rj) = (find(&mut root, i), find(&mut root, j));
                root[ri.max(rj)] = ri.min(rj);
            }
        }
    }
    let mut band_ids: Vec<usize> = Vec::new();
    let mut out: Vec<(Region, Vec<Word>)> = Vec::new();
    for (k, &li) in used.iter().enumerate() {
        let l = leaves[li];
        let r = find(&mut root, k);
        let band = match band_ids.iter().position(|&b| b == r) {
            Some(p) => p,
            None => {
                band_ids.push(r);
                band_ids.len() - 1
            }
        };
        let midrow = (l.first + l.end - 1) / 2;
        let cuts: Vec<f32> = gs
            .iter()
            .filter(|g| g.first_row <= midrow && g.last_row >= midrow)
            .map(|g| (g.left + g.right) / 2.0)
            .collect();
        let cx = if l.left.is_finite() && l.right.is_finite() {
            (l.left + l.right) / 2.0
        } else if l.left.is_finite() {
            l.left + 1.0
        } else if l.right.is_finite() {
            l.right - 1.0
        } else {
            0.0
        };
        out.push((
            Region {
                rect: Rect::new(0.0, 0.0, 0.0, 0.0),
                band,
                column: cuts.iter().filter(|m| **m < cx).count(),
                columns: cuts.len() + 1,
            },
            Vec::new(),
        ));
    }
    let mut stray = Vec::new();
    for (w, s) in words.into_iter().zip(slot) {
        match s.and_then(|li| used.binary_search(&li).ok()) {
            Some(i) => out[i].1.push(w),
            None => stray.push(w),
        }
    }
    if !stray.is_empty() {
        match out.last_mut() {
            Some(last) => last.1.extend(stray),
            None => out.push((
                Region {
                    rect: Rect::new(0.0, 0.0, 0.0, 0.0),
                    band: 0,
                    column: 0,
                    columns: 1,
                },
                stray,
            )),
        }
    }
    for (r, ws) in &mut out {
        let mut it = ws.iter().filter(|w| finite(w)).map(|w| w.bbox);
        if let Some(first) = it.next() {
            r.rect = it.fold(first, |acc, b| acc.union(&b));
        }
    }
    out
}

fn cmp(a: f32, b: f32) -> Ordering {
    a.total_cmp(&b)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::layout::Style;

    const SIZE: f32 = 10.0;

    fn word(text: &str, left: f32, right: f32, base: f32) -> Word {
        Word {
            text: text.into(),
            bbox: Rect::new(left, base - 0.9 * SIZE, right, base + 0.25 * SIZE),
            baseline: base,
            size: SIZE,
            font: "Serif".into(),
            style: Style::default(),
            glued: false,
            len: text.chars().count().max(1),
            chars: 0..0,
            figure: None,
        }
    }

    /// A justified row from `x0` to `x1`: `n` words of pseudo-random widths
    /// (deterministic, from `seed`) separated by equal stretched gaps.
    fn justified(x0: f32, x1: f32, base: f32, n: usize, seed: usize) -> Vec<Word> {
        let widths: Vec<f32> = (0..n)
            .map(|i| SIZE * (1.5 + ((seed * 7 + i * 13) % 9) as f32 * 0.4))
            .collect();
        let gap = (x1 - x0 - widths.iter().sum::<f32>()) / (n as f32 - 1.0);
        let mut x = x0;
        widths
            .iter()
            .enumerate()
            .map(|(i, w)| {
                let wd = word(&format!("w{seed}_{i}"), x, x + w, base);
                x += w + gap;
                wd
            })
            .collect()
    }

    /// Two justified columns `[x0, x0 + width]` and `[x0 + width + gutter, ...]` over
    /// `rows` rows starting at baseline `top`, with a leading of 1.2 em.
    fn two_columns(x0: f32, width: f32, gutter: f32, top: f32, rows: usize) -> Vec<Word> {
        let mut out = Vec::new();
        for r in 0..rows {
            let base = top + r as f32 * 1.2 * SIZE;
            out.extend(justified(x0, x0 + width, base, 5, r));
            let x2 = x0 + width + gutter;
            out.extend(justified(x2, x2 + width, base, 5, r + 100));
        }
        out
    }

    fn columns_per_band(parts: &[(Region, Vec<Word>)]) -> Vec<usize> {
        let mut v: Vec<usize> = parts.iter().map(|(r, _)| r.columns).collect();
        v.dedup();
        v
    }

    #[test]
    fn justified_single_column_with_wide_gaps_is_not_split() {
        // A 16 em column, 3 words per row: gaps of 3-5 em (wider than any gutter),
        // at a different x on every row.
        let mut ws = Vec::new();
        for r in 0..40 {
            ws.extend(justified(50.0, 210.0, 100.0 + r as f32 * 12.0, 3, r));
        }
        let rs = rows(&ws);
        assert!(gutters(&rs, &[], SIZE).is_empty());
        let parts = split(ws, &[]);
        assert_eq!(parts.len(), 1);
        assert_eq!(parts[0].0.columns, 1);
    }

    #[test]
    fn two_columns_with_a_narrow_gutter_are_split() {
        // LaTeX A5: 16.5 em columns, 0.75 em gutter (below LINE_SPLIT_GAP = 0.9 em).
        let ws = two_columns(42.0, 165.0, 7.5, 100.0, 40);
        let parts = split(ws, &[]);
        assert_eq!(parts.len(), 2);
        let (left, right) = (&parts[0], &parts[1]);
        assert_eq!((left.0.column, right.0.column), (0, 1));
        assert!(left.0.rect.right <= 207.01, "{:?}", left.0.rect);
        assert!(right.0.rect.left >= 214.49, "{:?}", right.0.rect);
        assert_eq!(left.1.len(), 200);
        assert_eq!(right.1.len(), 200);
    }

    #[test]
    fn full_width_title_and_abstract_above_two_columns() {
        let mut ws = vec![word("Titulo", 100.0, 300.0, 60.0)];
        for r in 0..4 {
            ws.extend(justified(42.0, 372.0, 90.0 + r as f32 * 12.0, 9, r + 50));
        }
        // Last line of the abstract: short, it stops before the gutter.
        ws.push(word("fim.", 42.0, 80.0, 138.0));
        ws.extend(two_columns(42.0, 160.0, 10.0, 170.0, 30));
        let parts = split(ws, &[]);
        assert_eq!(columns_per_band(&parts), [1, 2]);
        // The abstract's last line stays in the full-width band, with its paragraph.
        assert_eq!(parts[0].1.len(), 1 + 4 * 9 + 1);
        assert_eq!((parts[1].0.band, parts[1].0.column), (1, 0));
        assert_eq!((parts[2].0.band, parts[2].0.column), (1, 1));
    }

    #[test]
    fn right_column_starting_higher_is_still_read_after_the_left_one() {
        // LibreOffice page 1: a 28 pt title on top of column 1 puts its first baseline
        // below the first line of column 2.
        let mut ws = two_columns(42.0, 160.0, 14.0, 130.0, 30);
        ws.extend(justified(216.0, 376.0, 106.0, 5, 7));
        ws.extend(justified(216.0, 376.0, 118.0, 5, 8));
        let mut title = word("Titulo", 42.0, 150.0, 125.0);
        title.size = 28.0;
        ws.push(title);
        let parts = split(ws, &[]);
        let regions: Vec<&Region> = parts.iter().map(|p| &p.0).collect();
        assert_eq!(parts.len(), 2, "{regions:?}");
        assert!(parts[1].1.iter().any(|w| w.baseline == 106.0));
    }

    #[test]
    fn columns_with_independent_baselines() {
        // Chrome and LibreOffice: the two columns do not share baselines.
        let mut ws = Vec::new();
        for r in 0..30 {
            ws.extend(justified(42.0, 202.0, 100.0 + r as f32 * 12.7, 5, r));
            ws.extend(justified(216.0, 376.0, 106.0 + r as f32 * 12.7, 5, r + 9));
        }
        assert_eq!(split(ws, &[]).len(), 2);
    }

    #[test]
    fn table_is_not_split_into_page_columns() {
        // Four columns, 8 rows, short ragged cells 1-3 em apart (the kitchen-sink
        // table): every cell gap is empty in every row, and the first column is wide.
        let mut ws = vec![word("Texto", 50.0, 500.0, 80.0)];
        let widths = [[40.0, 25.0, 55.0, 30.0], [30.0, 45.0, 20.0, 50.0]];
        for r in 0..8 {
            let base = 100.0 + r as f32 * 12.0;
            let w = widths[r % 2];
            ws.push(word("a", 70.0, 70.0 + w[0] + 80.0, base));
            ws.push(word("b", 230.0, 230.0 + w[1], base));
            ws.push(word("c", 300.0, 300.0 + w[2], base));
            ws.push(word("d", 380.0, 380.0 + w[3] + 60.0, base));
        }
        ws.push(word("Texto", 50.0, 500.0, 210.0));
        let rs = rows(&ws);
        assert!(gutters(&rs, &[], SIZE).is_empty());
        assert_eq!(split(ws, &[]).len(), 1);
    }

    #[test]
    fn two_column_table_with_short_cells_is_not_split() {
        // Term | definition: the left cells are short and ragged (low fill).
        let mut ws = Vec::new();
        let terms = [30.0, 45.0, 25.0, 140.0, 35.0, 50.0, 28.0, 40.0, 33.0, 60.0];
        for (r, t) in terms.iter().enumerate() {
            let base = 100.0 + r as f32 * 12.0;
            ws.push(word("termo", 50.0, 50.0 + t, base));
            ws.extend(justified(210.0, 500.0, base, 8, r));
        }
        assert!(gutters(&rows(&ws), &[], SIZE).is_empty());
    }

    #[test]
    fn list_with_hanging_indent_is_not_a_gutter() {
        // Marker -> text gap of 0.5 em, empty in every row of the list.
        let mut ws = Vec::new();
        for r in 0..20 {
            let base = 100.0 + r as f32 * 12.0;
            if r % 2 == 0 {
                ws.push(word("•", 50.0, 54.0, base));
            }
            ws.extend(justified(59.0, 300.0, base, 6, r));
        }
        assert!(gutters(&rows(&ws), &[], SIZE).is_empty());
    }

    #[test]
    fn three_columns() {
        let mut ws = Vec::new();
        for r in 0..30 {
            let base = 100.0 + r as f32 * 12.0;
            for (c, x0) in [40.0, 165.0, 290.0].into_iter().enumerate() {
                ws.extend(justified(x0, x0 + 115.0, base, 4, r * 3 + c));
            }
        }
        let parts = split(ws, &[]);
        let cols: Vec<(usize, usize)> = parts.iter().map(|p| (p.0.column, p.0.columns)).collect();
        assert_eq!(cols, [(0, 3), (1, 3), (2, 3)]);
    }

    #[test]
    fn full_width_element_between_two_column_sections() {
        // Columns, a full-width figure caption crossing the gutter, columns again:
        // read top section left/right, the caption, then bottom section left/right.
        let mut ws = two_columns(42.0, 160.0, 10.0, 100.0, 15);
        ws.push(word("Figura", 42.0, 372.0, 290.0));
        ws.extend(two_columns(42.0, 160.0, 10.0, 310.0, 15));
        let parts = split(ws, &[]);
        let order: Vec<(usize, usize)> = parts.iter().map(|p| (p.0.band, p.0.column)).collect();
        assert_eq!(order, [(0, 0), (0, 1), (1, 0), (2, 0), (2, 1)]);
        assert_eq!(parts[2].1[0].text, "Figura");
    }

    fn figure_word(text: &str, left: f32, right: f32, base: f32, rect: Rect) -> Word {
        let mut w = word(text, left, right, base);
        w.size = 5.0;
        w.figure = Some(crate::layout::Figure { object: 7, rect });
        w
    }

    #[test]
    fn diagram_labels_inside_a_column_do_not_cancel_the_gutter() {
        // Word 2509.09931 p. 2: column 1 is mostly a diagram whose two stacks of boxes
        // leave a 3 em gap over 30 rows; a few prose rows at the bottom.
        let rect = Rect::new(60.0, 100.0, 200.0, 460.0);
        let mut ws = Vec::new();
        for r in 0..30 {
            let base = 110.0 + r as f32 * 12.0;
            ws.push(figure_word("Conv", 62.0, 110.0, base, rect));
            ws.push(figure_word("Pool", 140.0, 198.0, base, rect));
        }
        for r in 0..8 {
            ws.extend(justified(42.0, 202.0, 480.0 + r as f32 * 12.0, 5, r));
        }
        for r in 0..40 {
            ws.extend(justified(216.0, 376.0, 110.0 + r as f32 * 12.0, 5, r + 50));
        }
        // A misplaced Type3 glyph of the figure, far outside its form, in column 2.
        ws.push(figure_word("*", 300.0, 305.0, 300.0, rect));
        let parts = split(ws, &[]);
        let cols: Vec<(usize, usize, usize)> = parts
            .iter()
            .map(|p| (p.0.column, p.0.columns, p.1.len()))
            .collect();
        assert_eq!(cols, [(0, 2, 60 + 40), (1, 2, 200 + 1)], "{cols:?}");
    }

    #[test]
    fn full_width_figure_still_cuts_the_gutter() {
        let rect = Rect::new(40.0, 280.0, 380.0, 330.0);
        let mut ws = two_columns(42.0, 160.0, 10.0, 100.0, 15);
        for r in 0..3 {
            let base = 290.0 + r as f32 * 12.0;
            ws.push(figure_word("a", 50.0, 80.0, base, rect));
            ws.push(figure_word("b", 340.0, 370.0, base, rect));
        }
        ws.extend(two_columns(42.0, 160.0, 10.0, 340.0, 15));
        let order: Vec<(usize, usize)> = split(ws, &[])
            .iter()
            .map(|p| (p.0.band, p.0.column))
            .collect();
        assert_eq!(order, [(0, 0), (0, 1), (1, 0), (2, 0), (2, 1)]);
    }

    #[test]
    fn hanging_indent_list_next_to_the_gutter_does_not_cancel_it() {
        // USGS p. 1: column 2 is a long list whose `•` sits on the column edge and
        // whose text starts 0.7 em after it, so the marker -> text gap is empty in
        // every row (≥ MIN_GUTTER) and used to bound column 2 to the marker.
        let mut ws = Vec::new();
        for r in 0..40 {
            let base = 100.0 + r as f32 * 12.0;
            ws.extend(justified(42.0, 202.0, base, 5, r));
            if r % 5 == 0 {
                ws.push(word("•", 222.0, 225.3, base));
            }
            ws.extend(justified(232.3, 382.0, base, 5, r + 60));
        }
        let parts = split(ws, &[]);
        let cols: Vec<(usize, usize)> = parts.iter().map(|p| (p.0.column, p.0.columns)).collect();
        assert_eq!(cols, [(0, 2), (1, 2)]);
        assert!(parts[1].1.iter().any(|w| w.text == "•"));
    }

    /// arXiv `table*` (2509.23299 p. 4): a full-width table on top whose inner column
    /// gap sits on the page gutter, rows ending exactly at the column edges, then two
    /// justified columns.
    fn table_star(header_intrudes: bool) -> Vec<Word> {
        let mut ws = Vec::new();
        for r in 0..8 {
            let base = 100.0 + r as f32 * 12.0;
            ws.push(word("System", 42.0, 90.0, base));
            ws.push(word("1.234", 180.0, 202.0, base));
            ws.push(word("2.345", 216.0, 238.0, base));
            ws.push(word("3.456", 350.0, 372.0, base));
        }
        if header_intrudes {
            // `OVRL ↑` passes the edge of column 1 by 0.58 em.
            ws.push(word("OVRL", 180.0, 207.8, 88.0));
            ws.push(word("SIG", 216.0, 236.0, 88.0));
        }
        ws.extend(two_columns(42.0, 160.0, 14.0, 210.0, 30));
        ws
    }

    fn bands(parts: &[(Region, Vec<Word>)]) -> Vec<(usize, usize, usize)> {
        parts
            .iter()
            .map(|p| (p.0.band, p.0.column, p.0.columns))
            .collect()
    }

    #[test]
    fn full_width_table_on_the_gutter_is_cut_by_its_rules() {
        let ws = table_star(false);
        // Without rules the table is split into the page columns (achado 010).
        assert_eq!(bands(&split(ws.clone(), &[])), [(0, 0, 2), (0, 1, 2)]);
        let rules: Vec<Rect> = [94.0, 106.0, 190.0]
            .iter()
            .map(|&y| Rect::new(42.0, y, 372.0, y + 0.8))
            .collect();
        let parts = split(ws, &rules);
        assert_eq!(bands(&parts), [(0, 0, 1), (1, 0, 2), (1, 1, 2)]);
        assert_eq!(parts[0].1.len(), 8 * 4);
        // A rule inside one column does not cut the gutter.
        let inner = [Rect::new(42.0, 300.0, 202.0, 300.8)];
        assert_eq!(bands(&split(table_star(false), &inner)).len(), 2);
    }

    #[test]
    fn text_passing_the_justified_edge_cuts_the_gutter() {
        // Without rules, the intruding header row cuts the gutter and goes full
        // width; the table rows below it end at the column edges and stay in the
        // columns (on the real page the rules move them out too).
        let parts = split(table_star(true), &[]);
        assert_eq!(bands(&parts)[0], (0, 0, 1));
        assert!(parts[0].1.iter().any(|w| w.text == "OVRL"));
        // A justified two-column page is not cut.
        let plain = two_columns(42.0, 160.0, 14.0, 100.0, 40);
        assert_eq!(bands(&split(plain, &[])), [(0, 0, 2), (0, 1, 2)]);
    }

    #[test]
    fn table_in_one_column_with_its_own_baselines_does_not_bound_it() {
        // arXiv 2509.23299 p. 4, Table 2: cells in column 1 on baselines that column 2
        // does not share, so the table covers many page rows but few column-1 rows.
        let mut ws = Vec::new();
        for r in 0..40 {
            let base = 100.0 + r as f32 * 12.0;
            ws.extend(justified(216.0, 376.0, base, 5, r + 30));
            if !(10..16).contains(&r) {
                ws.extend(justified(42.0, 202.0, base, 5, r));
            }
        }
        for r in 0..6 {
            // Six table rows between rows 10 and 16 of column 2, offset baselines,
            // with 2 em gaps between cells.
            let base = 100.0 + 10.0 * 12.0 + 6.0 + r as f32 * 13.0;
            ws.push(word("a", 42.0, 90.0, base));
            ws.push(word("1.0", 110.0, 140.0, base));
            ws.push(word("2.0", 160.0, 202.0, base));
        }
        let parts = split(ws, &[]);
        assert_eq!(bands(&parts), [(0, 0, 2), (0, 1, 2)]);
    }

    #[test]
    fn nested_layout_reads_the_long_column_whole() {
        // USGS p. 1: a lead paragraph over columns 1-2, column 3 from the top to the
        // foot. Reading order: lead, column 1, column 2, column 3 (not lead, top of
        // column 3, columns 1-2, rest of column 3).
        let mut ws = Vec::new();
        for r in 0..40 {
            let base = 100.0 + r as f32 * 12.0;
            if r < 8 {
                ws.extend(justified(40.0, 280.0, base, 8, r));
            } else {
                ws.extend(justified(40.0, 155.0, base, 4, r));
                ws.extend(justified(165.0, 280.0, base, 4, r + 50));
            }
            ws.extend(justified(290.0, 405.0, base, 4, r + 100));
        }
        let parts = split(ws, &[]);
        let firsts: Vec<(usize, &str)> = parts
            .iter()
            .map(|p| (p.0.columns, p.1[0].text.as_str()))
            .collect();
        assert_eq!(
            firsts,
            [(2, "w0_0"), (3, "w8_0"), (3, "w58_0"), (3, "w100_0")]
        );
        assert_eq!(parts[3].1.len(), 40 * 4);
    }

    #[test]
    fn garbage_does_not_panic_and_keeps_every_word() {
        let mut ws = two_columns(42.0, 160.0, 10.0, 100.0, 20);
        let mut bad = word("x", f32::NAN, 1.0, 50.0);
        bad.size = f32::INFINITY;
        ws.push(bad);
        ws.push(word("y", 10.0, 5.0, f32::NAN));
        let n = ws.len();
        let parts = split(ws, &[]);
        assert_eq!(parts.iter().map(|p| p.1.len()).sum::<usize>(), n);
        assert!(split(Vec::new(), &[]).is_empty());
        assert!(gutters(&[], &[], SIZE).is_empty());
    }

    #[test]
    fn deterministic() {
        let ws = two_columns(42.0, 160.0, 10.0, 100.0, 20);
        assert_eq!(split(ws.clone(), &[]), split(ws, &[]));
    }
}