kakemono 0.11.0

Convert scientific-paper PDFs (arXiv) into clean, readable HTML in four fidelity modes, Word documents, Markdown, LaTeX or EPUB books
Documentation
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
//! Building the text of blocks: styled spans, de-hyphenation, equation runs and table cells.
//!
//! [`TextBuilder`] turns the glyph lines of a block into the styled
//! [`Span`]s of the output model. Line-end hyphens are removed when the
//! document's own vocabulary (see [`build_vocab`]) says they are soft.

use crate::analysis::tables::Grid;
use crate::backend::FontInfo;
use crate::model::Line;
use crate::model::*;
use std::collections::{HashMap, HashSet};
use std::ops::Range;

/// Most characters of an anchor slug; longer headings are cut, which keeps
/// the URL fragments readable.
const MAX_SLUG_CHARS: usize = 48;

/// Smallest width (points) given to an equation run, so that zero-width
/// glyphs still produce a positioned box.
const MIN_RUN_WIDTH_PT: f32 = 0.1;

/// Vertical bars of formulas (absolute value, norm, "such that"). TeX builds
/// the tall ones from pieces of an extension font; each piece is drawn on its
/// own, fitted to the box its ink has in the PDF, because a bar of a text
/// font is as tall as the font says, whatever the piece it stands for.
const BAR_GLYPHS: [&str; 4] = ["|", "\u{2223}", "\u{2225}", "\u{2016}"];

/// Tuning parameters of text building. Part of [`SemanticsConfig`](super::SemanticsConfig).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextConfig {
    /// At a line-end hyphen whose halves are both words of the document,
    /// the hyphen is kept when the left half has at least this many
    /// characters ("multi-" + "head"); shorter left halves are usually
    /// prefixes broken off a single word.
    pub compound_part_min_chars_count: usize,
    /// Two lines of a table cell stand one under the other (a cell wrapped
    /// over several lines) when the second baseline is at least this far
    /// below the first (multiple of the font size); pieces side by side on
    /// one row are closer.
    pub cell_wrap_min_dy_em: f32,
    /// Height of the math axis above the baseline (multiple of the font
    /// size); glyphs centred far from it are big operators or delimiters.
    pub math_axis_height_em: f32,
    /// A formula glyph whose ink is taller than this (multiple of the font
    /// size) is drawn on its own (big operators, tall delimiters).
    pub tall_glyph_min_height_em: f32,
    /// A formula glyph whose ink centre is further than this from the math
    /// axis (multiple of the font size) is drawn on its own.
    pub off_axis_min_offset_em: f32,
    /// Glyphs whose sizes differ by less than this (points) may share an
    /// equation run.
    pub run_size_tolerance_pt: f32,
    /// Glyphs whose baselines differ by less than this (points) may share
    /// an equation run.
    pub run_baseline_tolerance_pt: f32,
    /// A glyph starting less than this (multiple of its font size) after
    /// the end of the current run joins it.
    pub run_max_gap_em: f32,
    /// Inside and around an inline fraction, a gap wider than this many
    /// font sizes is a word space.
    pub fraction_space_min_em: f32,
    /// A glyph in a term of an inline fraction at most this fraction of the
    /// size of the glyph before it ...
    pub term_script_max_size_ratio: f32,
    /// ... and set more than this many of that glyph's font sizes above or
    /// below it is its superscript or subscript.
    pub term_script_min_offset_em: f32,
}

impl Default for TextConfig {
    fn default() -> Self {
        Self {
            compound_part_min_chars_count: 4,
            fraction_space_min_em: 0.2,
            term_script_max_size_ratio: 0.85,
            term_script_min_offset_em: 0.05,
            cell_wrap_min_dy_em: 0.5,
            math_axis_height_em: 0.25,
            tall_glyph_min_height_em: 1.3,
            off_axis_min_offset_em: 0.6,
            run_size_tolerance_pt: 0.1,
            run_baseline_tolerance_pt: 0.2,
            run_max_gap_em: 0.6,
        }
    }
}

/// Converts lines of glyphs into styled spans.
pub(crate) struct TextBuilder<'a> {
    /// Font table, for the style of each glyph.
    pub(crate) fonts: &'a [FontInfo],
    /// Words of the document (see [`build_vocab`]), for de-hyphenation.
    pub(crate) vocab: &'a HashSet<String>,
    /// Thresholds of text building.
    pub(crate) cfg: &'a TextConfig,
}

/// The text of a block, built by [`TextBuilder::build`].
pub(crate) struct Built {
    /// The running text of the block.
    pub(crate) spans: Vec<Span>,
    /// Plain text of each line, as it appears in the running text.
    pub(crate) line_texts: Vec<String>,
    /// Styled spans of each line, for the position-preserving renderers.
    pub(crate) hlines: Vec<HLine>,
}

/// An equation run that may still grow.
struct OpenRun {
    /// The run so far.
    run: EqRun,
    /// Font of its glyphs.
    font: u16,
    /// Right edge of its last glyph.
    end: f32,
}

/// The reading order of a line's glyphs: left to right, except that a
/// superscript and a subscript set one above the other ("410^{+160}_{-180}")
/// are read one after the other, not interleaved digit by digit. The second
/// element holds the glyph ranges of the stacked pairs that are inline
/// fractions, read "1/2".
fn stacked_script_order(glyphs: &[LineGlyph], cfg: &TextConfig) -> (Vec<usize>, Vec<Range<usize>>) {
    let mut order: Vec<usize> = Vec::with_capacity(glyphs.len());
    let mut fractions: Vec<Range<usize>> = Vec::new();
    let mut i = 0;
    while i < glyphs.len() {
        if glyphs[i].script == 0 {
            order.push(i);
            i += 1;
            continue;
        }
        // A run of script glyphs: superscripts first when both kinds overlap.
        let start = i;
        while i < glyphs.len() && glyphs[i].script != 0 {
            i += 1;
        }
        let run = start..i;
        let span = |sign: i8| {
            run.clone()
                .filter(|&k| glyphs[k].script.signum() == sign)
                .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), k| {
                    (lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
                })
        };
        let (up, down) = (span(1), span(-1));
        let stacked = up.0 < down.1 && down.0 < up.1;
        // Terms stacked on a fraction bar (see `mark_fractions`): the other
        // scripts of the run left of the fraction are read before it (the
        // T→∞ under "lim" before R(T)/T), the rest after it.
        let (left, right) = run
            .clone()
            .filter(|&k| glyphs[k].is_fraction_term())
            .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), k| {
                (lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
            });
        if left <= right {
            let before = |k: &usize| (glyphs[*k].x0 + glyphs[*k].x1) / 2.0 < left;
            let others: Vec<usize> = run.clone().filter(|&k| !glyphs[k].is_fraction_term()).collect();
            let (ahead, behind): (Vec<usize>, Vec<usize>) = others.into_iter().partition(before);
            push_stacked(glyphs, &ahead, &mut order);
            for sign in [1, -1] {
                let term: Vec<usize> = run
                    .clone()
                    .filter(|&k| glyphs[k].is_fraction_term() && glyphs[k].script.signum() == sign)
                    .collect();
                term_order(glyphs, &term, cfg, &mut order);
            }
            push_stacked(glyphs, &behind, &mut order);
            fractions.push(run);
        } else if stacked {
            order.extend(run.clone().filter(|&k| glyphs[k].script > 0));
            order.extend(run.filter(|&k| glyphs[k].script < 0));
        } else {
            order.extend(run);
        }
    }
    (order, fractions)
}

/// Appends the glyphs of a fraction's `term` (indexes, left to right) to
/// `order`: each glyph on the term's baseline, then its scripts in the term
/// (smaller glyphs set off that baseline, see [`term_scripts`]), the
/// superscripts first when they stand over the subscripts (g⁴ over T,i).
fn term_order(glyphs: &[LineGlyph], term: &[usize], cfg: &TextConfig, order: &mut Vec<usize>) {
    let mut k = 0;
    while k < term.len() {
        let base = &glyphs[term[k]];
        order.push(term[k]);
        k += 1;
        // A radical sign is drawn larger than what follows it, which is
        // its radicand, not its scripts.
        if base.text == "\u{221A}" {
            continue;
        }
        let start = k;
        while k < term.len() && glyphs[term[k]].size <= cfg.term_script_max_size_ratio * base.size {
            k += 1;
        }
        let scripts = &term[start..k];
        let offset = cfg.term_script_min_offset_em * base.size;
        let (ups, downs): (Vec<usize>, Vec<usize>) = scripts.iter().partition(|&&i| glyphs[i].y < base.y - offset);
        let extent = |part: &[usize]| {
            part.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &i| {
                (lo.min(glyphs[i].x0), hi.max(glyphs[i].x1))
            })
        };
        let (up, down) = (extent(&ups), extent(&downs));
        if up.0 < down.1 && down.0 < up.1 {
            order.extend(ups);
            order.extend(downs);
        } else {
            order.extend(scripts);
        }
    }
}

/// Appends the script glyphs `run` (indexes, left to right) to `order`:
/// superscripts first when superscripts and subscripts overlap, as in
/// [`stacked_script_order`].
fn push_stacked(glyphs: &[LineGlyph], run: &[usize], order: &mut Vec<usize>) {
    let span = |sign: i8| {
        run.iter()
            .filter(|&&k| glyphs[k].script.signum() == sign)
            .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &k| {
                (lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
            })
    };
    let (up, down) = (span(1), span(-1));
    if up.0 < down.1 && down.0 < up.1 {
        order.extend(run.iter().filter(|&&k| glyphs[k].script > 0));
        order.extend(run.iter().filter(|&&k| glyphs[k].script < 0));
    } else {
        order.extend(run);
    }
}

/// The text set around the glyphs of inline fractions, by position in the
/// reading `order`: an opening parenthesis before a term of several parts
/// and the closing one right after it, the slash before the denominator,
/// and parentheses around the radicand of a radical that starts a term
/// (√(1−β₂ᵗ)), which then needs none of its own.
#[derive(Default)]
struct FractionMarks {
    /// Text written before the glyph at each position.
    before: HashMap<usize, String>,
    /// Text written right after the glyph at each position, in its style:
    /// a closing parenthesis belongs to the term it closes.
    after: HashMap<usize, String>,
}

/// The [`FractionMarks`] of the inline fractions of a line (the glyph
/// ranges `fractions`, read in `order`).
fn fraction_marks(
    glyphs: &[LineGlyph],
    order: &[usize],
    fractions: &[Range<usize>],
    cfg: &TextConfig,
) -> FractionMarks {
    let mut marks = FractionMarks::default();
    // A term of several parts: a gap in it, or an operator; its own
    // scripts (smaller glyphs) do not count.
    let compound = |term: &[usize]| {
        let largest = term.iter().map(|&pos| glyphs[order[pos]].size).fold(0.0, f32::max);
        let term: Vec<usize> = term
            .iter()
            .copied()
            .filter(|&pos| glyphs[order[pos]].size > cfg.term_script_max_size_ratio * largest)
            .collect();
        term.windows(2).any(|pair| {
            let (left, right) = (&glyphs[order[pair[0]]], &glyphs[order[pair[1]]]);
            right.x0 - left.x1 > cfg.fraction_space_min_em * right.size
        }) || term.iter().any(|&pos| {
            glyphs[order[pos]]
                .text
                .chars()
                .any(|ch| "+-\u{2212}\u{B1}\u{B7}\u{D7}=,".contains(ch))
        })
    };
    for run in fractions {
        let positions: Vec<usize> = (0..order.len()).filter(|&pos| run.contains(&order[pos])).collect();
        let term = |sign: i8| -> Vec<usize> {
            positions
                .iter()
                .copied()
                .filter(|&pos| {
                    let glyph = &glyphs[order[pos]];
                    glyph.is_fraction_term() && glyph.script.signum() == sign
                })
                .collect()
        };
        let (numerator, denominator) = (term(1), term(-1));
        let (Some(&den_start), false) = (denominator.first(), numerator.is_empty()) else {
            continue;
        };
        for (idx, term) in [numerator, denominator].iter().enumerate() {
            let (first, last) = (term[0], term[term.len() - 1]);
            if idx == 1 {
                marks.before.entry(den_start).or_default().push('/');
            }
            let radical = glyphs[order[first]].text == "\u{221A}" && term.len() > 1;
            if radical && compound(&term[1..]) {
                marks.before.entry(term[1]).or_default().push('(');
                marks.after.entry(last).or_default().push(')');
            } else if !radical && compound(term) {
                marks.before.entry(first).or_default().push('(');
                marks.after.entry(last).or_default().push(')');
            }
        }
    }
    marks
}

/// The scripts inside the terms of inline fractions, by glyph index: a
/// glyph of a term smaller than the glyph before it in its term (at most
/// [`TextConfig::term_script_max_size_ratio`] of it) and set higher or
/// lower (by more than [`TextConfig::term_script_min_offset_em`]) is its
/// superscript or subscript: the 1 and the 2 of β₁² over √β₂. A term of a
/// fraction in a superscript is a superscript as a whole, so its own
/// scripts are not marked.
fn term_scripts(glyphs: &[LineGlyph], order: &[usize], cfg: &TextConfig) -> HashMap<usize, u8> {
    let mut scripts = HashMap::new();
    // The last full-size glyph of each term, by its sign.
    let mut base: HashMap<i8, &LineGlyph> = HashMap::new();
    for &index in order {
        let glyph = &glyphs[index];
        if glyph.script.abs() != FRACTION_TERM {
            base.clear();
            continue;
        }
        // A radical sign is larger than its radicand: no base for it.
        if glyph.text == "\u{221A}" {
            base.remove(&glyph.script);
            continue;
        }
        let Some(&prev) = base.get(&glyph.script) else {
            base.insert(glyph.script, glyph);
            continue;
        };
        if glyph.size > cfg.term_script_max_size_ratio * prev.size {
            base.insert(glyph.script, glyph);
            continue;
        }
        let offset = cfg.term_script_min_offset_em * prev.size;
        if glyph.y < prev.y - offset {
            scripts.insert(index, SUP);
        } else if glyph.y > prev.y + offset {
            scripts.insert(index, SUB);
        }
    }
    scripts
}

/// Whether a space goes before the glyph at position `pos` of the reading
/// `order`, when it is in an inline fraction or right after one: the space
/// marks of the glyphs were set in left-to-right order, which mixes the two
/// terms, so the gaps are measured again, within each term and around the
/// fraction. `None` for the other glyphs.
fn fraction_space(
    glyphs: &[LineGlyph],
    order: &[usize],
    pos: usize,
    fractions: &[Range<usize>],
    cfg: &TextConfig,
) -> Option<bool> {
    let glyph = &glyphs[order[pos]];
    let prev = &glyphs[order[pos.checked_sub(1)?]];
    // Only the terms are the fraction: other scripts of its run (a limit
    // under "lim") are spaced as usual.
    let run_of = |index: usize| {
        fractions
            .iter()
            .find(|run| run.contains(&index) && glyphs[index].is_fraction_term())
    };
    let wide = |gap: f32| gap > cfg.fraction_space_min_em * glyph.size;
    let extent = |run: &Range<usize>| {
        run.clone()
            .filter(|&k| glyphs[k].is_fraction_term())
            .map(|k| (glyphs[k].x0, glyphs[k].x1))
            .fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (x0, x1)| {
                (lo.min(x0), hi.max(x1))
            })
    };
    match (run_of(order[pos]), run_of(order[pos - 1])) {
        // Inside one fraction: a gap within a term; none between the terms.
        (Some(run), Some(prev_run)) if run == prev_run => {
            Some(prev.script.signum() == glyph.script.signum() && wide(glyph.x0 - prev.x1))
        }
        // The fraction starts: the gap from the text before it.
        (Some(run), _) => Some(wide(extent(run).0 - prev.x1)),
        // The text after a fraction: the gap from its right edge.
        (None, Some(prev_run)) => Some(wide(glyph.x0 - extent(prev_run).1)),
        (None, None) => None,
    }
}

/// Appends `text` in `style` and `color` to `spans`.
fn push_text(spans: &mut Vec<Span>, text: &str, style: u8, color: [u8; 3]) {
    match spans.last_mut() {
        Some(span) if span.style == style && span.color == color => span.text.push_str(text),
        _ => spans.push(Span {
            text: text.to_string(),
            style,
            href: None,
            color,
        }),
    }
}

impl TextBuilder<'_> {
    /// Styled text of a single line as placed on the page: the terms of an
    /// inline fraction stay a superscript and a subscript.
    fn placed_line_spans(&self, line: &Line) -> Vec<Span> {
        if !line.glyphs.iter().any(LineGlyph::is_fraction_term) {
            return self.line_spans(line);
        }
        let mut placed = line.clone();
        for glyph in &mut placed.glyphs {
            if glyph.script.abs() == FRACTION_TERM {
                glyph.script = glyph.script.signum();
            } else if glyph.script.abs() == RAISED_FRACTION_TERM {
                // Both terms of a fraction in a superscript are raised.
                glyph.script = 1;
            }
        }
        self.line_spans(&placed)
    }

    /// Styled text of a single line, as read: inline fractions read "1/2".
    pub(crate) fn line_spans(&self, line: &Line) -> Vec<Span> {
        let mut spans: Vec<Span> = Vec::new();
        let (order, fractions) = stacked_script_order(&line.glyphs, self.cfg);
        // The terms of an inline fraction read as "1/2", "(n−1)/n".
        let marks = fraction_marks(&line.glyphs, &order, &fractions, self.cfg);
        let term_scripts = term_scripts(&line.glyphs, &order, self.cfg);
        // The closing marks after the glyph at a position of the order, in
        // the glyph's own style.
        let close_after = |spans: &mut Vec<Span>, pos: usize| {
            if let Some(close) = marks.after.get(&pos) {
                let glyph = &line.glyphs[order[pos]];
                push_text(spans, close, line.style_of(glyph, self.fonts), glyph.color);
            }
        };
        for (glyph_idx, &index) in order.iter().enumerate() {
            if glyph_idx > 0 {
                close_after(&mut spans, glyph_idx - 1);
            }
            let glyph = &line.glyphs[index];
            // Marks around fraction terms take the style of the term, not
            // of a script inside it.
            let base_style = line.style_of(glyph, self.fonts);
            let style = base_style | term_scripts.get(&index).copied().unwrap_or(0);
            let mut space = fraction_space(&line.glyphs, &order, glyph_idx, &fractions, self.cfg)
                .unwrap_or(glyph.space_before)
                && glyph_idx > 0;
            if let Some(before) = marks.before.get(&glyph_idx) {
                if space {
                    push_text(&mut spans, " ", base_style, glyph.color);
                }
                push_text(&mut spans, before, base_style, glyph.color);
                space = false;
            }
            // A space after a link stays out of it.
            let mut lead = "";
            if let Some(span) = spans.last_mut() {
                let same_link = span.href.as_deref() == glyph.link.as_deref();
                if space {
                    if same_link || span.href.is_none() {
                        span.text.push(' ');
                    } else {
                        lead = " ";
                    }
                }
                if span.style == style && span.color == glyph.color && same_link {
                    span.text.push_str(&glyph.text);
                    continue;
                }
            }
            spans.push(Span {
                text: format!("{lead}{}", glyph.text),
                style,
                href: glyph.link.as_deref().map(str::to_string),
                color: glyph.color,
            });
        }
        if let Some(last) = order.len().checked_sub(1) {
            close_after(&mut spans, last);
        }
        spans
    }

    /// Converts lines into styled spans, joining the lines into running text.
    /// `skip` glyphs are dropped from the start of the running text and
    /// `mask` style bits are cleared in it (e.g. bold inside headings). The
    /// per-line output keeps everything.
    pub(crate) fn build(&self, lines: &[Line], skip: usize, mask: u8) -> Built {
        let texts: Vec<String> = lines.iter().map(|line| line.text()).collect();
        // The running text reads inline fractions as "1/2"; the per-line
        // spans keep them stacked, as placed on the page.
        let mut read: Vec<HLine> = Vec::with_capacity(lines.len());
        let mut hlines: Vec<HLine> = Vec::with_capacity(lines.len());
        let mut line_texts: Vec<String> = Vec::with_capacity(lines.len());
        for (line_idx, line) in lines.iter().enumerate() {
            let mut line_spans = self.line_spans(line);
            let mut placed_spans = self.placed_line_spans(line);
            let soft_hyphen = match texts.get(line_idx + 1) {
                Some(next) => {
                    self.join_line_end(&mut placed_spans, &texts[line_idx], next);
                    self.join_line_end(&mut line_spans, &texts[line_idx], next)
                }
                None => false,
            };
            line_texts.push(line_spans.iter().map(|span| span.text.as_str()).collect());
            read.push(HLine {
                spans: line_spans,
                soft_hyphen,
            });
            hlines.push(HLine {
                spans: placed_spans,
                soft_hyphen,
            });
        }
        let mut spans = running_spans(&read, mask);
        if skip > 0 && !lines.is_empty() {
            let n: usize = lines[0]
                .glyphs
                .iter()
                .take(skip)
                .map(|glyph| glyph.text.chars().count())
                .sum();
            strip_chars(&mut spans, n);
        }
        Built {
            spans,
            line_texts,
            hlines,
        }
    }

    /// Prepares the spans of a line (text `text`) to be followed by the next
    /// line (text `next`): removes a soft hyphen, or adds the space between
    /// the lines (none after a slash, as in URLs, nor in Chinese or Japanese
    /// text, see [`joins_without_space`]). Returns whether a soft hyphen was
    /// removed.
    fn join_line_end(&self, spans: &mut Vec<Span>, text: &str, next: &str) -> bool {
        // A URL broken across lines goes on without a space. A hyphen at
        // the break is part of it ("py-faster-" / "rcnn"), unless TeX
        // hyphenated a word there: the joined word is used elsewhere in
        // the paper ("ope-" / "nai.com", and the paper says OpenAI).
        if url_continues(text, next) {
            if text.ends_with('-') && url_hyphen_is_soft(text, next, self.vocab) {
                if let Some(last) = spans.last_mut() {
                    last.text.pop();
                    if last.text.is_empty() {
                        spans.pop();
                    }
                }
                return true;
            }
            return false;
        }
        if text.ends_with('-') && text.chars().count() > 1 {
            if remove_hyphen(text, next, self.vocab, self.cfg) {
                if let Some(last) = spans.last_mut() {
                    last.text.pop();
                    if last.text.is_empty() {
                        spans.pop();
                    }
                }
                return true;
            }
        } else if !text.ends_with('/')
            && !text.is_empty()
            && !joins_without_space(text, next)
            && let Some(last) = spans.last_mut()
        {
            last.text.push(' ');
        }
        false
    }

    /// Positioned glyph runs of a displayed formula. Neighbouring glyphs of
    /// the same font, size, baseline and colour form one run; tall or
    /// off-axis glyphs (big operators, radicals) get a run of their own with
    /// their ink box; glyphs without a Unicode value are left out (they stay
    /// part of the page picture).
    pub(crate) fn eq_runs(&self, lines: &[Line]) -> Vec<EqRun> {
        let mut runs: Vec<EqRun> = Vec::new();
        for line in lines {
            let mut current: Option<OpenRun> = None;
            for glyph in &line.glyphs {
                // No Unicode value: the glyph stays part of the page picture.
                if glyph.text.contains('\u{FFFD}') {
                    close_run(&mut current, &mut runs);
                    continue;
                }
                let style = line.style_of(glyph, self.fonts) & !(SUP | SUB);
                if self.stands_alone(glyph) {
                    close_run(&mut current, &mut runs);
                    runs.push(EqRun {
                        text: glyph.text.clone(),
                        x: glyph.ox,
                        y: glyph.oy,
                        width: (glyph.x1 - glyph.x0).max(MIN_RUN_WIDTH_PT),
                        size: glyph.size,
                        style,
                        color: glyph.color,
                        ink: Some(glyph.ink),
                    });
                    continue;
                }
                match current.as_mut().filter(|open| self.extends_run(open, glyph)) {
                    Some(open) => {
                        if glyph.space_before {
                            open.run.text.push(' ');
                        }
                        open.run.text.push_str(&glyph.text);
                        open.end = glyph.x1;
                        open.run.width = glyph.x1 - open.run.x;
                    }
                    None => {
                        close_run(&mut current, &mut runs);
                        current = Some(OpenRun {
                            run: EqRun {
                                text: glyph.text.clone(),
                                x: glyph.x0,
                                y: glyph.oy,
                                width: (glyph.x1 - glyph.x0).max(MIN_RUN_WIDTH_PT),
                                size: glyph.size,
                                style,
                                color: glyph.color,
                                ink: None,
                            },
                            font: glyph.font,
                            end: glyph.x1,
                        });
                    }
                }
            }
            close_run(&mut current, &mut runs);
        }
        runs
    }

    /// Whether a formula glyph is drawn on its own: much taller than the
    /// font size, centred far from the math axis, a radical sign or a
    /// vertical bar ([`BAR_GLYPHS`]).
    fn stands_alone(&self, glyph: &LineGlyph) -> bool {
        let axis = glyph.oy - self.cfg.math_axis_height_em * glyph.size;
        glyph.ink.height() > self.cfg.tall_glyph_min_height_em * glyph.size
            || (glyph.ink.cy() - axis).abs() > self.cfg.off_axis_min_offset_em * glyph.size
            || glyph.text == "\u{221A}"
            || BAR_GLYPHS.contains(&glyph.text.as_str())
    }

    /// Whether `glyph` continues the open run: same font, size, baseline and
    /// colour, close after its end and not left of its start.
    fn extends_run(&self, open: &OpenRun, glyph: &LineGlyph) -> bool {
        open.font == glyph.font
            && (open.run.size - glyph.size).abs() < self.cfg.run_size_tolerance_pt
            && (open.run.y - glyph.oy).abs() < self.cfg.run_baseline_tolerance_pt
            && open.run.color == glyph.color
            && glyph.x0 - open.end < self.cfg.run_max_gap_em * glyph.size
            && glyph.x0 >= open.run.x
    }

    /// Converts a table grid into the output table, with the styled text of
    /// every cell (the lines of a cell joined by spaces).
    pub(crate) fn table(&self, grid: Grid) -> Table {
        let rows = grid
            .rows
            .iter()
            .map(|row| {
                row.iter()
                    .map(|cell| TableCell {
                        col: cell.col,
                        colspan: cell.colspan,
                        rowspan: cell.rowspan,
                        spans: self.cell_spans(&cell.lines),
                    })
                    .collect()
            })
            .collect();
        Table {
            n_cols: grid.n_cols,
            header_rows: grid.header_rows,
            col_align: grid
                .col_align
                .iter()
                .map(|align| match align {
                    Align::Left => "left",
                    Align::Center => "center",
                    Align::Right => "right",
                })
                .collect(),
            rows,
            rule_above: grid.rule_above,
            rule_bottom: grid.rule_bottom,
            rule_left: grid.rule_left,
            rule_right: grid.rule_right,
            geom: TableGeom {
                bbox: grid.bbox,
                col_bounds: grid.col_bounds,
                col_text: grid.col_text,
                row_bounds: grid.row_bounds,
                row_baselines: grid.row_baselines,
                size: grid.size,
            },
        }
    }

    /// Styled text of a table cell: its lines joined by single spaces.
    /// Lines that stand one under the other (a cell wrapped over several
    /// lines) are joined like the lines of a paragraph, so a word broken by a
    /// hyphen at the line end is whole again.
    fn cell_spans(&self, lines: &[Line]) -> Vec<Span> {
        let mut spans: Vec<Span> = Vec::new();
        for (line_idx, line) in lines.iter().enumerate() {
            let mut line_spans = self.line_spans(line);
            if let Some(next) = lines.get(line_idx + 1) {
                if next.baseline - line.baseline > line.size * self.cfg.cell_wrap_min_dy_em {
                    self.join_line_end(&mut line_spans, &line.text(), &next.text());
                } else if let Some(last) = line_spans.last_mut() {
                    last.text.push(' ');
                }
            }
            spans.extend(line_spans);
        }
        spans
    }
}

/// Anchor slug of a text: lowercase letters and digits, every other run of
/// characters replaced by one hyphen, at most [`MAX_SLUG_CHARS`] characters.
pub(crate) fn slug(text: &str) -> String {
    let mut out = String::new();
    for ch in text.chars() {
        if ch.is_alphanumeric() {
            out.extend(ch.to_lowercase());
        } else if !out.ends_with('-') && !out.is_empty() {
            out.push('-');
        }
    }
    out.trim_end_matches('-').chars().take(MAX_SLUG_CHARS).collect()
}

/// The words of a text: maximal runs of letters and hyphens.
pub(crate) fn tokens(text: &str) -> impl Iterator<Item = &str> {
    text.split(|ch: char| !(ch.is_alphabetic() || ch == '-'))
        .filter(|token| !token.is_empty())
}

/// The vocabulary of the document: every lowercase word (and every part of
/// a hyphenated word) that does not touch a line-end hyphen. Used to decide
/// whether a hyphen at a line break is part of the word.
pub(crate) fn build_vocab<'a>(blocks: impl Iterator<Item = &'a [Line]>) -> HashSet<String> {
    let mut vocab = HashSet::new();
    for lines in blocks {
        let mut prev_hyphen = false;
        for line in lines {
            let text = line.text();
            let ends_hyphen = text.ends_with('-');
            let line_tokens: Vec<&str> = tokens(&text).collect();
            let n = line_tokens.len();
            for (i, token) in line_tokens.into_iter().enumerate() {
                if (i == 0 && prev_hyphen) || (i + 1 == n && ends_hyphen) {
                    continue;
                }
                let word = token.trim_matches('-').to_lowercase();
                if word.is_empty() {
                    continue;
                }
                for part in word.split('-') {
                    if !part.is_empty() {
                        vocab.insert(part.to_string());
                    }
                }
                vocab.insert(word);
            }
            prev_hyphen = ends_hyphen;
        }
    }
    vocab
}

/// Whether a line ends inside a URL that the next line goes on with: the
/// last word of `text` is a URL ("https://…", "www.…") and ends where TeX
/// breaks URLs ("faster_" / "rcnn", "py-faster-" / "rcnn"). After a period
/// the next line must go on in lower case or with a digit ("github." /
/// "com/…"), not start a sentence.
pub(crate) fn url_continues(text: &str, next: &str) -> bool {
    let Some(last) = text.split_whitespace().last() else {
        return false;
    };
    let last = last.trim_start_matches(['(', '[', '<', '"', '\u{201c}']);
    // "http:" / "//arxiv.org/...": the scheme alone ends the line.
    if matches!(last, "http:" | "https:") && next.starts_with("//") {
        return true;
    }
    if !(last.contains("://") || last.starts_with("www.")) {
        return false;
    }
    let Some(first) = next.trim_start().chars().next() else {
        return false;
    };
    if next.starts_with(char::is_whitespace) {
        return false;
    }
    match last.chars().last() {
        Some('_' | '-' | '/' | '?' | '=' | '&' | '#' | '~' | '%' | ':') => true,
        // After a dot the URL goes on with a host or path part ("org/abs"),
        // not with a word of the text ("arXiv preprint").
        Some('.') => {
            let token = next.split_whitespace().next().unwrap_or("");
            let host = token.split('/').next().unwrap_or("");
            (first.is_lowercase() || first.is_ascii_digit()) && !host.chars().any(char::is_uppercase)
        }
        _ => false,
    }
}

/// Whether the hyphen ending `text`, inside a URL, was put there by
/// hyphenation: the letters on both sides of it make a word of the
/// document.
fn url_hyphen_is_soft(text: &str, next: &str, vocab: &HashSet<String>) -> bool {
    let left: String = text
        .chars()
        .rev()
        .skip(1)
        .take_while(|ch| ch.is_alphabetic())
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    let right: String = next.chars().take_while(|ch| ch.is_alphabetic()).collect();
    !left.is_empty() && !right.is_empty() && vocab.contains(&format!("{left}{right}").to_lowercase())
}

/// Decides whether a line-end hyphen is a soft hyphen (to be removed).
///
/// `left` is the text of the line ending with the hyphen, `right` the text
/// of the next line. The hyphen is kept when the continuation does not
/// start with a lowercase letter, when the left part is itself a
/// hyphenated compound ("state-of-"), when the hyphenated form is known
/// from the document, or when both halves are known words and the left one
/// is long enough; otherwise (including when the joined word is known, or
/// nothing is known) it is removed.
pub(crate) fn remove_hyphen(left: &str, right: &str, vocab: &HashSet<String>, cfg: &TextConfig) -> bool {
    let trailing: String = left
        .chars()
        .rev()
        .skip(1)
        .take_while(|ch| ch.is_alphabetic())
        .collect::<Vec<_>>()
        .into_iter()
        .rev()
        .collect();
    let leading: String = right.chars().take_while(|ch| ch.is_alphabetic()).collect();
    if trailing.is_empty() || leading.is_empty() {
        return false;
    }
    // "end-\nto-end": the right part goes on with a hyphen of its own, so
    // the broken one belongs to the compound too.
    if right.chars().nth(leading.chars().count()) == Some('-') {
        return false;
    }
    if !leading.chars().next().unwrap().is_lowercase() {
        // "PAS-\nCAL": TeX broke a word in capitals the paper uses whole.
        let capitals = |part: &str| part.chars().all(char::is_uppercase);
        return trailing.chars().count() >= 2
            && leading.chars().count() >= 2
            && capitals(&trailing)
            && capitals(&leading)
            && vocab.contains(&format!("{trailing}{leading}").to_lowercase());
    }
    // "state-of-\nthe-art": the left part is itself a hyphenated compound.
    let before: Vec<char> = left.chars().rev().skip(1 + trailing.chars().count()).take(1).collect();
    if before.first() == Some(&'-') {
        return false;
    }
    // "CNN-\nbased", "RoI-\nbased": TeX never breaks an acronym (two
    // capitals, the last letter one of them); the hyphen is real.
    if trailing.chars().filter(|ch| ch.is_uppercase()).count() >= 2
        && trailing.chars().last().is_some_and(char::is_uppercase)
    {
        return false;
    }
    let (left_part, right_part) = (trailing.to_lowercase(), leading.to_lowercase());
    if vocab.contains(&format!("{left_part}{right_part}")) {
        return true;
    }
    if vocab.contains(&format!("{left_part}-{right_part}")) {
        return false;
    }
    // "sequence-\naligned": both parts are words of the paper, the right one
    // perhaps with an inflection ("aligned" where the paper says "align").
    let known = |word: &str| {
        vocab.contains(word)
            || ["ed", "d", "ing", "s", "es"].iter().any(|suffix| {
                word.strip_suffix(suffix).is_some_and(|stem| {
                    stem.chars().count() >= cfg.compound_part_min_chars_count && vocab.contains(stem)
                })
            })
    };
    !(left_part.chars().count() >= cfg.compound_part_min_chars_count
        && vocab.contains(&left_part)
        && known(&right_part))
}

/// Removes the first `n` characters from a span list (dropping spans that
/// become empty), then the whitespace at the start of the first span.
pub(crate) fn strip_chars(spans: &mut Vec<Span>, mut n: usize) {
    while n > 0 && !spans.is_empty() {
        let len = spans[0].text.chars().count();
        if len <= n {
            n -= len;
            spans.remove(0);
        } else {
            spans[0].text = spans[0].text.chars().skip(n).collect();
            n = 0;
        }
    }
    if let Some(first) = spans.first_mut() {
        first.text = first.text.trim_start().to_string();
    }
}

/// Joins the line spans of a block into the running text: neighbouring
/// spans of the same style (after clearing the `mask` bits) and colour are
/// merged.
fn running_spans(hlines: &[HLine], mask: u8) -> Vec<Span> {
    let mut spans: Vec<Span> = Vec::new();
    for span in hlines.iter().flat_map(|hline| hline.spans.iter()) {
        let style = span.style & !mask;
        match spans.last_mut() {
            Some(prev) if prev.style == style && prev.color == span.color && prev.href == span.href => {
                prev.text.push_str(&span.text)
            }
            _ => spans.push(Span {
                text: span.text.clone(),
                style,
                href: span.href.clone(),
                color: span.color,
            }),
        }
    }
    spans
}

/// Moves the open run, if any, to the finished runs.
fn close_run(current: &mut Option<OpenRun>, runs: &mut Vec<EqRun>) {
    if let Some(open) = current.take() {
        runs.push(open.run);
    }
}

/// Whether two lines of a paragraph join without a space: Chinese and
/// Japanese are written without spaces between words, so a line that ends
/// with a CJK character and a next line that starts with one join directly
/// ("年々" / "増えています"), and so does a line that ends with a CJK
/// punctuation mark ("、" "。").
fn joins_without_space(text: &str, next: &str) -> bool {
    let (Some(last), Some(first)) = (text.trim_end().chars().last(), next.trim_start().chars().next()) else {
        return false;
    };
    is_cjk_punctuation_mark(last) || (is_cjk_char(last) && is_cjk_char(first))
}

/// Whether `ch` is a character of Chinese or Japanese text: a Han
/// ideograph, kana, a CJK punctuation mark or a full-width form.
fn is_cjk_char(ch: char) -> bool {
    matches!(
        ch,
        '\u{3000}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF00}'..='\u{FFEF}'
    )
}

/// Whether `ch` is a CJK punctuation mark (the ideographic comma and full
/// stop, brackets and quotes, and their full-width forms).
fn is_cjk_punctuation_mark(ch: char) -> bool {
    matches!(ch, '\u{3001}'..='\u{303F}') || (matches!(ch, '\u{FF01}'..='\u{FF65}') && !ch.is_alphanumeric())
}

#[cfg(test)]
#[allow(clippy::min_ident_chars, clippy::missing_docs_in_private_items)]
mod tests {
    use super::*;

    #[test]
    fn chinese_and_japanese_lines_join_without_space() {
        assert!(joins_without_space("外国人の数が年々", "増えています。"));
        assert!(joins_without_space("身につけるための教材です。", "Irodori"));
        assert!(!joins_without_space("such as 日本語", "while N2"));
        assert!(!joins_without_space("the people", "communicating"));
    }

    use std::collections::HashSet;

    fn vocab(words: &[&str]) -> HashSet<String> {
        words.iter().map(|w| w.to_string()).collect()
    }

    #[test]
    fn urls_broken_across_lines_go_on() {
        assert!(url_continues(
            "available at https://github.com/shaoqingren/faster_",
            "rcnn (in MATLAB) and"
        ));
        assert!(url_continues(
            "see https://github.com/rbgirshick/py-faster-",
            "rcnn (in Python)."
        ));
        assert!(url_continues("at www.robots.ox.ac.", "uk/~vgg"));
        assert!(!url_continues("results at https://example.com/page.html.", "We then"));
        assert!(!url_continues("the dot-product (multi-", "plicative) attention"));
        assert!(!url_continues("https://example.com/a", "and more"));
        let vocab: HashSet<String> = ["openai", "faster", "rcnn"].iter().map(|w| w.to_string()).collect();
        assert!(url_hyphen_is_soft("https://ope-", "nai.com/blog", &vocab));
        assert!(!url_hyphen_is_soft(
            "https://github.com/rbgirshick/py-faster-",
            "rcnn",
            &vocab
        ));
        assert!(url_continues("see http:", "//arxiv.org/abs/1804.08838"));
        assert!(url_continues("https://aclanthology.", "org/N19-1246"));
        assert!(!url_continues(
            "URL http://arxiv.org/abs/2104.08691.",
            "arXiv: 2104.08691."
        ));
    }

    #[test]
    fn soft_hyphens_are_removed() {
        let v = vocab(&["multi", "head", "multi-head", "self", "attention", "information"]);
        let cfg = TextConfig::default();
        // Unknown fragments: a plain word break.
        assert!(remove_hyphen("dot-product (multi-", "plicative) attention", &v, &cfg));
        // The joined word is known.
        assert!(remove_hyphen("more in-", "formation is needed", &v, &cfg));
        // Both halves are words of their own and the compound is not known.
        assert!(!remove_hyphen("layers of self-", "attention are used", &v, &cfg));
        // A compound seen elsewhere in the document keeps its hyphen.
        assert!(!remove_hyphen("we use multi-", "head attention", &v, &cfg));
        // Capitalised or non-alphabetic continuations keep the hyphen.
        assert!(!remove_hyphen("the English-", "German task", &v, &cfg));
        assert!(!remove_hyphen("pages 10-", "20 of the", &v, &cfg));
        // Part of a longer hyphenated compound.
        assert!(!remove_hyphen("a state-of-", "the-art model", &v, &cfg));
    }
}