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
//! Grouping heuristics: characters → words → lines → blocks.
//!
//! Pure functions over our own types (no PDFium), so they are unit-tested with
//! synthetic characters. Every tolerance is relative to the font size and documented
//! with the observation that motivated it (docs/achados/004-agrupamento-linhas-blocos.md).

use std::cmp::Ordering;

use super::columns::{self, Region};
use super::furniture;
use super::{Block, Char, Line, Page, Rect, Style, Word};

// ---------------------------------------------------------------- words

/// A horizontal gap larger than this fraction of the font size splits a word even
/// without a space character. Kerning and rounding gaps seen in the corpus stay below
/// 0.05 em (LaTeX `p`→`d` in "pdfsift": 0.5 pt at 17 pt; Chrome `Intr`|`odução`, two
/// text objects, overlap by 0.4 pt at 24 pt), while the narrowest word space is about
/// 0.25 em (Chrome: 3.0 pt at 12 pt). LaTeX emits no space characters at all; PDFium
/// synthesizes them, so this is only a safety net for spaces PDFium does not infer.
pub const WORD_GAP: f32 = 0.15;

/// A character whose left edge is this far (in em) to the LEFT of the previous
/// character's left edge starts a new word: the stream jumped back (new line, new
/// column, out-of-order text). Measured from the previous LEFT edge, not its right
/// edge, because PDFium decomposes ligatures into characters that all carry the
/// ligature's box (LaTeX `fi` → `f` 211.1..216.8 and `i` 211.1..216.8), which looks like
/// a 0.57 em overlap from the right edge.
pub const BACKTRACK: f32 = 0.1;

/// Two characters whose baselines differ by more than this fraction of the (smaller)
/// font size are not in the same word. Within a line the baseline is exact in all
/// four producers; a superscript moves it by ~0.4 em (Chrome footnote mark: 5 pt at
/// 12 pt; LaTeX: 3.5 pt at 10 pt).
pub const BASELINE_TOL: f32 = 0.15;

/// Font sizes within this relative difference count as the same size.
pub const SIZE_TOL: f32 = 0.05;

/// Splits characters (in PDFium text order) into words.
///
/// Word boundaries: any whitespace (real or PDFium-generated), a gap wider than
/// [`WORD_GAP`], a jump back, or a baseline change. A change of font, size or style
/// without a gap also ends the word, but the next one is marked `glued`, so the text
/// is rebuilt without an invented space (`negrito` + `,`).
///
/// PDFium-generated spaces are trusted as word breaks: PDFium inserts them from the
/// same kind of gap analysis, and LaTeX output has no other spaces. Generated
/// `\r\n` are just separators; lines are rebuilt geometrically afterwards.
#[cfg(test)]
pub fn words(chars: &[Char]) -> Vec<Word> {
    words_with_hints(chars).0
}

/// [`words`], plus one [`furniture::Hint`] per word: [`furniture::Hint::Pagination`]
/// when every char of the word is inside a pagination artifact (achado 009).
pub fn words_with_hints(chars: &[Char]) -> (Vec<Word>, Vec<furniture::Hint>) {
    let hint = |all_pagination: bool| {
        if all_pagination {
            furniture::Hint::Pagination
        } else {
            furniture::Hint::None
        }
    };
    let is_pagination = |c: &Char| c.source.artifact.as_ref().is_some_and(|a| a.pagination);
    let mut hints = Vec::new();
    let mut pagination = false;
    let mut out: Vec<Word> = Vec::new();
    let mut cur: Option<Word> = None;
    let mut space_pending = true;
    let mut last_left = f32::NEG_INFINITY;
    for (i, c) in chars.iter().enumerate() {
        if c.ch.is_whitespace() || c.ch.is_control() || c.ch == '\u{FFFE}' {
            if let Some(w) = cur.take() {
                out.push(w);
                hints.push(hint(pagination));
            }
            space_pending = true;
            continue;
        }
        if c.size <= 0.0 || c.bbox.width() < 0.0 {
            continue;
        }
        if let Some(mut w) = cur.take() {
            let size = w.size.min(c.size);
            let gap = c.bbox.left - w.bbox.right;
            let same_base = (c.baseline - w.baseline).abs() <= BASELINE_TOL * size;
            let adjacent = gap <= WORD_GAP * size && c.bbox.left >= last_left - BACKTRACK * size;
            let same_font = c.font == w.font && c.style == w.style && same_size(c.size, w.size);
            last_left = c.bbox.left;
            if same_base && adjacent && same_font {
                if w.figure != c.source.figure {
                    w.figure = None;
                }
                w.text.push(c.ch);
                w.bbox = w.bbox.union(&c.bbox);
                w.len += 1;
                w.chars.end = i + 1;
                pagination &= is_pagination(c);
                cur = Some(w);
                continue;
            }
            // Different font right next to the previous word: no space between them.
            space_pending = !(same_base && adjacent);
            out.push(w);
            hints.push(hint(pagination));
        }
        pagination = is_pagination(c);
        cur = Some(Word {
            text: c.ch.to_string(),
            bbox: c.bbox,
            baseline: c.baseline,
            size: c.size,
            font: c.font.clone(),
            style: c.style,
            glued: !space_pending && !out.is_empty(),
            len: 1,
            chars: i..i + 1,
            figure: c.source.figure,
        });
        space_pending = false;
        last_left = c.bbox.left;
    }
    if let Some(w) = cur {
        out.push(w);
        hints.push(hint(pagination));
    }
    (out, hints)
}

fn same_size(a: f32, b: f32) -> bool {
    (a - b).abs() <= SIZE_TOL * a.max(b)
}

// ---------------------------------------------------------------- lines

/// The "core" of a word is the band from `baseline - CORE * size` to the baseline
/// (roughly x-height to cap-height). Loose boxes are too tall to compare lines:
/// PDFium's loose box is 1.41 em high (LaTeX 10 pt: 14.1 pt) while lines are 1.2 em
/// apart, so loose boxes of consecutive lines overlap. Cores of consecutive lines never
/// overlap as long as the leading is at least `CORE` em.
pub const CORE: f32 = 0.6;

/// A smaller-font group of words is a superscript/subscript of a line when its core
/// overlaps the line's core by at least this fraction of its own core height.
/// LaTeX footnote mark (7 pt, 3.5 pt above a 10 pt baseline): 2.5 / 4.2 ≈ 0.6;
/// Chrome (10 pt, 5 pt above a 12 pt baseline): 2.2 / 6 ≈ 0.37.
pub const SCRIPT_OVERLAP: f32 = 0.3;

/// A word group is only a script candidate if its size is at most this fraction of the
/// line's size (LaTeX 7/10, Chrome 10/12 ≈ 0.83).
pub const SCRIPT_MAX_RATIO: f32 = 0.9;

/// Words on the same baseline separated by more than this many em are put in
/// different lines: they belong to different columns or table cells. Observed:
/// justified prose stretches word spaces to at most 0.60 em (a LaTeX line) and a list
/// marker sits 0.46–0.59 em before its text, while table columns are at least 1.00 em
/// apart (Chrome `4|Tipografia`; LaTeX 1.19, Typst 1.09) and running headers/footers
/// 25–40 em.
/// Exception that no threshold can fix: LibreOffice puts a right-aligned number column
/// 0.35 em from the next column (`4 Tipografia`), so those two cells stay together.
pub const LINE_SPLIT_GAP: f32 = 0.9;

/// Same as [`LINE_SPLIT_GAP`] between two monospaced words: code aligns with runs of
/// spaces, and one space is already 0.5–0.6 em (Typst, LibreOffice, Chrome).
pub const LINE_SPLIT_GAP_MONO: f32 = 3.0;

/// A row is a justified prose line, never split at wide gaps, when it spans its whole
/// column (both ends within [`ALIGN_TOL`] of the column's edges), has a line of the
/// same size within [`MAX_LEADING`] above or below (running headers and footers that
/// span the page, `TABELAS … 2`, are isolated), and its largest word gap is at most
/// this factor times its smallest one. Justification stretches every
/// gap of a line by the same amount, so a very loose line keeps uniform gaps, while a
/// table row mixes intra-cell spaces (~0.25 em) with cell gaps (≥ 1 em). Measured on
/// the two-columns corpus (finding 005): the ~50 justified lines whose widest gap
/// exceeds [`LINE_SPLIT_GAP`] (up to 3.7 em in Chrome, which justifies without
/// hyphenating) have ratios of 1.00–1.01, except one LaTeX line with a sentence
/// space (see [`SENTENCE_GAP_RATIO`]); rows that span their region and are not
/// prose measure 4.5 (Typst run-in heading `Resumo`), 41 (Chrome running header) and
/// 66 (a LibreOffice kitchen-sink table row).
pub const JUSTIFIED_RATIO: f32 = 1.5;

/// A gap after sentence punctuation (`.` `!` `?` `:`) may be up to this factor times
/// the line's smallest other gap: TeX without French spacing stretches it more
/// (LaTeX `ções.` → `Sejam`: 1.87 em against 0.81 em, ratio 2.32, finding 005).
pub const SENTENCE_GAP_RATIO: f32 = 3.0;

/// Groups words into lines: baseline clustering, then superscripts/subscripts merged
/// into the line they decorate, then splitting at very wide horizontal gaps.
/// Lines are returned top to bottom, then left to right. Without a column extent, so
/// justified lines are not recognised (see [`lines_in`]); kept for tests.
#[cfg(test)]
pub fn lines(words: Vec<Word>) -> Vec<Line> {
    lines_in(words, None)
}

/// [`lines`] for the words of one region (a column or a full-width band) whose
/// horizontal extent is `column` (left, right): rows that are justified across the
/// whole column are not split at their wide gaps (see [`JUSTIFIED_RATIO`]).
pub fn lines_in(words: Vec<Word>, column: Option<(f32, f32)>) -> Vec<Line> {
    // (stream index, word): the index tells whether two words were consecutive in the
    // content stream, which is what makes `glued` meaningful after sorting by x.
    let mut items: Vec<(usize, Word)> = words.into_iter().enumerate().collect();
    items.sort_by(|a, b| {
        cmp_f32(a.1.baseline, b.1.baseline)
            .then(cmp_f32(a.1.bbox.left, b.1.bbox.left))
            .then(a.0.cmp(&b.0))
    });

    // 1. Baseline clusters.
    let mut clusters: Vec<Vec<(usize, Word)>> = Vec::new();
    for it in items {
        if let Some(c) = clusters.last_mut() {
            let ref_base = c[0].1.baseline;
            let size = c[0].1.size.min(it.1.size);
            if (it.1.baseline - ref_base).abs() <= BASELINE_TOL * size {
                c.push(it);
                continue;
            }
        }
        clusters.push(vec![it]);
    }

    // 2. Merge script clusters into the line they decorate.
    let mut merged = vec![false; clusters.len()];
    for i in 0..clusters.len() {
        let (size_i, core_i, extent_i) = cluster_metrics(&clusters[i]);
        let mut best: Option<(usize, f32)> = None;
        for (j, other) in clusters.iter().enumerate() {
            if i == j || merged[j] {
                continue;
            }
            let (size_j, core_j, extent_j) = cluster_metrics(other);
            if size_i > SCRIPT_MAX_RATIO * size_j {
                continue;
            }
            let overlap = (core_i.1.min(core_j.1) - core_i.0.max(core_j.0)).max(0.0);
            let near = extent_i.0 <= extent_j.1 + size_j && extent_i.1 >= extent_j.0 - size_j;
            if near
                && overlap >= SCRIPT_OVERLAP * (core_i.1 - core_i.0)
                && best.is_none_or(|(_, o)| overlap > o)
            {
                best = Some((j, overlap));
            }
        }
        if let Some((j, _)) = best {
            let moved = std::mem::take(&mut clusters[i]);
            clusters[j].extend(moved);
            merged[i] = true;
        }
    }

    // Baseline and size of every (merged) row, to tell a justified line inside a
    // paragraph from an isolated running header or footer that also spans the column.
    let rows: Vec<(f32, f32)> = clusters
        .iter()
        .filter(|c| !c.is_empty())
        .map(|c| {
            let (size, core, _) = cluster_metrics(c);
            (core.1, size)
        })
        .collect();

    // 3. Sort each line left to right, split at wide gaps, build `Line`s.
    let mut out = Vec::new();
    for mut c in clusters.into_iter().filter(|c| !c.is_empty()) {
        c.sort_by(|a, b| cmp_f32(a.1.bbox.left, b.1.bbox.left).then(a.0.cmp(&b.0)));
        let size = dominant_size(c.iter().map(|(_, w)| (w.size, w.len)));
        let base = cluster_metrics(&c).1.1;
        let has_neighbour = rows.iter().any(|&(b, sz)| {
            let step = (b - base).abs();
            same_size(sz, size) && step > BASELINE_TOL * size && step <= MAX_LEADING * size
        });
        let justified = has_neighbour && column.is_some_and(|col| is_justified(&c, col, size));
        let mut part: Vec<Word> = Vec::new();
        let mut prev_seq: Option<usize> = None;
        let mut split_once = false;
        for (seq, mut w) in c {
            if let Some(last) = part.last() {
                let gap = w.bbox.left - last.bbox.right;
                let limit = if w.style.mono && last.style.mono {
                    LINE_SPLIT_GAP_MONO
                } else {
                    LINE_SPLIT_GAP
                };
                // A lone leading marker keeps its text even across a wide gap
                // (LibreOffice footnote: `1` then 0.91 em then `Notas`).
                // Only at the very start of the row: a number starting a later cell
                // (`4 Tipografia`) must still be split from the cell before it.
                let lone_marker = !split_once && part.len() == 1 && is_marker_or_number(&last.text);
                if gap > limit * size && !lone_marker && !justified {
                    out.push(make_line(std::mem::take(&mut part)));
                    prev_seq = None;
                    split_once = true;
                }
            }
            // `glued` is only trusted when the two words were consecutive in the stream.
            if prev_seq.is_none_or(|p| p + 1 != seq) {
                w.glued = match part.last() {
                    Some(last) => w.bbox.left - last.bbox.right <= WORD_GAP * size,
                    None => false,
                };
            }
            if part.is_empty() {
                w.glued = false;
            }
            prev_seq = Some(seq);
            part.push(w);
        }
        if !part.is_empty() {
            out.push(make_line(part));
        }
    }
    out.sort_by(|a, b| cmp_f32(a.baseline, b.baseline).then(cmp_f32(a.bbox.left, b.bbox.left)));
    out
}

/// See [`JUSTIFIED_RATIO`]. `c` is sorted left to right.
fn is_justified(c: &[(usize, Word)], (left, right): (f32, f32), size: f32) -> bool {
    let (Some(first), Some(last)) = (c.first(), c.last()) else {
        return false;
    };
    if c.iter().any(|(_, w)| w.style.mono) {
        return false;
    }
    let tol = ALIGN_TOL * size;
    if (first.1.bbox.left - left).abs() > tol || (right - last.1.bbox.right).abs() > tol {
        return false;
    }
    // Word gaps only: kerning seams and style changes without a space are not gaps.
    // (gap, follows sentence punctuation)
    let gaps: Vec<(f32, bool)> = c
        .windows(2)
        .map(|p| {
            let end = p[0].1.text.chars().last();
            let sentence = matches!(end, Some('.' | '!' | '?' | ':'));
            (p[1].1.bbox.left - p[0].1.bbox.right, sentence)
        })
        .filter(|(g, _)| *g > WORD_GAP * size)
        .collect();
    let plain = gaps.iter().filter(|g| !g.1).map(|g| g.0);
    let min = plain.clone().fold(f32::INFINITY, f32::min);
    let max = plain.fold(f32::NEG_INFINITY, f32::max);
    let sentence_max = gaps
        .iter()
        .filter(|g| g.1)
        .map(|g| g.0)
        .fold(f32::NEG_INFINITY, f32::max);
    min.is_finite() && max <= JUSTIFIED_RATIO * min && sentence_max <= SENTENCE_GAP_RATIO * min
}

fn is_marker_or_number(t: &str) -> bool {
    is_marker(t) || (t.chars().count() <= 3 && t.chars().all(|c| c.is_ascii_digit()))
}

/// Text that is drawn with vector paths instead of glyphs: Chrome draws list bullets as
/// small filled discs (3.8 × 3.8 pt), circles (5.6 × 5.6 pt) and squares, so they
/// never appear in the character stream. A small, roughly square path sitting on a
/// line's core, just left of its first word, becomes a synthetic `•` word.
pub const PATH_MARKER_MAX: f32 = 0.6;
/// Minimum side of a path marker, in em (excludes dots and hairlines).
pub const PATH_MARKER_MIN: f32 = 0.15;
/// Maximum distance from the marker's right edge to the line's first word, in em
/// (Chrome: 8.6 pt at 12 pt ≈ 0.7 em).
pub const PATH_MARKER_GAP: f32 = 1.5;

/// Prepends a synthetic `•` word to every line that a vector bullet (from `marks`,
/// candidate path bounding boxes) sits in front of. Lines are re-sorted.
pub fn attach_path_markers(lines: &mut [Line], marks: &[Rect]) {
    for m in marks {
        let (w, h) = (m.width(), m.height());
        let target = lines.iter_mut().find(|l| {
            let size = l.size;
            let core = Rect::new(
                l.bbox.left,
                l.baseline - CORE * size,
                l.bbox.right,
                l.baseline,
            );
            let square = w <= PATH_MARKER_MAX * size
                && h <= PATH_MARKER_MAX * size
                && w >= PATH_MARKER_MIN * size
                && h >= PATH_MARKER_MIN * size
                && w <= 1.5 * h
                && h <= 1.5 * w;
            let mid = (m.top + m.bottom) / 2.0;
            let gap = l.bbox.left - m.right;
            square
                && mid >= core.top
                && mid <= core.bottom
                && gap >= 0.0
                && gap <= PATH_MARKER_GAP * size
                && !starts_with_marker(l)
        });
        if let Some(l) = target {
            if let Some(w) = l.words.first_mut() {
                w.glued = false;
            }
            l.words.insert(
                0,
                Word {
                    text: "•".into(),
                    bbox: *m,
                    baseline: l.baseline,
                    size: l.size,
                    font: String::from("(vector path)"),
                    style: Style::default(),
                    glued: false,
                    len: 1,
                    // Drawn, not text: no chars.
                    chars: 0..0,
                    figure: None,
                },
            );
            l.bbox = l.bbox.union(m);
        }
    }
}

/// (dominant size, core band (top, bottom), horizontal extent (left, right)).
fn cluster_metrics(c: &[(usize, Word)]) -> (f32, (f32, f32), (f32, f32)) {
    let size = dominant_size(c.iter().map(|(_, w)| (w.size, w.len)));
    let base = c
        .iter()
        .find(|(_, w)| same_size(w.size, size))
        .map_or(0.0, |(_, w)| w.baseline);
    let left = c
        .iter()
        .map(|(_, w)| w.bbox.left)
        .fold(f32::INFINITY, f32::min);
    let right = c
        .iter()
        .map(|(_, w)| w.bbox.right)
        .fold(f32::NEG_INFINITY, f32::max);
    (size, (base - CORE * size, base), (left, right))
}

fn make_line(words: Vec<Word>) -> Line {
    let size = dominant_size(words.iter().map(|w| (w.size, w.len)));
    let baseline = words
        .iter()
        .find(|w| same_size(w.size, size))
        .map_or(0.0, |w| w.baseline);
    let style = majority_style(words.iter().map(|w| (w.style, w.len)));
    let bbox = union_all(words.iter().map(|w| w.bbox));
    Line {
        words,
        bbox,
        baseline,
        size,
        style,
    }
}

// ---------------------------------------------------------------- blocks

/// Maximum baseline-to-baseline step (in em) between two lines of a block.
/// Observed leading inside blocks: LaTeX 1.20, Typst 1.31 (code 1.41), LibreOffice
/// 1.15, Chrome 1.12 (code 1.25). Paragraph-to-paragraph steps are 1.79 or more in
/// every producer; table rows step 1.50 (Chrome) and 1.75 (Typst), so those rows end
/// up as separate blocks while LaTeX/LibreOffice rows (1.20/1.15) stay together.
pub const MAX_LEADING: f32 = 1.45;

/// Once a block has two lines its own leading is known; a later line may be at most
/// this factor farther. Chrome grows a line box that holds a superscript: 1.12 em
/// becomes 1.40 em (factor 1.25) for the line with the footnote mark.
pub const LEADING_GROWTH: f32 = 1.3;

/// Lefts (or centers) within this many em count as aligned.
pub const ALIGN_TOL: f32 = 0.5;

/// A first line may be indented by up to this many em relative to the continuation
/// lines (paragraph first-line indent, typically 1–2 em).
pub const MAX_FIRST_INDENT: f32 = 3.0;

/// Groups lines into blocks. A line joins the block whose last line is just above it
/// when the vertical step, alignment and typography are all compatible; a line that
/// starts with a list marker always starts a new block (one block per list item).
pub fn blocks(lines: Vec<Line>) -> Vec<Block> {
    let mut groups: Vec<Vec<Line>> = Vec::new();
    for line in lines {
        // The open block whose last line is the closest one above and horizontally
        // overlapping this line.
        let mut best: Option<(usize, f32)> = None;
        for (i, g) in groups.iter().enumerate() {
            let Some(prev) = g.last() else { continue };
            let step = line.baseline - prev.baseline;
            if step <= 0.0 {
                continue;
            }
            let bbox = union_all(g.iter().map(|l| l.bbox));
            if bbox.h_overlap(&line.bbox) <= 0.0 {
                continue;
            }
            if best.is_none_or(|(_, s)| step < s) {
                best = Some((i, step));
            }
        }
        match best {
            Some((i, _)) if joins(&groups[i], &line) => groups[i].push(line),
            _ => groups.push(vec![line]),
        }
    }
    groups.into_iter().map(make_block).collect()
}

/// Whether `line` continues the block made of `g` (non-empty).
fn joins(g: &[Line], line: &Line) -> bool {
    let (Some(first), Some(prev)) = (g.first(), g.last()) else {
        return false;
    };
    let size = prev.size.max(line.size);
    if !same_size(prev.size, line.size) || first.style.bold != line.style.bold {
        return false;
    }
    if first.style.mono != line.style.mono {
        return false;
    }
    if starts_with_marker(line) {
        return false;
    }
    let step = line.baseline - prev.baseline;
    let max_step = if g.len() >= 2 {
        let lead = g[1].baseline - g[0].baseline;
        (lead * LEADING_GROWTH).min(MAX_LEADING * size)
    } else {
        MAX_LEADING * size
    };
    if step > max_step {
        return false;
    }
    let tol = ALIGN_TOL * size;
    let aligned = |a: f32, b: f32| (a - b).abs() <= tol;
    let left = line.bbox.left;
    // Code keeps its indentation: any line starting at or right of the block's left.
    if first.style.mono && line.style.mono && left >= first.bbox.left - tol {
        return true;
    }
    if aligned(left, prev.bbox.left) || aligned(line.bbox.center_x(), prev.bbox.center_x()) {
        return true;
    }
    if g.len() == 1 {
        // First-line indent: continuation lines start further left.
        if left < prev.bbox.left && prev.bbox.left - left <= MAX_FIRST_INDENT * size {
            return true;
        }
        // Hanging indent (list items, footnotes): continuation aligned with the
        // second word of the first line (LibreOffice footnote `1 Notas…`, text at 86.3).
        let second = prev.words.get(1).map(|w| w.bbox.left);
        if second.is_some_and(|x| aligned(left, x) && x - prev.bbox.left <= MAX_FIRST_INDENT * size)
        {
            return true;
        }
    }
    false
}

/// Whether the line's first word looks like a list marker: a bullet glyph or an
/// enumerator (`1.`, `2)`, `a)`, `(iv)`). Glyphs seen in the corpus: `• – ∗` (LaTeX),
/// `• ‣ –` (Typst), `•` (LibreOffice, OpenSymbol) — docs/achados/001, finding 5.
/// The marker must be followed by more text on the same line.
pub fn starts_with_marker(line: &Line) -> bool {
    line.words.len() >= 2 && line.words.first().is_some_and(|w| is_marker(&w.text))
}

pub fn is_marker(t: &str) -> bool {
    const BULLETS: &[&str] = &[
        "•", "◦", "▪", "▫", "‣", "⁃", "–", "—", "-", "∗", "*", "·", "■", "□", "●", "○", "►", "▸",
        "➢", "✓",
        // Symbol-font bullet mapped to the Private Use Area (Word/Wingdings exports).
        "\u{F0B7}",
    ];
    if BULLETS.contains(&t) {
        return true;
    }
    let (body, close) = match t.char_indices().last() {
        Some((i, c @ ('.' | ')'))) => (&t[..i], c),
        _ => return false,
    };
    let body = if close == ')' {
        body.strip_prefix('(').unwrap_or(body)
    } else {
        body
    };
    let n = body.chars().count();
    if n == 0 {
        return false;
    }
    let digits = n <= 3 && body.chars().all(|c| c.is_ascii_digit());
    let letter = n == 1 && body.chars().all(|c| c.is_ascii_alphabetic());
    let roman = n <= 5 && body.chars().all(|c| "ivxlc".contains(c));
    digits || letter || roman
}

fn make_block(lines: Vec<Line>) -> Block {
    let size = dominant_size(
        lines
            .iter()
            .flat_map(|l| l.words.iter().map(|w| (w.size, w.len))),
    );
    let style = majority_style(
        lines
            .iter()
            .flat_map(|l| l.words.iter().map(|w| (w.style, w.len))),
    );
    let bbox = union_all(lines.iter().map(|l| l.bbox));
    Block {
        lines,
        bbox,
        size,
        style,
        region: 0,
    }
}

// ---------------------------------------------------------------- pipeline

/// The blocks of [`layout_from_chars`] (for tests).
#[cfg(test)]
pub fn blocks_from_chars(chars: &[Char], path_marks: &[Rect]) -> Vec<Block> {
    layout_from_chars(chars, path_marks).1
}

/// Full layout grouping for one page taken alone (for tests): no furniture removal.
#[cfg(test)]
pub fn layout_from_chars(chars: &[Char], path_marks: &[Rect]) -> (Vec<Region>, Vec<Block>) {
    layout_from_words(words(chars), path_marks, &[])
}

/// Layout grouping of one page's (body) words: regions (column detection,
/// [`columns::split`]) → lines → blocks. Words are split into regions before lines
/// are formed, so no line or block crosses a gutter. `path_marks` are bounding boxes
/// of small vector paths that may be list bullets (see [`attach_path_markers`]);
/// `rules` are thin horizontal vector lines (table rules, achado 012).
/// Returns the regions and the blocks, both in reading order; each block's `region`
/// indexes the first vector.
pub fn layout_from_words(
    ws: Vec<Word>,
    path_marks: &[Rect],
    rules: &[Rect],
) -> (Vec<Region>, Vec<Block>) {
    let mut regions = Vec::new();
    let mut out = Vec::new();
    for (i, (region, ws)) in columns::split(ws, rules).into_iter().enumerate() {
        let mut ls = lines_in(ws, Some((region.rect.left, region.rect.right)));
        // A vector bullet only attaches to a line just right of it, so it cannot be
        // claimed by a line of another column.
        attach_path_markers(&mut ls, path_marks);
        out.extend(blocks(ls).into_iter().map(|mut b| {
            b.region = i;
            b
        }));
        regions.push(region);
    }
    (regions, out)
}

/// What extraction produces for one page.
#[derive(Clone, Debug, Default)]
pub struct PagePrimitives {
    pub width: f32,
    pub height: f32,
    pub chars: Vec<Char>,
    pub path_marks: Vec<Rect>,
    /// Thin horizontal vector lines ([`super::extract::page_rules`]).
    pub rules: Vec<Rect>,
}

/// Layout of a whole document: characters → words per page; page furniture
/// (running headers, footers, page numbers) is detected across pages
/// ([`furniture::detect`]) and taken out **before** column detection, so it cannot
/// shape the columns (finding 005, finding 7; finding 008); the remaining words go
/// through [`layout_from_words`]. Furniture is kept in [`Page::furniture`] as blocks
/// for inspection. Page numbers are the 1-based positions in `pages`.
pub fn layout_document(pages: Vec<PagePrimitives>) -> Vec<Page> {
    let (page_words, page_hints): (Vec<Vec<Word>>, Vec<Vec<furniture::Hint>>) =
        pages.iter().map(|p| words_with_hints(&p.chars)).unzip();
    let inputs: Vec<furniture::PageWords> = pages
        .iter()
        .zip(page_words.iter().zip(&page_hints))
        .enumerate()
        .map(|(i, (p, (ws, hs)))| furniture::PageWords {
            number: i + 1,
            width: p.width,
            words: ws,
            hints: hs,
        })
        .collect();
    let flags = furniture::detect(&inputs);
    pages
        .into_iter()
        .zip(page_words)
        .zip(flags)
        .enumerate()
        .map(|(i, ((p, ws), fl))| {
            let mut body = Vec::new();
            // Furniture words grouped by reason, so each block carries one reason.
            let mut furn: Vec<(furniture::Reason, Vec<Word>)> = Vec::new();
            for (w, r) in ws.into_iter().zip(fl) {
                match r {
                    None => body.push(w),
                    Some(r) => match furn.iter_mut().find(|(k, _)| *k == r) {
                        Some((_, v)) => v.push(w),
                        None => furn.push((r, vec![w])),
                    },
                }
            }
            furn.sort_by_key(|(r, _)| *r);
            let (regions, blocks_) = layout_from_words(body, &p.path_marks, &p.rules);
            let mut furniture: Vec<furniture::Furniture> = furn
                .into_iter()
                .flat_map(|(reason, ws)| {
                    blocks(lines_in(ws, None))
                        .into_iter()
                        .map(move |block| furniture::Furniture { block, reason })
                })
                .collect();
            furniture.sort_by(|a, b| {
                cmp_f32(a.block.bbox.top, b.block.bbox.top)
                    .then(cmp_f32(a.block.bbox.left, b.block.bbox.left))
            });
            Page {
                number: i + 1,
                width: p.width,
                height: p.height,
                regions,
                blocks: blocks_,
                furniture,
                chars: p.chars,
            }
        })
        .collect()
}

// ---------------------------------------------------------------- helpers

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

fn union_all(mut it: impl Iterator<Item = Rect>) -> Rect {
    let first = it.next().unwrap_or(Rect::new(0.0, 0.0, 0.0, 0.0));
    it.fold(first, |acc, r| acc.union(&r))
}

/// The size carrying the most characters (sizes bucketed to 0.1 pt; ties → larger).
fn dominant_size(it: impl Iterator<Item = (f32, usize)>) -> f32 {
    let mut buckets: Vec<(i64, usize)> = Vec::new();
    for (s, n) in it {
        let k = (s * 10.0).round() as i64;
        match buckets.iter_mut().find(|(b, _)| *b == k) {
            Some((_, c)) => *c += n,
            None => buckets.push((k, n)),
        }
    }
    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)
}

/// Each flag is set when more than half of the characters have it. Per-flag majority
/// rather than the most common combination: a LaTeX line with bold, italic and
/// bold-italic spans has 33 regular chars against 38 bold ones split over two
/// combinations.
fn majority_style(it: impl Iterator<Item = (Style, usize)>) -> Style {
    let (mut total, mut b, mut i, mut m) = (0, 0, 0, 0);
    for (s, n) in it {
        total += n;
        b += if s.bold { n } else { 0 };
        i += if s.italic { n } else { 0 };
        m += if s.mono { n } else { 0 };
    }
    Style {
        bold: 2 * b > total,
        italic: 2 * i > total,
        mono: 2 * m > total,
    }
}

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

    const REGULAR: Style = Style {
        bold: false,
        italic: false,
        mono: false,
    };
    const BOLD: Style = Style {
        bold: true,
        italic: false,
        mono: false,
    };
    const MONO: Style = Style {
        bold: false,
        italic: false,
        mono: true,
    };

    /// Synthetic text run: every glyph advances 0.5 em; a space is a PDFium-generated
    /// zero-width character followed by a 0.25 em gap (as in the LaTeX output).
    fn run(text: &str, x: f32, base: f32, size: f32, style: Style) -> Vec<Char> {
        let font = match (style.bold, style.mono) {
            (_, true) => "Mono",
            (true, _) => "Serif-Bold",
            _ => "Serif",
        };
        let mut out = Vec::new();
        let mut x = x;
        for ch in text.chars() {
            if ch == ' ' {
                out.push(Char {
                    ch,
                    bbox: Rect::new(x, base, x, base),
                    baseline: base,
                    size,
                    font: font.into(),
                    style,
                    generated: true,
                    kind: CharKind::Text,
                    source: Default::default(),
                });
                x += 0.25 * size;
                continue;
            }
            let w = 0.5 * size;
            out.push(Char {
                ch,
                bbox: Rect::new(x, base - 0.9 * size, x + w, base + 0.25 * size),
                baseline: base,
                size,
                font: font.into(),
                style,
                generated: false,
                kind: CharKind::Text,
                source: Default::default(),
            });
            x += w;
        }
        out
    }

    fn texts(blocks: &[Block]) -> Vec<String> {
        blocks
            .iter()
            .map(|b| {
                let ls: Vec<String> = b.lines.iter().map(Line::text).collect();
                ls.join(" / ")
            })
            .collect()
    }

    fn group(chars: &[Char]) -> Vec<String> {
        texts(&blocks_from_chars(chars, &[]))
    }

    #[test]
    fn spaces_and_gaps_split_words() {
        let mut c = run("ab cd", 0.0, 100.0, 10.0, REGULAR);
        // No space character, but a 0.3 em gap after "cd" (ends at 22.5): new word.
        c.extend(run("ef", 25.5, 100.0, 10.0, REGULAR));
        let w: Vec<String> = words(&c).into_iter().map(|w| w.text).collect();
        assert_eq!(w, ["ab", "cd", "ef"]);
    }

    #[test]
    fn split_text_objects_without_gap_are_one_word() {
        // Chrome: "Intr" and "odução" are separate text objects that touch.
        let mut c = run("Intr", 90.0, 200.0, 24.0, BOLD);
        c.extend(run("odução", 90.0 + 4.0 * 12.0 - 0.4, 200.0, 24.0, BOLD));
        let w = words(&c);
        assert_eq!(w.len(), 1);
        assert_eq!(w[0].text, "Introdução");
    }

    #[test]
    fn decomposed_ligature_sharing_one_box_stays_in_the_word() {
        // LaTeX "fi": PDFium gives `f` and `i` the same (ligature) box.
        let mut c = run("e", 0.0, 100.0, 10.0, REGULAR);
        let lig = Rect::new(5.0, 91.0, 10.7, 102.5);
        for ch in ['f', 'i'] {
            let mut x = c[0].clone();
            x.ch = ch;
            x.bbox = lig;
            c.push(x);
        }
        c.extend(run("ca", 10.7, 100.0, 10.0, REGULAR));
        let w = words(&c);
        assert_eq!(w.len(), 1);
        assert_eq!(w[0].text, "efica");
    }

    #[test]
    fn jump_back_starts_a_new_word() {
        let mut c = run("abc", 50.0, 100.0, 10.0, REGULAR);
        c.extend(run("de", 0.0, 100.0, 10.0, REGULAR));
        assert_eq!(words(&c).len(), 2);
    }

    #[test]
    fn style_change_without_space_is_glued() {
        let mut c = run("negrito", 0.0, 100.0, 10.0, BOLD);
        c.extend(run(", fim", 35.0, 100.0, 10.0, REGULAR));
        let ls = lines(words(&c));
        assert_eq!(ls.len(), 1);
        assert_eq!(ls[0].text(), "negrito, fim");
        assert!(ls[0].words[1].glued);
    }

    #[test]
    fn superscript_stays_on_its_line() {
        // LaTeX footnote mark: 7 pt, 3.5 pt above a 10 pt baseline.
        let mut c = run("frase.", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("1", 30.5, 96.5, 7.0, REGULAR));
        c.extend(run("Linha seguinte", 0.0, 112.0, 10.0, REGULAR));
        let ls = lines(words(&c));
        assert_eq!(ls.len(), 2);
        assert_eq!(ls[0].text(), "frase. 1");
        assert_eq!(ls[0].baseline, 100.0);
        assert_eq!(ls[0].size, 10.0);
    }

    #[test]
    fn wide_gap_splits_a_row_into_cells() {
        let mut c = run("LaTeX", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("LuaTeX", 60.0, 100.0, 10.0, REGULAR));
        let ls = lines(words(&c));
        let t: Vec<String> = ls.iter().map(Line::text).collect();
        assert_eq!(t, ["LaTeX", "LuaTeX"]);
    }

    #[test]
    fn lone_leading_number_keeps_its_text() {
        // LibreOffice footnote: "1", 0.91 em, then the note text.
        let mut c = run("1", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("Notas", 14.1, 100.0, 10.0, REGULAR));
        assert_eq!(lines(words(&c)).len(), 1);
        // But a number that starts a later cell is split from the cell before it.
        let mut c = run("LuaTeX", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("4", 50.0, 100.0, 10.0, REGULAR));
        c.extend(run("Tipografia", 65.0, 100.0, 10.0, REGULAR));
        assert_eq!(lines(words(&c)).len(), 3);
    }

    #[test]
    fn monospace_runs_of_spaces_do_not_split() {
        let mut c = run("let", 0.0, 100.0, 10.0, MONO);
        // Two spaces of 0.6 em each, like aligned code (1.2 em gap).
        c.extend(run("=", 27.0, 100.0, 10.0, MONO));
        assert_eq!(lines(words(&c)).len(), 1);
        // The same gap between proportional words is a cell boundary.
        let mut c = run("let", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("=", 27.0, 100.0, 10.0, REGULAR));
        assert_eq!(lines(words(&c)).len(), 2);
    }

    #[test]
    fn paragraph_lines_form_one_block_and_a_gap_separates_paragraphs() {
        let mut c = Vec::new();
        c.extend(run("primeira linha", 0.0, 100.0, 10.0, REGULAR));
        c.extend(run("segunda linha", 0.0, 112.0, 10.0, REGULAR));
        c.extend(run("fim", 0.0, 124.0, 10.0, REGULAR));
        // 1.8 em: new paragraph.
        c.extend(run("outro", 0.0, 142.0, 10.0, REGULAR));
        assert_eq!(group(&c), ["primeira linha / segunda linha / fim", "outro"]);
    }

    #[test]
    fn heading_is_its_own_block_even_with_tight_spacing() {
        let mut c = run("Título", 0.0, 100.0, 14.0, BOLD);
        c.extend(run("corpo do texto", 0.0, 114.0, 10.0, REGULAR));
        assert_eq!(group(&c), ["Título", "corpo do texto"]);
        // Same size, bold: still separate.
        let mut c = run("Subtítulo", 0.0, 100.0, 10.0, BOLD);
        c.extend(run("corpo do texto", 0.0, 112.0, 10.0, REGULAR));
        assert_eq!(group(&c), ["Subtítulo", "corpo do texto"]);
    }

    #[test]
    fn list_items_are_separate_blocks_with_hanging_continuation() {
        let mut c = Vec::new();
        c.extend(run("• primeiro", 10.0, 100.0, 10.0, REGULAR));
        c.extend(run("• segundo item", 10.0, 112.0, 10.0, REGULAR));
        // Continuation aligned with the text after the marker (x = 10 + 5 + 2.5).
        c.extend(run("continua", 17.5, 124.0, 10.0, REGULAR));
        c.extend(run("1. terceiro", 10.0, 136.0, 10.0, REGULAR));
        assert_eq!(
            group(&c),
            ["• primeiro", "• segundo item / continua", "1. terceiro"]
        );
    }

    #[test]
    fn first_line_indent_and_code_indentation() {
        let mut c = run("recuado", 15.0, 100.0, 10.0, REGULAR);
        c.extend(run("continua", 0.0, 112.0, 10.0, REGULAR));
        assert_eq!(group(&c), ["recuado / continua"]);

        let mut c = run("fn main() {", 0.0, 100.0, 10.0, MONO);
        c.extend(run("let x = 1;", 20.0, 112.0, 10.0, MONO));
        c.extend(run("}", 0.0, 124.0, 10.0, MONO));
        assert_eq!(group(&c), ["fn main() { / let x = 1; / }"]);
    }

    #[test]
    fn different_alignment_breaks_the_block() {
        let mut c = run("parágrafo um", 0.0, 100.0, 10.0, REGULAR);
        c.extend(run("citação recuada", 40.0, 112.0, 10.0, REGULAR));
        c.extend(run("continua", 40.0, 124.0, 10.0, REGULAR));
        assert_eq!(group(&c), ["parágrafo um", "citação recuada / continua"]);
    }

    #[test]
    fn vector_bullet_becomes_a_marker() {
        // Chrome: list bullets are 3.8 pt filled paths, not glyphs.
        let mut c = run("primeiro", 20.0, 100.0, 12.0, REGULAR);
        c.extend(run("segundo", 20.0, 113.5, 12.0, REGULAR));
        let marks = [
            Rect::new(8.0, 94.0, 11.8, 97.8),
            Rect::new(8.0, 107.5, 11.8, 111.3),
        ];
        let b = blocks_from_chars(&c, &marks);
        assert_eq!(texts(&b), ["• primeiro", "• segundo"]);
        // A hairline (table rule) is not a bullet.
        let b = blocks_from_chars(&c, &[Rect::new(8.0, 96.0, 18.0, 96.8)]);
        assert_eq!(texts(&b), ["primeiro / segundo"]);
    }

    #[test]
    fn markers() {
        for m in [
            "•", "–", "∗", "‣", "1.", "12)", "a)", "(iv)", "iii.", "\u{F0B7}",
        ] {
            assert!(is_marker(m), "{m}");
        }
        for m in ["1", "abc.", "1234.", "texto", ")", "."] {
            assert!(!is_marker(m), "{m}");
        }
    }

    #[test]
    fn dominant_size_and_majority_style() {
        assert_eq!(
            dominant_size([(10.0, 50), (7.0, 1), (14.0, 3)].into_iter()),
            10.0
        );
        let bold_italic = Style {
            italic: true,
            ..BOLD
        };
        // The LaTeX line with bold, italic and bold-italic spans (finding 004).
        let s = majority_style([(REGULAR, 33), (BOLD, 16), (bold_italic, 22)].into_iter());
        assert!(s.bold && !s.italic);
    }

    #[test]
    fn loose_justified_line_in_a_column_is_not_split() {
        // Chrome justifies without hyphenating: "hifenização é um recurso de" with
        // equal gaps of 1.0 em in a 16 em column, between two normal lines.
        // Words end at 155 (0.5 em per glyph); the column is [0, 155].
        let mut c = run("linha anterior", 0.0, 100.0, 10.0, REGULAR);
        for (i, w) in ["hifenização", "é", "um", "recurso", "de"]
            .iter()
            .enumerate()
        {
            let x = [0.0, 65.0, 80.0, 100.0, 145.0][i];
            c.extend(run(w, x, 112.0, 10.0, REGULAR));
        }
        c.extend(run("linha seguinte", 0.0, 124.0, 10.0, REGULAR));
        let ws = words(&c);
        let ls = lines_in(ws.clone(), Some((0.0, 155.0)));
        assert_eq!(
            ls.len(),
            3,
            "{:?}",
            ls.iter().map(Line::text).collect::<Vec<_>>()
        );
        assert_eq!(ls[1].text(), "hifenização é um recurso de");
        // Without the column extent the old behaviour stays: split at > 0.9 em.
        assert_eq!(lines(ws).len(), 7);
    }

    #[test]
    fn running_header_spanning_the_column_is_still_split() {
        // LaTeX: `TABELAS` left and the page number right, 40 em apart, isolated.
        let mut c = run("TABELAS", 0.0, 20.0, 10.0, REGULAR);
        c.extend(run("2", 395.0, 20.0, 10.0, REGULAR));
        c.extend(run("corpo do texto", 0.0, 60.0, 10.0, REGULAR));
        let ls = lines_in(words(&c), Some((0.0, 400.0)));
        assert_eq!(ls.len(), 3);
    }

    #[test]
    fn table_row_with_uneven_gaps_is_still_split() {
        // Cells `LaTeX LuaTeX` | `4` | `Tipografia clássica`, spanning the column,
        // between other rows: gaps of 0.25 em inside cells, ≥ 1 em between them.
        let mut c = Vec::new();
        for base in [100.0, 112.0, 124.0] {
            c.extend(run("LaTeX LuaTeX", 0.0, base, 10.0, REGULAR));
            c.extend(run("4", 80.0, base, 10.0, REGULAR));
            c.extend(run("Tipografia clássica", 100.0, base, 10.0, REGULAR));
        }
        let ls = lines_in(words(&c), Some((0.0, 197.5)));
        assert_eq!(ls.len(), 9);
    }

    #[test]
    fn two_columns_from_chars_never_share_a_line_or_block() {
        // Two 15 em columns (the left run is 152.5 pt wide), 0.8 em gutter (LaTeX
        // A5), 8 rows on shared baselines: every line stops at the gutter, and
        // column 1 is read before column 2.
        let left = "alfa beta gama delta épsilon zeta";
        let right = "um dois três quatro cinco seis";
        let mut c = Vec::new();
        for r in 0..8 {
            let base = 100.0 + r as f32 * 12.0;
            c.extend(run(left, 0.0, base, 10.0, REGULAR));
            c.extend(run(right, 160.5, base, 10.0, REGULAR));
        }
        let (regions, bs) = layout_from_chars(&c, &[]);
        assert_eq!(regions.len(), 2);
        assert_eq!(bs.len(), 2);
        assert_eq!((bs[0].region, bs[1].region), (0, 1));
        assert!(bs[0].bbox.right <= 152.5 && bs[1].bbox.left >= 160.5);
        assert!(bs[0].lines.iter().all(|l| l.text() == left));
    }

    #[test]
    fn running_head_is_removed_before_the_column_split() {
        // LaTeX pages 2-3 of two-columns (finding 005, finding 7): a running title
        // over column 1 and the page number over column 2, 3.5 em above the text.
        // Without stage 5 they would open the two column regions.
        let left = "alfa beta gama delta épsilon zeta";
        let right = "um dois três quatro cinco seis";
        let pages: Vec<PagePrimitives> = ["PALAVRAS COMPOSTAS", "CONCLUSÃO"]
            .iter()
            .enumerate()
            .map(|(i, head)| {
                let mut c = run(head, 0.0, 65.0, 10.0, REGULAR);
                c.extend(run(&format!("{}", i + 2), 300.0, 65.0, 10.0, REGULAR));
                for r in 0..8 {
                    let base = 100.0 + r as f32 * 12.0;
                    c.extend(run(left, 0.0, base, 10.0, REGULAR));
                    c.extend(run(right, 160.5, base, 10.0, REGULAR));
                }
                PagePrimitives {
                    width: 320.0,
                    height: 400.0,
                    chars: c,
                    ..Default::default()
                }
            })
            .collect();
        for p in layout_document(pages) {
            assert_eq!(p.regions.len(), 2);
            assert_eq!(p.blocks.len(), 2);
            assert!(
                p.blocks
                    .iter()
                    .all(|b| b.lines[0].text() != "PALAVRAS COMPOSTAS")
            );
            assert!(p.regions.iter().all(|r| r.rect.top > 90.0));
            let f: Vec<(String, furniture::Reason)> = p
                .furniture
                .iter()
                .map(|f| (f.block.lines[0].text(), f.reason))
                .collect();
            assert_eq!(f.len(), 2, "{f:?}");
            assert_eq!(f[1].1, furniture::Reason::Repeated);
            assert_eq!(f[0].1, furniture::Reason::SharedRow);
        }
    }

    #[test]
    fn garbage_input_does_not_panic() {
        let mut c = run("ok", 0.0, 100.0, 10.0, REGULAR);
        let mut bad = c[0].clone();
        bad.size = 0.0;
        c.push(bad);
        let mut junk = c[0].clone();
        junk.ch = '\u{FFFE}';
        c.push(junk);
        let _ = blocks_from_chars(&c, &[Rect::new(f32::NAN, 0.0, 1.0, 1.0)]);
        assert!(blocks_from_chars(&[], &[]).is_empty());
    }
}