kakemono 0.15.0

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
//! Flowing HTML for a sequence of blocks, shared by the medium and friendly modes.

use super::*;
use crate::model::*;
use regex::Regex;
use std::sync::LazyLock;

/// A section number at the start of a heading ("3.2 ", "A.1 ", "IV. "),
/// set apart in the friendly mode so it can hang in the margin.
static SECTION_NUMBER: LazyLock<Regex> =
    LazyLock::new(|| Regex::new(r"^(?:\d+(?:\.\d+)*\.?|[A-Z](?:\.\d+)+\.?|[A-Z]\.|[IVXL]+\.)\s+").unwrap());

/// Smallest scale of an equation or a picture of a table in a narrow column
/// (a phone, a book page): text in it stays readable, and the picture
/// scrolls sideways instead.
const LEGIBLE_MIN_SCALE: f32 = 0.7;
/// Indent of each level of a nested list item, in em.
const HTML_NEST_EM: f32 = 1.5;
/// A picture on the first page that covers at least this fraction of it is
/// the cover of a book.
const COVER_MIN_AREA_RATIO: f32 = 0.8;

/// How image widths are expressed in a given mode.
pub(crate) enum WidthUnit {
    /// Relative to the body font size (`pt_per_em` points per em).
    Em {
        /// Points per em: the body font size of the document.
        pt_per_em: f32,
    },
    /// Like [`WidthUnit::Em`], but every image shrinks to fit its container,
    /// legible or not: an e-reader page cannot scroll sideways.
    EmFit {
        /// Points per em: the body font size of the document.
        pt_per_em: f32,
    },
    /// Relative to the page container width (`page_width` points wide).
    Cqw {
        /// Width of the page in points.
        page_width: f32,
    },
}

impl WidthUnit {
    /// The CSS `width` of an image that is `width_pt` points wide in the
    /// PDF, never wider than its container. A `legible` image (equations,
    /// pictures of tables) shrinks to fit only down to
    /// [`LEGIBLE_MIN_SCALE`] of its size; beyond that its container scrolls.
    fn css(&self, width_pt: f32, legible: bool) -> String {
        match self {
            WidthUnit::Em { pt_per_em } if legible => {
                let width = width_pt / pt_per_em;
                format!(
                    "width:{width:.2}em;max-width:max(100%,{:.2}em)",
                    width * LEGIBLE_MIN_SCALE
                )
            }
            WidthUnit::Em { pt_per_em } | WidthUnit::EmFit { pt_per_em } => {
                format!("width:{:.2}em;max-width:100%", width_pt / pt_per_em)
            }
            WidthUnit::Cqw { page_width } => format!("width:{:.2}cqw;max-width:100%", width_pt / page_width * 100.0),
        }
    }
}

/// What a mode needs to know to write flowing blocks.
pub(crate) struct FlowCtx {
    /// How image widths are expressed.
    pub unit: WidthUnit,
    /// Write the markup of the Offprint design (friendly mode): hanging
    /// section numbers, reference and list labels, figure plates, caption
    /// labels without punctuation, numeric table columns.
    pub offprint: bool,
    /// Ids of the blocks that are the front and the back cover of the book
    /// (see [`cover_blocks`]), whose figures get the `cover` and
    /// `back-cover` classes: the book view sets them as pages of their own.
    pub covers: (Option<usize>, Option<usize>),
    /// Classes of the small pictures set beside the text that follows them
    /// (see [`side_figures`]), by block id.
    pub sides: std::collections::HashMap<usize, &'static str>,
    /// Write the formulas inside running text as MathML (see
    /// [`inline_math`](super::inline_math)); otherwise as styled text.
    pub math: bool,
    /// List the added notes of each block in an aside right after
    /// it; otherwise the mode writes them elsewhere (EPUB: at the end of
    /// the chapter).
    pub note_asides: bool,
}

/// A picture at most this share of its page wide can stand beside text.
const SIDE_MAX_WIDTH_RATIO: f32 = 0.4;
/// The text beside a picture and the picture share at least this share of
/// the height of the lower of the two.
const SIDE_MIN_OVERLAP_RATIO: f32 = 0.5;
/// The text beside a picture may reach this far (points) over its edge.
const SIDE_EDGE_TOLERANCE_PT: f32 = 2.0;

/// The small uncaptioned pictures that stand beside the text block after
/// them in `blocks` (an icon left of a note, a portrait right of a
/// biography), with the class that floats them to their side: `side-l` or
/// `side-r`.
pub(crate) fn side_figures(doc: &Document, blocks: &[&Block]) -> std::collections::HashMap<usize, &'static str> {
    let mut sides = std::collections::HashMap::new();
    for pair in blocks.windows(2) {
        let (fig, text) = (pair[0], pair[1]);
        let BlockKind::Figure {
            image: Some(image),
            label: None,
            ..
        } = &fig.kind
        else {
            continue;
        };
        let textual = matches!(
            text.kind,
            BlockKind::Paragraph { .. } | BlockKind::Note | BlockKind::Heading { .. }
        );
        let Some(page) = doc.pages.get(image.page) else {
            continue;
        };
        if !textual
            || fig.table.is_some()
            || text.page != image.page
            || image.rect.width() > SIDE_MAX_WIDTH_RATIO * page.width
        {
            continue;
        }
        let (rect, other) = (image.rect, text.bbox);
        let overlap = rect.y1.min(other.y1) - rect.y0.max(other.y0);
        if overlap < SIDE_MIN_OVERLAP_RATIO * rect.height().min(other.height()) {
            continue;
        }
        if other.x0 >= rect.x1 - SIDE_EDGE_TOLERANCE_PT {
            sides.insert(fig.id, "side-l");
        } else if other.x1 <= rect.x0 + SIDE_EDGE_TOLERANCE_PT {
            sides.insert(fig.id, "side-r");
        }
    }
    sides
}

/// Whether the caption of a float goes before its picture or table: the
/// side it had in the paper (the first line of the caption above the middle
/// of the picture), or, without page geometry (a Word document), the side
/// the document puts it on.
pub(crate) fn caption_first(block: &Block, image: Option<&ImageSpec>) -> bool {
    match (image, block.lines.first()) {
        (Some(spec), Some(line)) => line.bbox.cy() < spec.rect.cy(),
        _ => block.caption_above,
    }
}

/// The structure a displayed formula is written from: its [`MathNode`]
/// when there is one and `equations` asks for MathML, or when there is no
/// picture of the formula to show instead. `None` means its picture.
pub(crate) fn equation_math<'a>(
    block: &'a Block,
    image: Option<&ImageSpec>,
    equations: Equations,
) -> Option<&'a MathNode> {
    block
        .math
        .as_ref()
        .filter(|_| equations == Equations::MathMl || image.is_none())
}

/// The ids of the blocks that are the front and the back cover of a book:
/// the first figure, when it is a picture on the first page covering most
/// of it (see [`COVER_MIN_AREA_RATIO`]), and the last one, when it is such
/// a picture on the last page. `None` for papers.
pub(crate) fn cover_blocks(doc: &Document) -> (Option<usize>, Option<usize>) {
    let mut figures = doc
        .blocks
        .iter()
        .filter(|block| matches!(block.kind, BlockKind::Figure { .. }));
    let covering = |block: &Block, page_idx: usize| {
        let BlockKind::Figure { image: Some(image), .. } = &block.kind else {
            return false;
        };
        doc.pages.get(page_idx).is_some_and(|page| {
            image.page == page_idx && image.rect.area() >= COVER_MIN_AREA_RATIO * page.width * page.height
        })
    };
    let front = figures.next().filter(|block| covering(block, 0)).map(|block| block.id);
    let last_page = doc.pages.len().saturating_sub(1);
    let back = figures
        .next_back()
        .filter(|block| last_page > 0 && covering(block, last_page))
        .map(|block| block.id);
    (front, back)
}

/// A run of consecutive blocks that share a container element.
#[derive(PartialEq, Clone, Copy)]
enum Group {
    /// No container.
    None,
    /// List items, in a `<ul>`.
    List,
    /// Bibliography entries, in an `<ol>`.
    Refs,
    /// Paragraphs of the abstract, in a `<section>`.
    Abstract,
}

/// The HTML heading tag of a heading level (`h1` is the paper title).
pub(crate) fn heading_tag(level: u8) -> &'static str {
    match level {
        0 | 1 => "h2",
        2 => "h3",
        3 => "h4",
        _ => "h5",
    }
}

/// Renders a sequence of blocks as flowing HTML, grouping list items,
/// references and abstract paragraphs. Pictures are requested from `images`
/// in the order of the blocks.
pub(crate) fn render_flow(blocks: &[&Block], images: &mut ImageStore<'_>, ctx: &FlowCtx) -> String {
    let mut out = String::new();
    let mut group = Group::None;
    let mut block_idx = 0;
    // The notes of headings, held back until the block after them.
    let mut held_notes = String::new();
    while block_idx < blocks.len() {
        let block = blocks[block_idx];
        if ctx.offprint
            && let Some(end) = code_run(blocks, block_idx)
        {
            close_group(group, &mut out);
            group = Group::None;
            let run = &blocks[block_idx..end];
            out.push_str(&code::listing_html(&code::listing_lines(run), "", &id_attr(run[0])));
            block_idx = end;
            continue;
        }
        let want = group_of(block, group);
        if want != group {
            close_group(group, &mut out);
            open_group(want, blocks, block_idx, &mut out);
            group = want;
        }
        // In the friendly mode an equation whose number was read as a
        // paragraph of its own ("(2)") takes that number back.
        if ctx.offprint
            && let BlockKind::Equation { image, number: None } = &block.kind
            && let Some(number) = blocks.get(block_idx + 1).and_then(|next| stray_equation_number(next))
        {
            out.push_str(&equation_html(
                block,
                image.as_ref(),
                &Some(number),
                &id_attr(block),
                images,
                ctx,
            ));
            block_idx += 2;
            continue;
        }
        // A small picture and the text beside it share a box, so that the
        // next pair starts below both.
        if group == Group::None
            && ctx.sides.contains_key(&block.id)
            && let Some(next) = blocks.get(block_idx + 1)
            && group_of(next, group) == Group::None
        {
            out.push_str("<div class=\"beside\">");
            block_with_notes(block, images, ctx, &mut out, &mut held_notes);
            block_with_notes(next, images, ctx, &mut out, &mut held_notes);
            out.push_str("</div>\n");
            block_idx += 2;
            continue;
        }
        block_with_notes(block, images, ctx, &mut out, &mut held_notes);
        block_idx += 1;
    }
    close_group(group, &mut out);
    out.push_str(&held_notes);
    out
}

/// The equation number written as a paragraph of its own: a paragraph whose
/// whole text is a number in parentheses, "(2)" or "(2.1)".
pub(crate) fn stray_equation_number(block: &Block) -> Option<String> {
    if !matches!(block.kind, BlockKind::Paragraph { in_abstract: false }) {
        return None;
    }
    let text = plain(&block.spans);
    let text = text.trim();
    let inner = text.strip_prefix('(')?.strip_suffix(')')?;
    let digits = inner
        .split('.')
        .all(|part| !part.is_empty() && part.len() <= 3 && part.bytes().all(|b| b.is_ascii_digit()));
    digits.then(|| text.to_string())
}

/// The end of the run of code paragraphs starting at `blocks[start]`, when
/// the run has at least two lines (one monospaced line stays inline code)
/// or holds a listing found by the analysis.
pub(crate) fn code_run(blocks: &[&Block], start: usize) -> Option<usize> {
    let end = start
        + blocks[start..]
            .iter()
            .take_while(|block| code::is_code_paragraph(block))
            .count();
    let lines: usize = blocks[start..end].iter().map(|block| block.lines.len()).sum();
    let listing = blocks[start..end]
        .iter()
        .any(|block| matches!(block.kind, BlockKind::Code));
    (lines >= 2 || listing).then_some(end)
}

/// Author groups as cards.
pub(crate) fn authors_html(blocks: &[&Block]) -> String {
    let cards: Vec<String> = blocks
        .iter()
        .filter(|block| matches!(block.kind, BlockKind::Authors))
        .map(|block| {
            let rows: Vec<String> = block
                .rows
                .iter()
                .enumerate()
                .map(|(i, row)| {
                    format!(
                        "<div class=\"{}\">{}</div>",
                        if i == 0 { "au-name" } else { "au-line" },
                        spans_html(row)
                    )
                })
                .collect();
            format!("<div class=\"author\">{}</div>", rows.join(""))
        })
        .collect();
    if cards.is_empty() {
        String::new()
    } else {
        format!("<div class=\"authors\">{}</div>\n", cards.join("\n"))
    }
}

/// The group a block belongs to, given the group that is open (`current`):
/// floats, equations and footnotes do not interrupt an abstract.
fn group_of(block: &Block, current: Group) -> Group {
    match &block.kind {
        BlockKind::ListItem { .. } | BlockKind::ListContinuation => Group::List,
        BlockKind::Reference { .. } => Group::Refs,
        BlockKind::Paragraph { in_abstract: true } => Group::Abstract,
        // Floats, equations and footnotes do not interrupt a group.
        BlockKind::Equation { .. } if current == Group::Abstract => current,
        _ => Group::None,
    }
}

/// Writes the closing tag of a group.
fn close_group(group: Group, out: &mut String) {
    match group {
        Group::List => out.push_str("</ul>\n"),
        Group::Refs => out.push_str("</ol>\n"),
        Group::Abstract => out.push_str("</section>\n"),
        Group::None => {}
    }
}

/// Writes the opening tag of a group that starts at `blocks[block_idx]`. An
/// abstract gets an "Abstract" label unless the block before it is a heading
/// saying so.
fn open_group(group: Group, blocks: &[&Block], block_idx: usize, out: &mut String) {
    match group {
        Group::List => out.push_str("<ul class=\"list\">\n"),
        Group::Refs => out.push_str("<ol class=\"refs\">\n"),
        Group::Abstract => {
            // The "Abstract" heading (if any) was emitted just before.
            let had_heading = block_idx > 0
                && matches!(blocks[block_idx - 1].kind, BlockKind::Heading { .. })
                && is_abstract_text(&blocks[block_idx - 1].spans);
            out.push_str("<section class=\"abstract\">\n");
            if !had_heading {
                out.push_str("<div class=\"abstract-label\">Abstract</div>\n");
            }
        }
        Group::None => {}
    }
}

/// Whether the text of `spans` is the word "Abstract" (any case, with an
/// optional final `.` or `:`).
pub(crate) fn is_abstract_text(spans: &[Span]) -> bool {
    plain(spans)
        .trim_end_matches(['.', ':'])
        .eq_ignore_ascii_case("abstract")
}

/// Whether `spans` are a scene break of a novel: a paragraph of only
/// "#", "*" or "⁂" marks ("#", "* * *"), centred in the book.
pub(crate) fn is_scene_break(spans: &[Span]) -> bool {
    let text = plain(spans);
    let marks: Vec<char> = text.chars().filter(|ch| !ch.is_whitespace()).collect();
    !marks.is_empty() && marks.len() <= 5 && marks.iter().all(|ch| matches!(ch, '#' | '*' | '\u{2042}'))
}

/// Writes one block, like [`block_html`], followed by the aside of its
/// added notes when the mode wants one there: inside the item for a
/// list item or a reference, after the block otherwise. The notes of a
/// heading are added to `held` instead, and come after the next block that
/// is not a heading (a heading stays with its text).
fn block_with_notes(block: &Block, images: &mut ImageStore<'_>, ctx: &FlowCtx, out: &mut String, held: &mut String) {
    let start = out.len();
    block_html(block, images, ctx, out);
    if !ctx.note_asides {
        return;
    }
    held.push_str(&super::notes::aside_html(&[block], ctx.math));
    if matches!(block.kind, BlockKind::Heading { .. }) || held.is_empty() {
        return;
    }
    let aside = std::mem::take(held);
    match out[start..].strip_suffix("</li>\n") {
        Some(item) => {
            let end = start + item.len();
            out.insert_str(end, aside.trim_end());
        }
        None => out.push_str(&aside),
    }
}

/// Writes one block. Titles and author blocks are written by the modes
/// themselves and are skipped here.
fn block_html(block: &Block, images: &mut ImageStore<'_>, ctx: &FlowCtx, out: &mut String) {
    let id = id_attr(block);
    match &block.kind {
        BlockKind::Title | BlockKind::Authors => {}
        BlockKind::Note => out.push_str(&format!(
            "<p class=\"note\">{}</p>\n",
            text_html(&block.spans, ctx.math)
        )),
        BlockKind::Heading { level } => {
            let tag = heading_tag(*level);
            let cls = if is_abstract_text(&block.spans) {
                " class=\"abstract-heading\""
            } else {
                ""
            };
            if let Some((label, rest)) = chapter_label(&block.spans).filter(|_| cls.is_empty()) {
                out.push_str(&format!(
                    "<{tag}{id} class=\"chapter\"><span class=\"chapno\">{}</span> {}</{tag}>\n",
                    esc(&label),
                    text_html(&rest, ctx.math)
                ));
                return;
            }
            match section_number(&block.spans).filter(|_| ctx.offprint && cls.is_empty()) {
                Some((number, rest)) => out.push_str(&format!(
                    "<{tag}{id} class=\"hang\"><span class=\"secno\">{}</span>{}</{tag}>\n",
                    esc(&number),
                    text_html(&rest, ctx.math)
                )),
                None => out.push_str(&format!(
                    "<{tag}{id}{cls}>{}</{tag}>\n",
                    text_html(&block.spans, ctx.math)
                )),
            }
        }
        BlockKind::Paragraph { .. } if is_scene_break(&block.spans) => {
            out.push_str(&format!(
                "<p{id} class=\"scene-break\">{}</p>\n",
                spans_html(&block.spans)
            ));
        }
        BlockKind::Paragraph { .. } => out.push_str(&format!("<p{id}>{}</p>\n", text_html(&block.spans, ctx.math))),
        BlockKind::ListItem { marker, level } => {
            let cls = if marker.is_some() { " class=\"labeled\"" } else { "" };
            // A nested item is indented by one step per level.
            let nest = if *level > 0 {
                format!(" style=\"margin-left:{}em\"", f32::from(*level) * HTML_NEST_EM)
            } else {
                String::new()
            };
            let body = match marker.as_deref().filter(|_| ctx.offprint) {
                Some(marker) => labelled_html(&block.spans, marker, "lbl", ctx.math),
                None => text_html(&block.spans, ctx.math),
            };
            out.push_str(&format!("<li{id}{cls}{nest}>{body}</li>\n"));
        }
        BlockKind::ListContinuation => out.push_str(&format!(
            "<li{id} class=\"more\">{}</li>\n",
            text_html(&block.spans, ctx.math)
        )),
        BlockKind::Reference { label } => {
            let body = match label.as_deref().filter(|_| ctx.offprint) {
                Some(label) => reference_html(&block.spans, label, ctx.math),
                None => text_html(&block.spans, ctx.math),
            };
            out.push_str(&format!("<li{id}>{body}</li>\n"));
        }
        BlockKind::Footnote { marker } => out.push_str(&footnote_html(block, marker, &id, ctx)),
        BlockKind::Equation { image, number } => {
            out.push_str(&equation_html(block, image.as_ref(), number, &id, images, ctx))
        }
        BlockKind::Figure { kind, image, label } => {
            out.push_str(&figure_html(block, *kind, image, label, &id, images, ctx));
        }
        BlockKind::Code => out.push_str(&code_html(block, &id)),
        BlockKind::ContentsEntry { level, page } => out.push_str(&format!(
            "<p{id} class=\"toc toc{level}\"><span class=\"toc-t\">{}</span><span class=\"toc-p\">{}</span></p>\n",
            spans_html(&block.spans),
            esc(page)
        )),
    }
}

/// A code listing: its rows in a `pre` element, with their indentation.
/// The rows are monospaced as a whole, so their spans keep only bold and
/// italic.
fn code_html(block: &Block, id: &str) -> String {
    let rows: Vec<String> = block
        .rows
        .iter()
        .map(|row| {
            let spans: Vec<Span> = row
                .iter()
                .map(|span| Span {
                    style: span.style & !style::MONO,
                    ..span.clone()
                })
                .collect();
            spans_html(&spans)
        })
        .collect();
    format!("<pre class=\"code\"{id}><code>{}</code></pre>\n", rows.join("\n"))
}

/// A footnote, with its marker (if any) as a superscript (in the friendly
/// mode, as a rubric label).
fn footnote_html(block: &Block, marker: &str, id: &str, ctx: &FlowCtx) -> String {
    let mark = if marker.is_empty() {
        String::new()
    } else if ctx.offprint {
        format!("<span class=\"fn-mark\">{}</span>", esc(marker))
    } else {
        format!("<sup class=\"fn-mark\">{}</sup> ", esc(marker))
    };
    format!(
        "<aside class=\"footnote\"{id} role=\"note\">{mark}{}</aside>\n",
        text_html(&block.spans, ctx.math)
    )
}

/// A displayed equation: its picture, with the text as alt text, and its
/// number.
fn equation_html(
    block: &Block,
    image: Option<&ImageSpec>,
    number: &Option<String>,
    id: &str,
    images: &mut ImageStore<'_>,
    ctx: &FlowCtx,
) -> String {
    let num = number
        .as_ref()
        .map(|number| format!("<span class=\"eqno\">{}</span>", esc(number)))
        .unwrap_or_default();
    if let Some(math) = equation_math(block, image, images.opts.equations) {
        let body = math_html(math, &plain(&block.spans));
        return format!("<div class=\"eq\"{id}><span class=\"eq-body\">{body}</span>{num}</div>\n");
    }
    let alt = esc(&plain(&block.spans));
    let Some(image) = image else {
        return format!("<div class=\"eq\"{id}><span class=\"eq-body\">{alt}</span>{num}</div>\n");
    };
    let img = format!(
        "<img src=\"{}\" alt=\"{alt}\"{} style=\"{}\" loading=\"lazy\">",
        images.region(image, "eq"),
        images.region_size_attrs(image),
        ctx.unit.css(image.rect.width(), true)
    );
    format!("<div class=\"eq\"{id}><span class=\"eq-body\">{img}</span>{num}</div>\n")
}

/// A float: its picture, or the reconstructed table instead of the picture
/// of a table, and its caption on the side it had in the paper.
fn figure_html(
    block: &Block,
    kind: FloatKind,
    image: &Option<ImageSpec>,
    label: &Option<String>,
    id: &str,
    images: &mut ImageStore<'_>,
    ctx: &FlowCtx,
) -> String {
    let cls = float_class(kind);
    let cover = if ctx.covers.0 == Some(block.id) {
        " cover"
    } else if ctx.covers.1 == Some(block.id) {
        " back-cover"
    } else {
        match ctx.sides.get(&block.id) {
            Some(&"side-l") => " side-l",
            Some(_) => " side-r",
            None => "",
        }
    };
    // A float whose text is all code is a listing.
    if ctx.offprint
        && kind == FloatKind::Algorithm
        && block.table.is_none()
        && let Some(lines) = code::float_listing_lines(block)
    {
        return code::listing_html(&lines, &caption_html_bare(&block.spans, ctx.math), id);
    }
    let alt = esc(&figure_alt(block, label));
    // An algorithm whose text reads as pseudocode is rebuilt as text.
    let algo = (ctx.offprint && kind == FloatKind::Algorithm && block.table.is_none())
        .then(|| code::algorithm_html(block))
        .flatten();
    let img = image
        .as_ref()
        .filter(|_| block.table.is_none() && algo.is_none())
        .map(|spec| (images.region(spec, cls), images.region_size_attrs(spec), spec))
        .map(|(src, size, spec)| {
            // The medium mode shows figures at their own pixel width on
            // phones (`--w`), known before the picture loads.
            let own = if ctx.offprint {
                String::new()
            } else {
                format!(";--w:{}px", images.region_size(spec).0)
            };
            let legible = matches!(kind, FloatKind::Table | FloatKind::Algorithm);
            format!(
                "<img src=\"{src}\" alt=\"{alt}\"{size} style=\"{}{own}\" loading=\"lazy\">",
                ctx.unit.css(spec.rect.width(), legible)
            )
        })
        .map(|img| match kind {
            FloatKind::Figure | FloatKind::Graphic if ctx.offprint => format!("<div class=\"plate\">{img}</div>"),
            // A picture of a table scrolls like a rebuilt table when the
            // column is too narrow for it.
            FloatKind::Table | FloatKind::Algorithm if ctx.offprint => format!("<div class=\"tbl-wrap\">{img}</div>"),
            _ => img,
        })
        .unwrap_or_default();
    // A reconstructed table replaces the picture of the table.
    let img = match (&block.table, algo) {
        (_, Some(algo)) => algo,
        (Some(table), _) if ctx.offprint => {
            format!("<div class=\"tbl-wrap\">{}</div>", table_html_numeric(table, ctx.math))
        }
        (Some(table), _) => format!("<div class=\"tbl-wrap\">{}</div>", table_html(table, ctx.math)),
        (None, None) => img,
    };
    let cap = if block.spans.is_empty() {
        String::new()
    } else if ctx.offprint {
        format!("<figcaption>{}</figcaption>", caption_html_bare(&block.spans, ctx.math))
    } else {
        format!("<figcaption>{}</figcaption>", caption_html(&block.spans, ctx.math))
    };
    // Keep the caption on the side it had in the paper.
    let caption_first = img.starts_with("<div class=\"algo\"") || caption_first(block, image.as_ref());
    let inner = if caption_first {
        format!("{cap}{img}")
    } else {
        format!("{img}{cap}")
    };
    format!("<figure class=\"float {cls}{cover}\"{id}>{inner}</figure>\n")
}

/// The section number at the start of a heading and the rest of its spans,
/// or `None` when the heading has no number.
fn section_number(spans: &[Span]) -> Option<(String, Vec<Span>)> {
    let first = spans.first()?;
    let found = SECTION_NUMBER.find(&first.text)?;
    if found.end() == first.text.len() && spans.len() == 1 {
        return None;
    }
    let mut rest = spans.to_vec();
    rest[0].text = first.text[found.end()..].to_string();
    Some((found.as_str().trim_end().to_string(), rest))
}

/// A heading that starts with a chapter label ("Chapter 1 The way of the
/// program"): the label and the rest of the heading.
fn chapter_label(spans: &[Span]) -> Option<(String, Vec<Span>)> {
    let first = spans.first()?;
    let found = crate::analysis::semantics::patterns::CHAPTER_LABEL.find(&first.text)?;
    let mut rest = spans.to_vec();
    rest[0].text = first.text[found.end()..].trim_start().to_string();
    let has_rest = rest.iter().any(|span| !span.text.trim().is_empty());
    has_rest.then(|| (found.as_str().trim_end().to_string(), rest))
}

/// A list item whose text starts with its `marker` ("(1)", "a."): the
/// marker in a `<span class="{class}">`, then the rest of the text.
/// Without the marker at the start, the plain text. Inline formulas are
/// MathML when `math`.
fn labelled_html(spans: &[Span], marker: &str, class: &str, math: bool) -> String {
    match spans.first() {
        Some(first) if !marker.is_empty() && first.text.starts_with(marker) => {
            let mut rest = spans.to_vec();
            rest[0].text = first.text[marker.len()..].trim_start().to_string();
            format!(
                "<span class=\"{class}\">{}</span>{}",
                esc(marker),
                text_html(&rest, math)
            )
        }
        _ => text_html(spans, math),
    }
}

/// A bibliography entry with its label ("[12]" or "12.") set apart in a
/// `<span class="rn">`. Inline formulas are MathML when `math`.
fn reference_html(spans: &[Span], label: &str, math: bool) -> String {
    let Some(first) = spans.first() else {
        return String::new();
    };
    let text = first.text.as_str();
    for printed in [format!("[{label}]"), format!("{label}."), label.to_string()] {
        if let Some(rest) = text.strip_prefix(printed.as_str()) {
            let mut rest_spans = spans.to_vec();
            rest_spans[0].text = rest.trim_start().to_string();
            return format!(
                "<span class=\"rn\">{}</span>{}",
                esc(&printed),
                text_html(&rest_spans, math)
            );
        }
    }
    text_html(spans, math)
}