kakemono 0.15.3

Convert scientific-paper PDFs (arXiv) and Word documents 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
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
//! Hard-95 mode: the page looks like the PDF, but everything that is text is
//! real, visible HTML text.
//!
//! Each page is drawn from the PDF with its text removed (so figures, rules
//! and other graphics stay vector pictures) and the text is put back as HTML
//! at its original place:
//!
//! * paragraphs, headings, captions, footnotes and references are flowing
//!   text in boxes at their original position, initially broken into exactly
//!   the lines of the PDF. A paragraph is one DOM element even when it
//!   continues in another column or on another page; the continuation boxes
//!   show a clipped copy;
//! * tables are real `<table>` elements laid out on the original grid;
//! * formulas are runs of text placed glyph run by glyph run;
//! * everything else (labels in figures, running heads, author lines) is
//!   placed line by line.
//!
//! A small script matches line widths to the PDF and, when the text changes
//! (for example after a translation), lets the affected block reflow inside
//! its box.

mod stacked;

use super::assets::origin_key;
use super::mathml::MATH_FACE;
use super::*;
use crate::common::geom::{Rect, median};
use crate::model::{Line, LineGlyph};
use std::collections::HashSet;

/// Style sheet of the mode, embedded in the page.
const CSS: &str = include_str!("hard95.css");
/// Script of the mode (zoom, line widths, reflow), embedded in the page.
const JS: &str = include_str!("hard95.js");
/// Style of the calls of added notes and of their popup, embedded
/// only in a page that has notes.
const NOTES_CSS: &str = include_str!("notes.css");
/// Script that shows an added note in a popup when its call is
/// tapped, embedded only in a page that has notes.
const NOTES_JS: &str = include_str!("notes.js");

/// Latin Modern, the fonts of LaTeX, for papers set in Computer Modern:
/// the text in the page then has the letter shapes and almost exactly the
/// widths of the PDF, so that fraction bars and radicals drawn in the page
/// picture stay over their text. Subsets with their vertical metrics set
/// to put the baseline where this mode places it (see `fonts/README.md`).
/// (family, style, weight, woff2 data).
const LATIN_MODERN: [(&str, &str, &str, &[u8]); 5] = [
    (
        "P2H LM Roman",
        "normal",
        "400",
        include_bytes!("fonts/lmroman10-regular.woff2"),
    ),
    (
        "P2H LM Roman",
        "italic",
        "400",
        include_bytes!("fonts/lmroman10-italic.woff2"),
    ),
    (
        "P2H LM Roman",
        "normal",
        "700",
        include_bytes!("fonts/lmroman10-bold.woff2"),
    ),
    (
        "P2H LM Roman",
        "italic",
        "700",
        include_bytes!("fonts/lmroman10-bolditalic.woff2"),
    ),
    (
        "P2H LM Mono",
        "normal",
        "400",
        include_bytes!("fonts/lmmono10-regular.woff2"),
    ),
];

/// Distance of the baseline from the top of a line box whose line-height
/// equals the font size, in em (typical for Times/Helvetica-like fonts).
const BASELINE: f32 = 0.84;

/// Prefixes of the (lower-cased) body font names of Computer Modern and its
/// relatives; such papers get the `cm` class, which selects a matching web
/// font.
const COMPUTER_MODERN_PREFIXES: [&str; 6] = ["cmr", "lmr", "lmroman", "cmu", "sfrm", "ecrm"];
/// Parts of the (lower-cased) names of the math fonts of TeX (Computer
/// Modern and Latin Modern); papers whose formulas use them get the `tm`
/// class, which sets formulas in Latin Modern even when the text is in
/// another font.
const TEX_MATH_NAMES: [&str; 7] = ["cmmi", "cmsy", "cmex", "lmmi", "lmsy", "lmex", "latinmodern-math"];

/// Characters whose glyphs stay in the page picture, where the text leaves
/// a gap for them: glyphs without Unicode value (U+FFFD), which cannot be
/// written, and radical signs, which TeX fonts hang below their origin and
/// whose bar is a rule of the picture.
const PICTURE_CHARS: [char; 2] = ['\u{FFFD}', '\u{221A}'];

/// A glyph whose ink is taller than this (in em of its font size) is a big
/// delimiter or operator of a formula (a parenthesis around a fraction, an
/// integral sign): it stays in the page picture, drawn exactly. Ordinary
/// parentheses are about 1 em tall. The same height as the analysis's
/// `tall_glyph_min_height_em`, which gives such a glyph of a formula a run
/// of its own.
const TALL_GLYPH_MIN_EM: f32 = 1.3;

/// Smallest and largest width of the gap left for a glyph without Unicode
/// value, in em: keeps odd glyph boxes from making absurd gaps.
const GAP_WIDTH_RANGE_EM: (f32, f32) = (0.1, 3.0);
/// Width of a gap for which no glyph width is known, in em.
const DEFAULT_GAP_EM: f32 = 0.5;

/// A line whose baseline is higher than the previous one by more than this
/// (in em of its font size) starts a new fragment: the block continues at
/// the top of another column.
const COLUMN_BREAK_RISE_EM: f32 = 0.5;
/// Distances between consecutive baselines below this (in em of the block
/// font size) are not line pitches (superscript lines, overlapping lines).
const MIN_PITCH_EM: f32 = 0.5;
/// Smallest line pitch of a block, in em of its font size.
const MIN_LEAD_EM: f32 = 0.9;
/// A line whose font size differs from the block font size by more than
/// this (in points) gets its own font size.
const FONT_SIZE_TOLERANCE_PT: f32 = 0.3;
/// A line whose right end is within this distance (in points) of the right
/// edge of its fragment is a full line.
const FULL_LINE_TOLERANCE_PT: f32 = 1.5;
/// Lines whose centres are all within this distance (in points) of their
/// median centre are centred...
const CENTRED_TOLERANCE_PT: f32 = 2.5;
/// ...provided at least one line starts more than this (in points) from the
/// left edge of the block (otherwise the block is simply left-aligned).
const CENTRED_MIN_OFFSET_PT: f32 = 3.0;
/// Fewest lines a block needs to be recognised as centred.
const CENTRED_MIN_LINES: usize = 2;
/// Fewest lines a block needs to be recognised as justified.
const JUSTIFY_MIN_LINES: usize = 3;
/// A block is justified when at least this many tenths of its lines (not
/// counting the last one) are full lines.
const JUSTIFY_FULL_TENTHS: usize = 6;
/// A line of a flowing block is moved off the evenly spaced lines of its box
/// only when its baseline in the PDF is at least this far (in points) from
/// its place there; smaller differences are rounding.
const MIN_LINE_SHIFT_PT: f32 = 0.1;

/// A line of a table needs about this much height (in em of the table font
/// size); a row band thinner than this makes the browser grow the row.
const TABLE_MIN_ROW_EM: f32 = 0.95;
/// A table whose rows would have to grow by more than this fraction of the
/// height of its region to hold their text is not rebuilt: its grid is not
/// the grid of the printed table, and the rebuilt table would run over the
/// text below it.
const TABLE_MAX_GROWTH_RATIO: f32 = 0.10;

/// A rotated run belongs to a figure when its middle lies within the picture
/// region of the figure grown by this much (in points): axis titles sit at
/// the very edge of the region.
const FIGURE_REGION_MARGIN_PT: f32 = 2.0;

/// Converts PDF points to CSS lengths relative to one page.
struct Units {
    /// Width of the page in points.
    page_width: f32,
    /// Height of the page in points.
    page_height: f32,
}

impl Units {
    /// Horizontal position or width as a percentage of the page width.
    fn x(&self, value: f32) -> String {
        format!("{:.3}%", value / self.page_width * 100.0)
    }
    /// Vertical position or height as a percentage of the page height.
    fn y(&self, value: f32) -> String {
        format!("{:.3}%", value / self.page_height * 100.0)
    }
    /// A length that scales with the page (font sizes, margins).
    fn len(&self, value: f32) -> String {
        format!("{:.3}cqw", value / self.page_width * 100.0)
    }
    /// A width as a percentage of the page width, without unit (for the
    /// `data-w` attributes read by the script).
    fn width_attr(&self, value: f32) -> String {
        format!("{:.3}", value / self.page_width * 100.0)
    }
}

/// Consecutive lines of a block that sit in one column of one page.
struct Fragment {
    /// Index of the first line in the block.
    start: usize,
    /// Index after the last line in the block.
    end: usize,
    /// Page of the lines.
    page: usize,
    /// Left edge of the lines.
    x0: f32,
    /// Right edge of the lines.
    x1: f32,
}

/// How the boxes of a flowing block are set: shared by all its fragments.
struct BoxStyle {
    /// Font size of the block (median of its lines).
    size: f32,
    /// Line pitch of the block.
    lead: f32,
    /// Width of the widest fragment.
    width: f32,
    /// Indent of the first line relative to the others (negative for a
    /// hanging indent).
    indent: f32,
    /// The lines are centred.
    centred: bool,
    /// Text alignment when the block reflows: `center`, `justify` or `left`.
    align: &'static str,
}

/// Where the lines of a flowing block go in its boxes. The boxes space their
/// lines evenly (one line pitch apart, so the text can reflow); lines of the
/// PDF that are further apart or closer (a line with an inline fraction,
/// for example) are moved to their own baseline.
struct LinePlacement {
    /// For each line of the block, how far (in points, downwards) it is moved
    /// from its evenly spaced place.
    shifts: Vec<f32>,
    /// For each fragment, the height (in points) added below its evenly
    /// spaced lines so that its lowest line still fits in its box.
    extra: Vec<f32>,
}

/// The text layer of one page being written, with the glyphs it draws.
struct PageLayer<'u> {
    /// Units of the page.
    units: &'u Units,
    /// Index of the page.
    page_idx: usize,
    /// The HTML of the layer.
    html: String,
    /// Origins of all glyphs that are drawn as HTML on this page; they are
    /// removed from the picture of the page.
    drawn: HashSet<(i32, i32)>,
}

impl PageLayer<'_> {
    /// Adds the part of `block` that is on this page: an equation, author
    /// lines, or a text block with the content of its float.
    fn block(&mut self, doc: &Document, block: &Block) {
        // The target of cross references ("#fig-3", "#ref-12") to this block.
        if let Some(anchor) = block.anchor.as_deref().filter(|_| block.page == self.page_idx) {
            self.html.push_str(&format!(
                "<a class=\"anc\" id=\"{}\" style=\"left:{};top:{}\"></a>\n",
                esc(anchor),
                self.units.x(block.bbox.x0),
                self.units.y(block.bbox.y0)
            ));
        }
        match &block.kind {
            BlockKind::Equation { .. } => self.equation(block),
            BlockKind::Authors => self.authors(doc, block),
            _ => {
                // Caption or text block.
                self.text_block(doc, block);
                self.float_content(block);
            }
        }
    }

    /// Adds an equation that starts on this page, glyph run by glyph run.
    fn equation(&mut self, block: &Block) {
        if block.lines.first().is_some_and(|line| line.page == self.page_idx) {
            self.html.push_str(&equation(block, self.units));
            block
                .lines
                .iter()
                .for_each(|line| add_origins(&mut self.drawn, line, true));
        }
    }

    /// Adds the author lines on this page, each placed on its own (edited
    /// ones flow in the box of the group, see [`is_edited`]).
    fn authors(&mut self, doc: &Document, block: &Block) {
        if is_edited(block) {
            self.text_block(doc, block);
            return;
        }
        let mut html = String::new();
        for (line, hline) in block
            .lines
            .iter()
            .zip(&block.hlines)
            .filter(|(line, _)| line.page == self.page_idx)
        {
            html.push_str(&placed_line(self.units, line, &hline.spans));
            add_origins(&mut self.drawn, line, true);
        }
        if !html.is_empty() {
            self.html.push_str(&format!(
                "<div class=\"b\" data-kind=\"authors\" data-block=\"{}\">{html}</div>\n",
                block.id
            ));
        }
    }

    /// Adds the boxes of a flowing text block (or caption) on this page.
    fn text_block(&mut self, doc: &Document, block: &Block) {
        let html = flow_block(doc, block, self.page_idx, self.units);
        if !html.is_empty() {
            self.html.push_str(&html);
            // The edited text flows elsewhere than the glyphs it replaces:
            // none of them may stay in the picture.
            let edited = is_edited(block);
            for line in block.lines.iter().filter(|line| line.page == self.page_idx) {
                if edited {
                    add_all_origins(&mut self.drawn, line);
                } else {
                    add_origins(&mut self.drawn, line, true);
                }
            }
        }
    }

    /// Adds the content of a float that starts on this page: a table, or
    /// its text placed line by line.
    fn float_content(&mut self, block: &Block) {
        if !block.inner_lines.first().is_some_and(|line| line.page == self.page_idx)
            || replaced_picture(block).is_some()
        {
            return;
        }
        match block.table.as_ref().filter(|table| table_fits(table)) {
            Some(table) => {
                self.html
                    .push_str(&table_box(table, is_edited_table(block), self.units));
                block
                    .inner_lines
                    .iter()
                    .for_each(|line| add_origins(&mut self.drawn, line, false));
            }
            // The text inside a figure (or of a table whose grid could not be
            // rebuilt faithfully) stays in the page picture, where it
            // is drawn in the figure's own order: a legend box may cover
            // tick labels, which HTML laid on top would show. The HTML copy
            // is transparent, for selecting, searching and copying.
            None => {
                let mut html = String::new();
                for (line, spans) in block.inner_lines.iter().zip(&block.inner_spans) {
                    html.push_str(&placed_line(self.units, line, spans));
                }
                self.html.push_str(&format!(
                    "<div class=\"b\" data-kind=\"figure-text\" data-block=\"{}\">{html}</div>\n",
                    block.id
                ));
            }
        }
    }

    /// Adds the lines of the page that belong to no block (running heads,
    /// page numbers), each placed on its own.
    fn furniture(&mut self, loose: &[PLine]) {
        let mut html = String::new();
        for loose_line in loose {
            html.push_str(&placed_line(self.units, &loose_line.line, &loose_line.spans));
            add_origins(&mut self.drawn, &loose_line.line, true);
        }
        if !html.is_empty() {
            self.html
                .push_str(&format!("<div class=\"b\" data-kind=\"page-furniture\">{html}</div>\n"));
        }
    }

    /// Adds rotated text, turned around the start of its baseline. Text that
    /// lies inside a figure (axis titles) stays in the page picture, like the
    /// other text of the figure, and gets a transparent copy; the rest is
    /// drawn as visible text.
    fn rotated(&mut self, doc: &Document, rotated: &[RotatedRun]) {
        let figures = figure_regions(doc, self.page_idx);
        let replaced: Vec<Rect> = doc
            .blocks
            .iter()
            .filter_map(replaced_picture)
            .filter(|spec| spec.page == self.page_idx)
            .map(|spec| spec.rect)
            .collect();
        let mut visible = String::new();
        let mut in_figure = String::new();
        for run in rotated {
            let html = rotated_run_html(run, self.units);
            if replaced.iter().any(|rect| run_in_region(run, rect)) {
                continue;
            }
            if figures.iter().any(|rect| run_in_region(run, rect)) {
                in_figure.push_str(&html);
            } else {
                visible.push_str(&html);
                for &(x, y) in &run.origins {
                    self.drawn.insert(origin_key(x, y));
                }
            }
        }
        if !visible.is_empty() {
            self.html.push_str(&format!(
                "<div class=\"b\" data-kind=\"rotated-text\">{visible}</div>\n"
            ));
        }
        if !in_figure.is_empty() {
            self.html.push_str(&format!(
                "<div class=\"b\" data-kind=\"figure-text\">{in_figure}</div>\n"
            ));
        }
    }
}

/// The picture of a figure of the PDF replaced with `replace_image` (a
/// stored picture in place of its region of the page), if `block` is one.
fn replaced_picture(block: &Block) -> Option<&ImageSpec> {
    match &block.kind {
        BlockKind::Figure { image: Some(spec), .. } if spec.embedded.is_some() => Some(spec),
        _ => None,
    }
}

/// A replaced figure's picture, in a white box over its region of the page
/// (which still shows the original figure), fitted without stretching.
fn replaced_figure(id: usize, spec: &ImageSpec, images: &mut ImageStore<'_>, units: &Units) -> String {
    format!(
        "<div class=\"b\" data-kind=\"figure-picture\" data-block=\"{id}\" style=\"position:absolute;left:{};top:{};width:{};height:{};background:#fff\"><img src=\"{}\" alt=\"\" style=\"display:block;width:100%;height:100%;object-fit:contain\"></div>\n",
        units.x(spec.rect.x0),
        units.y(spec.rect.y0),
        units.x(spec.rect.width()),
        units.y(spec.rect.height()),
        images.region(spec, "fig"),
    )
}

/// The picture regions of the figures on page `page_idx` (tables are not
/// included: their text is drawn as HTML).
fn figure_regions(doc: &Document, page_idx: usize) -> Vec<Rect> {
    doc.blocks
        .iter()
        .filter(|block| block.table.is_none())
        .filter_map(|block| match &block.kind {
            BlockKind::Figure { image: Some(image), .. } if image.page == page_idx => Some(image.rect),
            _ => None,
        })
        .collect()
}

/// Whether the middle of a rotated run lies inside `rect` (grown by
/// [`FIGURE_REGION_MARGIN_PT`]).
pub(crate) fn run_in_region(run: &RotatedRun, rect: &Rect) -> bool {
    let (sin, cos) = run.angle.to_radians().sin_cos();
    let half = run.length * 0.5;
    // The middle of the baseline, moved up by about the height of the
    // letters to the middle of the text.
    let mid_x = run.x + cos * half + sin * run.size * 0.3;
    let mid_y = run.y + sin * half - cos * run.size * 0.3;
    rect.inflate(FIGURE_REGION_MARGIN_PT, FIGURE_REGION_MARGIN_PT)
        .contains_point(mid_x, mid_y)
}

/// One rotated run as an HTML element turned around its origin.
fn rotated_run_html(run: &RotatedRun, units: &Units) -> String {
    let span = Span {
        text: run.text.clone(),
        style: run.style,
        href: None,
        color: run.color,
        math: None,
        note: None,
    };
    format!(
        "<span class=\"rt\" style=\"left:{};top:{};font-size:{};transform:rotate({:.2}deg)\" data-w=\"{}\">{}</span>",
        units.x(run.x),
        units.y(run.y - BASELINE * run.size),
        units.len(run.size),
        run.angle,
        units.width_attr(run.length),
        span_html(&span, &run.text, &mut [].iter()),
    )
}

/// The `hard-95` mode: facsimile pages whose text is real, visible HTML.
pub(crate) struct Hard95;

impl Renderer for Hard95 {
    fn render(&self, analysis: &Analysis, images: &mut ImageStore<'_>) -> String {
        render(analysis, images)
    }
}

/// Writes the whole document in hard-95 mode. The page pictures (without
/// the text drawn as HTML) are requested from `images`, one per page in page
/// order.
pub(crate) fn render(analysis: &Analysis, images: &mut ImageStore<'_>) -> String {
    let doc = &analysis.doc;
    let title = doc_title(doc);
    let lower = doc.body_font.to_ascii_lowercase();
    let computer_modern = COMPUTER_MODERN_PREFIXES.iter().any(|prefix| lower.contains(prefix));
    let math_lower = doc.math_font.to_ascii_lowercase();
    let tex_math = TEX_MATH_NAMES.iter().any(|name| math_lower.contains(name));

    let mut pages = String::new();
    for (page_idx, page) in doc.pages.iter().enumerate() {
        pages.push_str(&page_html(analysis, page_idx, page, images));
    }

    let source = arxiv_abs_link(doc);
    // Computer Modern papers, and papers with TeX formulas, get Latin
    // Modern, and Latin Modern Math for the symbols that the text fonts do
    // not have.
    let fonts = if (computer_modern || tex_math) && images.opts.embed_fonts {
        let mut faces: String = LATIN_MODERN
            .iter()
            .map(|(family, style, weight, data)| font_face(family, style, weight, data))
            .collect();
        faces.push_str(&MATH_FACE);
        faces
    } else {
        String::new()
    };
    let (notes_css, notes_js) = if pages.contains("<sup class=\"an\"") {
        (NOTES_CSS, format!("<script>\n{NOTES_JS}</script>\n"))
    } else {
        ("", String::new())
    };
    format!(
        r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" content="kakemono (hard-95)">
<title>{title}</title>
<style>
{fonts}{CSS}{notes_css}</style>
</head>
<body class="hard95 fit{cm}{tm}">
<div class="topbar"><span class="t">{title}</span>{source}<span>{n} pages</span><button id="zout" type="button" aria-label="Zoom out">−</button><button id="zfit" type="button">Fit</button><button id="zin" type="button" aria-label="Zoom in">+</button></div>
<main class="pages">
{pages}</main>
<script>
{JS}</script>
{notes_js}</body>
</html>
"#,
        title = esc(&title),
        n = doc.pages.len(),
        cm = if computer_modern { " cm" } else { "" },
        tm = if tex_math { " tm" } else { "" },
    )
}

/// One page: the picture of the page without the text that the text layer
/// over it draws.
fn page_html(analysis: &Analysis, page_idx: usize, page: &PageInfo, images: &mut ImageStore<'_>) -> String {
    let doc = &analysis.doc;
    let units = Units {
        page_width: page.width,
        page_height: page.height,
    };
    let mut layer = PageLayer {
        units: &units,
        page_idx,
        html: String::new(),
        drawn: HashSet::new(),
    };
    for block in &doc.blocks {
        layer.block(doc, block);
    }
    if let Some(loose) = analysis.loose.get(page_idx) {
        layer.furniture(loose);
    }
    if let Some(rotated) = analysis.rotated.get(page_idx) {
        layer.rotated(doc, rotated);
    }
    let PageLayer {
        html: mut layer, drawn, ..
    } = layer;
    for block in &doc.blocks {
        if let Some(spec) = replaced_picture(block).filter(|spec| spec.page == page_idx) {
            layer.push_str(&replaced_figure(block.id, spec, images, &units));
        }
    }

    let bg = format!(
        "<img class=\"bg\" src=\"{}\" alt=\"\" width=\"{}\" height=\"{}\" loading=\"lazy\" decoding=\"async\">",
        images.page_without_text(page_idx, drawn),
        page.width,
        page.height
    );
    format!(
        "<section class=\"page\" id=\"page-{n}\" data-page=\"{n}\" style=\"--pw:{};--ph:{};aspect-ratio:{}/{}\">\n{bg}\n<div class=\"tl\">\n{layer}</div>\n</section>\n",
        page.width,
        page.height,
        page.width,
        page.height,
        n = page_idx + 1,
    )
}

/// Whether a glyph of a line of text stays in the page picture because it
/// is much taller than its font size (see [`TALL_GLYPH_MIN_EM`]).
fn is_tall(glyph: &LineGlyph) -> bool {
    glyph.text.chars().count() == 1 && glyph.ink.height() > TALL_GLYPH_MIN_EM * glyph.size
}

/// Widths (in em) of the glyphs of a line that stay in the picture of the
/// page (see [`PICTURE_CHARS`]); the text leaves a gap for them.
fn gaps_of(line: &Line) -> Vec<f32> {
    line.glyphs
        .iter()
        .filter(|glyph| glyph.text.contains(PICTURE_CHARS))
        .map(|glyph| ((glyph.x1 - glyph.x0) / line.size.max(1.0)).clamp(GAP_WIDTH_RANGE_EM.0, GAP_WIDTH_RANGE_EM.1))
        .collect()
}

/// One styled span as HTML. `text` is the part of the span's text to write;
/// each character of [`PICTURE_CHARS`] in it becomes a gap whose width is
/// taken from `gaps`.
fn span_html(span: &Span, text: &str, gaps: &mut std::slice::Iter<'_, f32>) -> String {
    let mut out = String::new();
    let mut piece = String::new();
    for ch in text.chars() {
        if !PICTURE_CHARS.contains(&ch) {
            piece.push(ch);
            continue;
        }
        out.push_str(&esc(&piece));
        piece.clear();
        let width_em = gaps.next().copied().unwrap_or(DEFAULT_GAP_EM);
        // A known character stays in the text (copied, read aloud), unseen.
        let unseen = if ch == '\u{FFFD}' {
            String::new()
        } else {
            ch.to_string()
        };
        out.push_str(&format!(
            "<span class=\"ph\" style=\"width:{width_em:.3}em\">{unseen}</span>"
        ));
    }
    out.push_str(&esc(&piece));
    wrap_span(span, out)
}

/// The HTML `inner` of a span's text wrapped in the elements of its style,
/// colour and link.
fn wrap_span(span: &Span, inner: String) -> String {
    if let Some(note) = &span.note {
        return note_call(span, note);
    }
    let mut out = inner;
    let mut classes: Vec<&str> = Vec::new();
    if span.style & MONO != 0 {
        classes.push("m");
    } else if span.style & SANS != 0 {
        classes.push("s");
    }
    if span.style & MATH != 0 {
        classes.push("x");
    }
    if span.style & SMALL_CAPS != 0 {
        classes.push("sc");
    }
    if span.style & SUP != 0 {
        out = format!("<sup>{out}</sup>");
    }
    if span.style & SUB != 0 {
        out = format!("<sub>{out}</sub>");
    }
    if span.style & ITALIC != 0 {
        out = format!("<i>{out}</i>");
    }
    if span.style & BOLD != 0 {
        out = format!("<b>{out}</b>");
    }
    let color = (span.color != [0; 3])
        .then(|| format!("color:#{:02x}{:02x}{:02x}", span.color[0], span.color[1], span.color[2]));
    if !classes.is_empty() || color.is_some() {
        let cls = if classes.is_empty() {
            String::new()
        } else {
            format!(" class=\"{}\"", classes.join(" "))
        };
        let style = color.map(|color| format!(" style=\"{color}\"")).unwrap_or_default();
        out = format!("<span{cls}{style}>{out}</span>");
    }
    match &span.href {
        Some(href) if href.starts_with('#') => format!("<a href=\"{}\">{out}</a>", esc(href)),
        Some(href) => format!(
            "<a href=\"{}\" target=\"_blank\" rel=\"noopener noreferrer\">{out}</a>",
            esc(href)
        ),
        None => out,
    }
}

/// Styled spans as HTML. Returns the markup and whether the text ended with
/// a space (which the caller places outside the line element).
fn spans_h95(spans: &[Span], gaps: &[f32]) -> (String, bool) {
    let mut out = String::new();
    let mut trailing = false;
    let mut gaps = gaps.iter();
    for (i, span) in spans.iter().enumerate() {
        let mut text = span.text.as_str();
        if i + 1 == spans.len() && text.ends_with(' ') {
            text = text.trim_end_matches(' ');
            trailing = true;
        }
        if !text.is_empty() {
            out.push_str(&span_html(span, text, &mut gaps));
        }
    }
    (out, trailing)
}

/// A line placed on its own: `left`/`top` position, font size, and the width
/// it must have. Returns an empty string when the line has no text.
fn placed_line(units: &Units, line: &Line, spans: &[Span]) -> String {
    let (html, _) = stacked::line_html(line, spans, units);
    if html.is_empty() {
        return String::new();
    }
    format!(
        "<span class=\"pl\" style=\"left:{};top:{};font-size:{}\" data-w=\"{}\">{html}</span>",
        units.x(line.bbox.x0),
        units.y(line.baseline - BASELINE * line.size),
        units.len(line.size),
        units.width_attr(line.bbox.width()),
    )
}

/// Splits the lines of a block into fragments: a new fragment starts on a
/// new page and where the baseline goes up (a new column).
fn fragments(lines: &[Line]) -> Vec<Fragment> {
    let mut out: Vec<Fragment> = Vec::new();
    for (i, line) in lines.iter().enumerate() {
        let new = match (out.last(), i.checked_sub(1).map(|prev_idx| &lines[prev_idx])) {
            (Some(frag), Some(prev)) => {
                line.page != frag.page || line.baseline < prev.baseline - COLUMN_BREAK_RISE_EM * line.size
            }
            _ => true,
        };
        if new {
            out.push(Fragment {
                start: i,
                end: i + 1,
                page: line.page,
                x0: line.bbox.x0,
                x1: line.bbox.x1,
            });
        } else {
            let frag = out.last_mut().unwrap();
            frag.end = i + 1;
            frag.x0 = frag.x0.min(line.bbox.x0);
            frag.x1 = frag.x1.max(line.bbox.x1);
        }
    }
    out
}

/// The boxes of a flowing block on page `page_idx`: the block itself where it
/// starts, clipped copies where it continues. Returns an empty string when
/// the block has no line on the page, or no line text to show.
fn flow_block(doc: &Document, block: &Block, page_idx: usize, units: &Units) -> String {
    let edited = is_edited(block);
    if block.lines.is_empty() || (!edited && block.hlines.len() != block.lines.len()) {
        return String::new();
    }
    let frags = fragments(&block.lines);
    if !frags.iter().any(|frag| frag.page == page_idx) {
        return String::new();
    }
    let size = median(
        &block.lines.iter().map(|line| line.size).collect::<Vec<_>>(),
        doc.body_size,
    );
    let lead = line_pitch(doc, block, &frags, size);
    let width = frags.iter().map(|frag| frag.x1 - frag.x0).fold(0.0, f32::max);
    let placement = line_placement(block, &frags, lead);
    let style = box_style(block, &frags, size, lead, width);
    let inner = if edited {
        edited_html(block)
    } else {
        flow_lines(block, &frags, size, &placement.shifts, style.align == "justify", units)
    };
    fragment_boxes(block, &frags, page_idx, &style, &placement.extra, &inner, edited, units)
}

/// The call of an added note: its number (the text of the numbered
/// call), raised, with the note as its tooltip and, hidden, as the content
/// of the popup that `notes.js` opens when the call is tapped. The page has
/// no room for the note itself.
fn note_call(call: &Span, note: &[Span]) -> String {
    let plain: String = note.iter().map(|span| span.text.as_str()).collect();
    let content: String = note.iter().map(|span| wrap_span(span, esc(&span.text))).collect();
    format!(
        "<sup class=\"an\" tabindex=\"0\" role=\"button\" title=\"{}\">{}<span class=\"an-c\" hidden>{content}</span></sup>",
        esc(plain.trim()),
        esc(&call.text)
    )
}

/// Whether the text of `block` was edited after the analysis (see
/// `render::json::apply`): its per-line text is gone, so it flows inside
/// the box of its lines instead of keeping them.
fn is_edited(block: &Block) -> bool {
    !matches!(block.kind, BlockKind::Equation { .. })
        && !block.lines.is_empty()
        && block.hlines.is_empty()
        && !block.spans.is_empty()
}

/// Whether the cells of the table of `block` were edited after the
/// analysis: the per-line text of the float is gone then.
fn is_edited_table(block: &Block) -> bool {
    !block.inner_lines.is_empty() && block.inner_spans.is_empty()
}

/// The edited text of a block as one flowing line (the rows of an author
/// group separated by line breaks). Glyphs left in the picture for
/// unedited text are written as text here, since the picture no longer
/// holds them where the text goes (see [`add_all_origins`]); glyphs without
/// Unicode value are left out.
fn edited_html(block: &Block) -> String {
    let spans_html = |spans: &[Span]| -> String {
        spans
            .iter()
            .map(|span| wrap_span(span, esc(&span.text.replace('\u{FFFD}', ""))))
            .collect()
    };
    let html = if matches!(block.kind, BlockKind::Authors) && !block.rows.is_empty() {
        block
            .rows
            .iter()
            .map(|row| spans_html(row))
            .collect::<Vec<_>>()
            .join("<br>")
    } else {
        spans_html(&block.spans)
    };
    format!("<span class=\"ln end\">{html}</span>")
}

/// Line pitch of a block of font size `size`: the median distance between
/// consecutive baselines within its fragments, or the document leading
/// scaled to the block font size when it has no such pair.
fn line_pitch(doc: &Document, block: &Block, frags: &[Fragment], size: f32) -> f32 {
    let mut pitches = Vec::new();
    for frag in frags {
        for pair in block.lines[frag.start..frag.end].windows(2) {
            let pitch = pair[1].baseline - pair[0].baseline;
            if pitch > MIN_PITCH_EM * size {
                pitches.push(pitch);
            }
        }
    }
    median(&pitches, doc.leading * size / doc.body_size).max(MIN_LEAD_EM * size)
}

/// How far each line of a block is moved from the evenly spaced lines of its
/// box (pitch `lead`) to sit on its baseline in the PDF, and how much taller
/// each fragment box is made for it.
///
/// Within a fragment, a line is placed relative to the first line of the
/// fragment. The height added to a fragment box is carried over to the lines
/// of the following fragments, so that in every box (which shows the whole
/// block, clipped) the lines of the other fragments stay outside the box.
fn line_placement(block: &Block, frags: &[Fragment], lead: f32) -> LinePlacement {
    let mut shifts = Vec::with_capacity(block.lines.len());
    let mut extra = Vec::with_capacity(frags.len());
    let mut carried = 0.0;
    for frag in frags {
        let first = block.lines[frag.start].baseline;
        let mut lowest = 0.0f32;
        for (line_no, line) in block.lines[frag.start..frag.end].iter().enumerate() {
            let below_first = line.baseline - first;
            lowest = lowest.max(below_first);
            shifts.push(below_first - line_no as f32 * lead + carried);
        }
        let mut added = lowest - (frag.end - frag.start - 1) as f32 * lead;
        if added < MIN_LINE_SHIFT_PT {
            added = 0.0;
        }
        extra.push(added);
        carried += added;
    }
    LinePlacement { shifts, extra }
}

/// The lines of a flowing block, each kept on a line of its own, with their
/// indent within the fragment, the width they must have and how far they
/// are moved down (`shifts`, see [`line_placement`]). When the block is
/// `justified`, its full lines are marked `data-j`: only those may be
/// fitted to their width by stretching the word spaces.
fn flow_lines(block: &Block, frags: &[Fragment], size: f32, shifts: &[f32], justified: bool, units: &Units) -> String {
    let mut inner = String::new();
    for (frag_idx, frag) in frags.iter().enumerate() {
        let range = frag.start..frag.end;
        let lines = block.lines[range.clone()].iter().zip(&block.hlines[range.clone()]);
        for (i, ((line, hline), &shift)) in range.clone().zip(lines.zip(&shifts[range])) {
            let (html, trailing) = stacked::line_html(line, &hline.spans, units);
            let mut style = format!("margin-left:{}", units.len((line.bbox.x0 - frag.x0).max(0.0)));
            if (line.size - size).abs() > FONT_SIZE_TOLERANCE_PT {
                style.push_str(&format!(";font-size:{}", units.len(line.size)));
            }
            if shift.abs() >= MIN_LINE_SHIFT_PT {
                style.push_str(&format!(";top:{}", units.len(shift)));
            }
            let last = frag_idx + 1 == frags.len() && i + 1 == frag.end;
            let full = justified && (frag.x1 - line.bbox.x1).abs() < FULL_LINE_TOLERANCE_PT;
            inner.push_str(&format!(
                "<span class=\"ln{}{}\" style=\"{style}\" data-w=\"{}\"{}>{html}</span>{}",
                if hline.soft_hyphen { " hy" } else { "" },
                if last { " end" } else { "" },
                units.width_attr(line.bbox.width()),
                if full { " data-j=\"1\"" } else { "" },
                if trailing { " " } else { "" },
            ));
        }
    }
    inner
}

/// How the block is set when it has to reflow: first-line indent and
/// alignment (centred, justified or left), from the geometry of its lines.
fn box_style(block: &Block, frags: &[Fragment], size: f32, lead: f32, width: f32) -> BoxStyle {
    let first = &block.lines[0];
    let rest_x0 = block.lines[frags[0].start + 1..frags[0].end]
        .iter()
        .map(|line| line.bbox.x0)
        .fold(f32::INFINITY, f32::min);
    let indent = if rest_x0.is_finite() {
        first.bbox.x0 - rest_x0
    } else {
        0.0
    };
    let full = block
        .lines
        .iter()
        .enumerate()
        .filter(|(i, line)| {
            let frag = frags.iter().find(|frag| frag.start <= *i && *i < frag.end).unwrap();
            (frag.x1 - line.bbox.x1).abs() < FULL_LINE_TOLERANCE_PT
        })
        .count();
    let centred = block.lines.len() >= CENTRED_MIN_LINES && {
        let centers: Vec<f32> = block.lines.iter().map(|line| line.bbox.cx()).collect();
        let mid = median(&centers, 0.0);
        centers.iter().all(|center| (center - mid).abs() < CENTRED_TOLERANCE_PT)
            && block
                .lines
                .iter()
                .any(|line| (line.bbox.x0 - frags[0].x0).abs() > CENTRED_MIN_OFFSET_PT)
    };
    let align = if centred {
        "center"
    } else if block.lines.len() >= JUSTIFY_MIN_LINES && full * 10 >= (block.lines.len() - 1) * JUSTIFY_FULL_TENTHS {
        "justify"
    } else {
        "left"
    };
    BoxStyle {
        size,
        lead,
        width,
        indent,
        centred,
        align,
    }
}

/// The boxes of the fragments of a block that are on page `page_idx`, each
/// showing `inner` (the lines of the whole block). The first fragment holds
/// the text; the others are clipped copies shifted up by the lines shown
/// before them, hidden from assistive technology and translation. `extra`
/// is the height added to each fragment box (see [`line_placement`]). The
/// boxes of an `edited` block start in reflow mode, and the script fits
/// their text into them.
#[allow(
    clippy::too_many_arguments,
    reason = "the parts of one flowing block, computed by flow_block"
)]
fn fragment_boxes(
    block: &Block,
    frags: &[Fragment],
    page_idx: usize,
    style: &BoxStyle,
    extra: &[f32],
    inner: &str,
    edited: bool,
    units: &Units,
) -> String {
    let BoxStyle {
        size,
        lead,
        width,
        indent,
        centred,
        align,
    } = *style;
    let mut out = String::new();
    let mut lines_before = 0usize;
    let mut extra_before = 0.0;
    for (frag_idx, frag) in frags.iter().enumerate() {
        let n = frag.end - frag.start;
        if frag.page == page_idx {
            let top = block.lines[frag.start].baseline - (lead * 0.5 + (BASELINE - 0.5) * size);
            let geometry = format!(
                "left:{};top:{};width:{};height:{};font-size:{};line-height:{};--ti:{};--pl:{}",
                units.x(frag.x0),
                units.y(top),
                units.x(width),
                units.len(n as f32 * lead + extra[frag_idx]),
                units.len(size),
                units.len(lead),
                units.len(if centred { 0.0 } else { indent }),
                units.len(if centred { 0.0 } else { (-indent).max(0.0) }),
            );
            if frag_idx == 0 {
                out.push_str(&format!(
                    "<div class=\"fb{}{}\" data-kind=\"{}\" data-block=\"{}\" data-align=\"{align}\" data-parts=\"{}\" style=\"{geometry}\"><div class=\"in\">{inner}</div></div>\n",
                    if frags.len() == 1 { " one" } else { "" },
                    if edited { " rf ed" } else { "" },
                    kind_name(&block.kind),
                    block.id,
                    frags.len(),
                ));
            } else {
                // The same text, shifted up by the lines shown before.
                out.push_str(&format!(
                    "<div class=\"fb cont{}{}\" data-of=\"{}\" data-skip=\"{lines_before}\" data-align=\"{align}\" translate=\"no\" aria-hidden=\"true\" style=\"{geometry}\"><div class=\"in\" style=\"margin-top:-{}\">{inner}</div></div>\n",
                    if frag_idx + 1 == frags.len() { " tail" } else { "" },
                    if edited { " rf" } else { "" },
                    block.id,
                    units.len(lines_before as f32 * lead + extra_before),
                ));
            }
        }
        lines_before += n;
        extra_before += extra[frag_idx];
    }
    out
}

/// Whether the rebuilt `table` can be laid out inside its region: the rows
/// of a table are as tall as the bands found in the PDF, and a band thinner
/// than a line of text would grow and push the table over what lies below.
/// That happens when cells of different columns that are centred on each
/// other were read as rows of their own.
fn table_fits(table: &Table) -> bool {
    let geom = &table.geom;
    let needed = TABLE_MIN_ROW_EM * geom.size;
    let growth: f32 = geom
        .row_bounds
        .windows(2)
        .map(|rows| (needed - (rows[1] - rows[0])).max(0.0))
        .sum();
    growth <= TABLE_MAX_GROWTH_RATIO * geom.bbox.height().max(1.0)
}

/// A reconstructed table laid out on its original grid. The text of an
/// `edited` table wraps inside its cells.
fn table_box(table: &Table, edited: bool, units: &Units) -> String {
    let geom = &table.geom;
    let (box_width, box_height) = (geom.bbox.width().max(1.0), geom.bbox.height().max(1.0));
    let mut out = format!(
        "<div class=\"tb{}\" data-kind=\"table\" style=\"left:{};top:{};width:{};height:{};font-size:{}\"><table><colgroup>",
        if edited { " rf" } else { "" },
        units.x(geom.bbox.x0),
        units.y(geom.bbox.y0),
        units.x(box_width),
        units.y(box_height),
        units.len(geom.size),
    );
    for col in 0..table.n_cols {
        out.push_str(&format!(
            "<col style=\"width:{:.3}%\">",
            (geom.col_bounds[col + 1] - geom.col_bounds[col]) / box_width * 100.0
        ));
    }
    out.push_str("</colgroup>");
    let mut open_row: Option<usize> = None;
    table_walk(table, |row_idx, col, cell| {
        if open_row != Some(row_idx) {
            if open_row.is_some() {
                out.push_str("</tr>");
            }
            out.push_str(&format!(
                "<tr style=\"height:{:.3}%\">",
                (geom.row_bounds[row_idx + 1] - geom.row_bounds[row_idx]) / box_height * 100.0
            ));
            open_row = Some(row_idx);
        }
        let tag = if row_idx < table.header_rows { "th" } else { "td" };
        match cell {
            None => out.push_str(&format!(
                "<{tag} class=\"e{}\"></{tag}>",
                table_rule_classes(table, row_idx, col, 1, 1)
            )),
            Some(cell) => out.push_str(&table_cell(table, units, row_idx, cell, tag)),
        }
    });
    if open_row.is_some() {
        out.push_str("</tr>");
    }
    out.push_str("</table></div>\n");
    out
}

/// A non-empty cell of row `row_idx` of a table laid out on its grid, as a
/// `tag` (`th` or `td`) element. Its padding puts the text where it is in
/// the PDF.
fn table_cell(table: &Table, units: &Units, row_idx: usize, cell: &TableCell, tag: &str) -> String {
    let geom = &table.geom;
    let first_col = cell.col.min(table.n_cols - 1);
    let last_col = (cell.col + cell.colspan).min(table.n_cols) - 1;
    // Put the first line on the baseline it has in the PDF (cells
    // spanning rows are centred instead).
    let top = if cell.rowspan > 1 {
        0.0
    } else {
        (geom.row_baselines[row_idx] - BASELINE * geom.size - geom.row_bounds[row_idx]).max(0.0)
    };
    let (align, pad) = if cell.colspan > 1 {
        ("c", format!(" style=\"padding-top:{}\"", units.len(top)))
    } else {
        // Keep the text inside the band it occupies in the PDF.
        let left = (geom.col_text[first_col].0 - geom.col_bounds[first_col]).max(0.0);
        let right = (geom.col_bounds[last_col + 1] - geom.col_text[last_col].1).max(0.0);
        (
            &table.col_align[first_col][..1],
            format!(
                " style=\"padding:{} {} 0 {}\"",
                units.len(top),
                units.len(right),
                units.len(left)
            ),
        )
    };
    let attrs = span_attrs(cell);
    let (html, _) = spans_h95(&cell.spans, &[]);
    format!(
        "<{tag}{attrs} class=\"{align}{}{}\"{pad}>{html}</{tag}>",
        if cell.rowspan > 1 { " mid" } else { "" },
        table_rule_classes(table, row_idx, cell.col, cell.colspan, cell.rowspan),
    )
}

/// The glyph runs of a displayed formula.
fn equation(block: &Block, units: &Units) -> String {
    let mut out = format!(
        "<div class=\"eq\" data-kind=\"equation\" data-block=\"{}\" translate=\"no\">",
        block.id
    );
    for run in &block.eq_runs {
        let span = Span {
            text: run.text.clone(),
            style: run.style | MATH,
            href: None,
            color: run.color,
            math: None,
            note: None,
        };
        let mut html = span_html(&span, &run.text, &mut [].iter());
        // A tall glyph (a big delimiter, an integral sign) stays in the page
        // picture, exactly as drawn: the text is an unseen copy.
        if run.ink.is_some_and(|ink| ink.height() > TALL_GLYPH_MIN_EM * run.size) {
            html = format!("<span class=\"ph\">{html}</span>");
        }
        let ink = run
            .ink
            .map(|ink| {
                format!(
                    " data-ink=\"{:.3},{:.3},{:.3},{:.3}\"",
                    ink.x0 / units.page_width * 100.0,
                    ink.y0 / units.page_height * 100.0,
                    ink.x1 / units.page_width * 100.0,
                    ink.y1 / units.page_height * 100.0
                )
            })
            .unwrap_or_default();
        out.push_str(&format!(
            "<span class=\"g\" style=\"left:{};top:{};font-size:{}\" data-w=\"{}\"{ink}>{html}</span>",
            units.x(run.x),
            units.y(run.y - BASELINE * run.size),
            units.len(run.size),
            units.width_attr(run.width),
        ));
    }
    out.push_str("</div>\n");
    out
}

/// Adds the origins of the glyphs of `line` that are written as text to the
/// set of glyphs drawn as HTML (glyphs without Unicode value and radicals
/// stay in the picture, and so do tall glyphs when `tall_in_picture`: in
/// text and formulas, not in tables, whose cells write them as text).
fn add_origins(set: &mut HashSet<(i32, i32)>, line: &Line, tall_in_picture: bool) {
    add_glyph_origins(set, line, |glyph| {
        glyph.text.contains(PICTURE_CHARS) || (tall_in_picture && is_tall(glyph))
    });
}

/// Adds the origins of every glyph of `line`, those of [`add_origins`]
/// leaves in the picture included: the text of an edited block.
fn add_all_origins(set: &mut HashSet<(i32, i32)>, line: &Line) {
    add_glyph_origins(set, line, |_| false);
}

/// Adds the origins of the glyphs of `line`, except those `keep` leaves in
/// the picture.
fn add_glyph_origins(set: &mut HashSet<(i32, i32)>, line: &Line, keep: impl Fn(&LineGlyph) -> bool) {
    for glyph in &line.glyphs {
        // Glyphs left in the picture (see `PICTURE_CHARS` and `is_tall`).
        if keep(glyph) {
            continue;
        }
        set.insert(origin_key(glyph.ox, glyph.oy));
        for &(x, y) in &glyph.extra {
            set.insert(origin_key(x, y));
        }
    }
}