kakemono 0.22.0

Convert PDF, Word and EPUB documents and web pages to HTML, Markdown, EPUB, LaTeX and JSON in Rust
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
//! Assembling the final [`Document`] from the classified nodes.
//!
//! Every node becomes one output [`Block`] with its styled text and a
//! unique anchor where it can be referenced (headings, references,
//! footnotes, equations, floats). Once all blocks exist, cross-references
//! and footnote marks in the running text are linked to those anchors.

use super::links::*;
use super::patterns::*;
use super::text::*;
use super::*;
use crate::analysis::blocks::LIST_LABEL;
use crate::analysis::lines::split_at_gaps;
use crate::analysis::page::{DocStats, PageData};
use crate::analysis::tables::extract_grid;
use crate::backend::FontInfo;
use crate::common::geom::Rect;
use crate::config::AnalyzeOptions;
use crate::model::FloatKind;
use crate::model::Line;
use crate::model::Loc;
use crate::model::*;
use std::collections::{HashMap, HashSet};

/// Value of [`LineGlyph::script`] for a superscript glyph.
const SUPERSCRIPT: i8 = 1;

/// Tuning parameters of document assembly. Part of [`SemanticsConfig`].
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AssembleConfig {
    /// Author lines whose baselines differ by less than this (points) are
    /// output as one row, their pieces separated by an em space.
    pub author_row_baseline_tolerance_pt: f32,
    /// Margin (points) added around an equation's box for its image, so
    /// that the ink of the glyphs is not clipped.
    pub equation_margin_pt: f32,
    /// Lines inside a table are split at gaps wider than this (multiple of
    /// the font size) before the grid is reconstructed: cells can be closer
    /// together than the gap at which lines are broken.
    pub table_cell_gap_em: f32,
    /// A superscript after a word of fewer letters than this is an exponent
    /// (x², c²), not a footnote mark.
    pub mark_min_word_letters_count: usize,
    /// A footnote mark links to a note at most this many pages before it ...
    pub note_max_pages_before: usize,
    /// ... or this many pages after it.
    pub note_max_pages_after: usize,
    /// A repeated label (the second "[1]", "Section 1", ...) starts a new set
    /// of numbering, as in a report followed by a system card, only when at
    /// least this many anchors of that kind repeat; fewer are stray duplicates.
    pub min_target_set_count: usize,
    /// A picture on the first or last page of a book covering at least this
    /// share of the page is its cover: it is shown whole, title included,
    /// rather than cut off just under the title set over it.
    pub cover_min_area_ratio: f32,
    /// A cover page has at most this many lines of text (title, authors,
    /// publisher).
    pub cover_max_lines_count: usize,
}

impl Default for AssembleConfig {
    fn default() -> Self {
        Self {
            author_row_baseline_tolerance_pt: 2.0,
            equation_margin_pt: 2.5,
            table_cell_gap_em: 0.55,
            mark_min_word_letters_count: 2,
            note_max_pages_before: 1,
            note_max_pages_after: 2,
            min_target_set_count: 2,
            cover_min_area_ratio: 0.6,
            cover_max_lines_count: 12,
        }
    }
}

/// The blocks being built, with the state shared between them.
struct Assembler<'a> {
    /// Builds the styled text.
    text: &'a TextBuilder<'a>,
    /// The pages, for clipping equation images.
    pages: &'a [PageData],
    /// Analysis options (table reconstruction and its thresholds).
    opts: &'a AnalyzeOptions,
    /// Thresholds of the assembly.
    cfg: &'a AssembleConfig,
    /// The blocks built so far; a block's id is its index.
    blocks: Vec<Block>,
    /// Every anchor given out so far.
    anchors: HashSet<String>,
    /// Lines outside every block, per page (running heads, equation numbers).
    loose: Vec<Vec<PLine>>,
    /// Text of each title block.
    title_parts: Vec<String>,
    /// Number of unnumbered equations so far, for their anchors.
    eq_counter: usize,
}

/// What a text node contributes to its block besides its lines.
struct TextContent {
    /// Kind of the output block.
    kind: BlockKind,
    /// Styled text.
    built: Built,
    /// Row-wise text (authors only).
    rows: Vec<Vec<Span>>,
    /// Anchor of the block, if it can be referenced.
    anchor: Option<String>,
}

/// Builds the document from the classified nodes, in their order.
///
/// `furniture` holds the running heads and page numbers removed from each
/// page; they are returned, with the equation numbers, as the loose lines
/// of each page (second element of the result). The document title is
/// taken from the title blocks when there are any.
pub(crate) fn build_document(
    nodes: Vec<Node>,
    pages: &[PageData],
    stats: &DocStats,
    fonts: &[FontInfo],
    mut meta: Meta,
    furniture: Vec<Vec<Line>>,
    opts: AnalyzeOptions,
) -> (Document, Vec<Vec<PLine>>) {
    let vocab = build_vocab(nodes.iter().filter_map(|node| match &node.kind {
        NodeKind::Text(block) | NodeKind::Footnote(block) => Some(block.lines.as_slice()),
        NodeKind::Float(float) => Some(float.caption.as_slice()),
        _ => None,
    }));
    let text = TextBuilder {
        fonts,
        vocab: &vocab,
        cfg: &opts.layout.semantics.text,
    };
    let mut assembler = Assembler {
        text: &text,
        pages,
        opts: &opts,
        cfg: &opts.layout.semantics.assemble,
        blocks: Vec::new(),
        anchors: HashSet::new(),
        loose: furniture_lines(furniture, pages.len(), &text),
        title_parts: Vec::new(),
        eq_counter: 0,
    };
    for node in nodes {
        assembler.push_node(node);
    }
    let Assembler {
        mut blocks,
        loose,
        title_parts,
        cfg,
        ..
    } = assembler;
    link_blocks(&mut blocks, cfg);
    link_contents(&mut blocks);

    if !title_parts.is_empty() {
        meta.title = Some(title_parts.join(" ").split_whitespace().collect::<Vec<_>>().join(" "));
    }
    let doc = Document {
        meta,
        pages: pages
            .iter()
            .map(|page| PageInfo {
                width: page.width,
                height: page.height,
            })
            .collect(),
        body_size: stats.body_size,
        leading: stats.leading,
        body_font: fonts
            .get(stats.body_font as usize)
            .map(|font| font.name.clone())
            .unwrap_or_default(),
        // Set by the pipeline, which counts the math glyphs of each page
        // before it drops its lines (see `count_math_glyphs`).
        math_font: String::new(),
        pictures: Vec::new(),
        blocks,
    };
    (doc, loose)
}

/// Adds the glyphs of `lines` that are in a math font to `counts` (glyphs
/// per font index), for [`main_math_font`].
pub(crate) fn count_math_glyphs(counts: &mut HashMap<u16, usize>, lines: &[Line], fonts: &[FontInfo]) {
    for glyph in lines.iter().flat_map(|line| &line.glyphs) {
        if fonts.get(glyph.font as usize).is_some_and(|font| font.math) {
            *counts.entry(glyph.font).or_default() += 1;
        }
    }
}

/// PostScript name of the math font with the most glyphs in `counts` (see
/// [`count_math_glyphs`]), or an empty string when no glyph is in a math
/// font.
pub(crate) fn main_math_font(counts: &HashMap<u16, usize>, fonts: &[FontInfo]) -> String {
    counts
        .iter()
        .map(|(&font, &count)| (font, count))
        .max_by_key(|&(font, count)| (count, std::cmp::Reverse(font)))
        .and_then(|(font, _)| fonts.get(font as usize))
        .map(|font| font.name.clone())
        .unwrap_or_default()
}

/// Whether a glyph's text is one of the symbols used as footnote marks
/// (asterisks, daggers, section and pilcrow signs).
pub(crate) fn is_footnote_symbol(text: &str) -> bool {
    matches!(text, "∗" | "†" | "‡" | "§" | "" | "*")
}

impl Assembler<'_> {
    /// Builds the block of one node and appends it.
    fn push_node(&mut self, node: Node) {
        let id = self.blocks.len();
        let loc = node.loc;
        let block = match node.kind {
            NodeKind::Text(text_block) => {
                let bbox = lines_bbox(&text_block.lines);
                let content = self.text_content(node.class, &text_block.lines, node.strip_prefix);
                let mut block = block_with_text(id, content.kind, loc, bbox, content.built);
                block.rows = content.rows;
                block.anchor = content.anchor;
                block.lines = text_block.lines;
                block
            }
            NodeKind::Footnote(text_block) => self.footnote_block(id, loc, text_block),
            NodeKind::Equation(equation) => self.equation_block(id, loc, equation),
            NodeKind::Float(float) => self.float_block(id, loc, float),
        };
        self.blocks.push(block);
    }

    /// Returns `base` if it is still free, else the first free `base-2`,
    /// `base-3`, …, and reserves it.
    fn unique_anchor(&mut self, base: String) -> String {
        unique_anchor(&mut self.anchors, base)
    }

    /// Kind, text and anchor of a text node of class `class`.
    /// `strip_prefix` characters (an inline label) are dropped from the
    /// text of paragraphs.
    fn text_content(&mut self, class: Class, lines: &[Line], strip_prefix: usize) -> TextContent {
        let mut rows = Vec::new();
        let mut anchor = None;
        let (kind, built) = match class {
            Class::Title => {
                let built = self.text.build(lines, 0, BOLD);
                self.title_parts.push(spans_text(&built.spans));
                (BlockKind::Title, built)
            }
            Class::Authors => {
                rows = self.author_rows(lines);
                (BlockKind::Authors, self.text.build(lines, 0, 0))
            }
            Class::Note => (BlockKind::Note, self.text.build(lines, 0, 0)),
            Class::Heading { level, number } => {
                let built = self.text.build(lines, 0, BOLD);
                let base = match &number {
                    Some(num) => format!("sec-{num}"),
                    None => format!("sec-{}", slug(&spans_text(&built.spans))),
                };
                anchor = Some(self.unique_anchor(base));
                (BlockKind::Heading { level }, built)
            }
            Class::ListItem { bullet } => {
                let built = self.text.build(lines, if bullet { 1 } else { 0 }, 0);
                let marker = if bullet {
                    None
                } else {
                    let text = spans_text(&built.spans);
                    LIST_LABEL.find(&text).map(|label| label.as_str().trim().to_string())
                };
                (BlockKind::ListItem { marker, level: 0 }, built)
            }
            Class::ListContinuation => (BlockKind::ListContinuation, self.text.build(lines, 0, 0)),
            Class::Reference => {
                let built = self.text.build(lines, 0, 0);
                let label = reference_label(&spans_text(&built.spans));
                if let Some(label) = &label {
                    anchor = Some(self.unique_anchor(format!("ref-{}", slug(label))));
                }
                (BlockKind::Reference { label }, built)
            }
            Class::Paragraph { in_abstract } => {
                let mut built = self.text.build(lines, 0, 0);
                if strip_prefix > 0 {
                    strip_chars(&mut built.spans, strip_prefix);
                }
                (BlockKind::Paragraph { in_abstract }, built)
            }
            Class::Code => {
                // The lines keep their breaks and indentation; the hard
                // renderers still use the lines as built.
                let mut built = self.text.build(lines, 0, 0);
                rows = super::code::code_rows(lines, self.text.fonts);
                built.spans = rows.join(&Span::plain("\n"));
                (BlockKind::Code, built)
            }
            Class::ContentsEntry { level, page } => {
                let mut built = self.text.build(lines, 0, 0);
                super::contents::strip_page_label(&mut built.spans, &page);
                (BlockKind::ContentsEntry { level, page }, built)
            }
            Class::Unknown => (
                BlockKind::Paragraph { in_abstract: false },
                self.text.build(lines, 0, 0),
            ),
        };
        TextContent {
            kind,
            built,
            rows,
            anchor,
        }
    }

    /// Rows of an author card: one per baseline; side-by-side pieces are
    /// separated by an em space.
    fn author_rows(&self, lines: &[Line]) -> Vec<Vec<Span>> {
        let mut rows: Vec<Vec<Span>> = Vec::new();
        let mut last_baseline = f32::NEG_INFINITY;
        for line in lines {
            let mut spans = self.text.line_spans(line);
            if (line.baseline - last_baseline).abs() < self.cfg.author_row_baseline_tolerance_pt && !rows.is_empty() {
                let row: &mut Vec<Span> = rows.last_mut().unwrap();
                row.push(Span::plain("\u{2003}"));
                row.append(&mut spans);
            } else {
                rows.push(spans);
            }
            last_baseline = line.baseline;
        }
        rows
    }

    /// The block of a footnote. Its mark (leading superscript glyphs, a
    /// leading footnote symbol, or a number followed by a period) is taken
    /// out of the text into the block kind and gives the anchor. A leading
    /// bullet is dropped.
    fn footnote_block(&mut self, id: usize, loc: Loc, text_block: TextBlock) -> Block {
        let bbox = lines_bbox(&text_block.lines);
        let first = &text_block.lines[0];
        let mut skip = first
            .glyphs
            .iter()
            .take_while(|glyph| glyph.script == SUPERSCRIPT)
            .count();
        if skip == 0
            && first
                .glyphs
                .first()
                .is_some_and(|glyph| is_footnote_symbol(&glyph.text))
        {
            skip = 1;
        }
        // A number on the baseline followed by a period ("1. Since ..."):
        // the number is the mark, the period goes with it.
        let mut dropped = 0;
        if skip == 0 {
            let digits = first
                .glyphs
                .iter()
                .take_while(|glyph| glyph.text.chars().all(|ch| ch.is_ascii_digit()) && !glyph.text.is_empty())
                .count();
            if digits > 0 && first.glyphs.get(digits).is_some_and(|glyph| glyph.text == ".") {
                skip = digits;
                dropped = 1;
            }
        }
        // A bullet ("• S. Ren is with ...", affiliations set as footnotes) is
        // no mark: it is dropped and the note has none.
        if skip == 0
            && first
                .glyphs
                .first()
                .is_some_and(|glyph| matches!(glyph.text.as_str(), "•" | "▪"))
        {
            dropped = 1;
        }
        let marker: String = first.glyphs[..skip].iter().map(|glyph| glyph.text.as_str()).collect();
        let built = self.text.build(&text_block.lines, skip + dropped, 0);
        let anchor = (!marker.is_empty()).then(|| self.unique_anchor(format!("fn-{}", slug_marker(&marker))));
        let mut block = block_with_text(id, BlockKind::Footnote { marker }, loc, bbox, built);
        block.anchor = anchor;
        block.lines = text_block.lines;
        block
    }

    /// The block of a displayed formula: an image of its area, its text as
    /// alt text and positioned glyph runs. Numbered equations are anchored
    /// by their number, the others by a running count; the equation number
    /// becomes a loose line of the page.
    fn equation_block(&mut self, id: usize, loc: Loc, equation: EquationBlock) -> Block {
        let mut lines = equation.lines;
        lines.sort_by(|a, b| a.baseline.total_cmp(&b.baseline).then(a.bbox.x0.total_cmp(&b.bbox.x0)));
        // As read, with inline fractions as "1/2".
        let read = |line: &Line| {
            if line.glyphs.iter().any(LineGlyph::is_fraction_term) {
                self.text
                    .line_spans(line)
                    .iter()
                    .map(|span| span.text.as_str())
                    .collect::<String>()
            } else {
                line.text()
            }
        };
        let alt = lines.iter().map(read).collect::<Vec<_>>().join(" ");
        let margin = self.cfg.equation_margin_pt;
        let rect = equation
            .bbox
            .inflate(margin, margin)
            .intersect(&self.pages[loc.page].rect());
        let anchor = match &equation.number {
            Some(num) => Some(self.unique_anchor(format!("eq-{}", num.trim_matches(['(', ')'])))),
            None => {
                self.eq_counter += 1;
                Some(self.unique_anchor(format!("eq-u{}", self.eq_counter)))
            }
        };
        if let Some(line) = equation.number_line {
            let spans = self.text.line_spans(&line);
            self.loose[loc.page].push(PLine {
                line,
                spans,
                kind: "eqno",
            });
        }
        let image = ImageSpec::region(loc.page, rect, true);
        let kind = BlockKind::Equation {
            image: Some(image),
            number: equation.number,
        };
        let mut block = new_block(id, kind, loc, rect);
        block.spans = vec![Span::plain(alt)];
        block.line_texts = lines.iter().map(|line| line.text()).collect();
        block.eq_runs = self.text.eq_runs(&lines);
        block.anchor = anchor;
        block.lines = lines;
        block
    }

    /// The region of a picture of page `page`: the whole page when the
    /// picture is a book's cover (see
    /// [`AssembleConfig::cover_min_area_ratio`]), else `rect` itself.
    fn cover_region(&self, page: usize, rect: Rect) -> Rect {
        let Some(data) = self.pages.get(page) else { return rect };
        let edge = page == 0 || page + 1 == self.pages.len();
        let page_rect = Rect::new(0.0, 0.0, data.width, data.height);
        if edge
            && self.pages.len() > 1
            && data.line_count() <= self.cfg.cover_max_lines_count
            && rect.area() >= self.cfg.cover_min_area_ratio * page_rect.area()
        {
            page_rect
        } else {
            rect
        }
    }

    /// The block of a figure, table or algorithm: its caption as text, an
    /// image of its region, the text inside it and, for simple tables (when
    /// enabled), the reconstructed table. Labelled floats are anchored by
    /// their number.
    fn float_block(&mut self, id: usize, loc: Loc, float: Float) -> Block {
        let built = self.text.build(&float.caption, 0, 0);
        let anchor = float.label.as_ref().map(|label| {
            let num = label.rsplit(' ').next().unwrap_or("");
            let prefix = match float.kind {
                FloatKind::Table => "tab",
                FloatKind::Algorithm => "alg",
                _ => "fig",
            };
            self.unique_anchor(format!("{prefix}-{num}"))
        });
        let mut rows = Vec::new();
        if !float.inner_text.is_empty() {
            rows.push(vec![Span::plain(float.inner_text.clone())]);
        }
        let table = self.float_table(&float);
        let region = float.region.map(|rect| self.cover_region(float.page, rect));
        let kind = BlockKind::Figure {
            kind: float.kind,
            image: region.map(|rect| ImageSpec::region(float.page, rect, false)),
            label: float.label.clone(),
        };
        let mut block = block_with_text(id, kind, loc, float.bbox, built);
        block.rows = rows;
        block.anchor = anchor;
        block.lines = float.caption;
        block.inner_spans = float
            .inner_lines
            .iter()
            .map(|line| self.text.line_spans(line))
            .collect();
        block.inner_lines = float.inner_lines;
        block.table = table;
        block
    }

    /// The reconstructed grid of a tabular float, if table reconstruction is
    /// enabled, the float has a region, looks tabular and holds no images;
    /// `None` also when no grid is found.
    fn float_table(&self, float: &Float) -> Option<Table> {
        let tabular = float.kind == FloatKind::Table || (float.kind == FloatKind::Graphic && float.table_like);
        match float.region {
            Some(region) if self.opts.tables && tabular && !float.complex => {
                // Cells can be closer together than the gap at which
                // lines are broken; split more finely. Pieces that
                // end up in the same column are joined again.
                let pieces: Vec<Line> = float
                    .inner_lines
                    .iter()
                    .flat_map(|line| {
                        split_at_gaps(line, self.cfg.table_cell_gap_em * line.size, &self.opts.layout.lines)
                    })
                    .collect();
                extract_grid(
                    region,
                    &pieces,
                    &float.hrules,
                    &float.vrules,
                    &self.opts.layout.tables,
                    &self.opts.layout.lines,
                )
                .map(|grid| self.text.table(grid))
            }
            _ => None,
        }
    }
}

/// The removed running heads and page numbers as loose lines, one list per
/// page (`n_pages` lists).
fn furniture_lines(furniture: Vec<Vec<Line>>, n_pages: usize, text: &TextBuilder<'_>) -> Vec<Vec<PLine>> {
    let mut loose: Vec<Vec<PLine>> = vec![Vec::new(); n_pages];
    for (page_idx, lines) in furniture.into_iter().enumerate() {
        for line in lines {
            let spans = text.line_spans(&line);
            loose[page_idx].push(PLine {
                line,
                spans,
                kind: "header",
            });
        }
    }
    loose
}

/// An empty block of the given kind, place and box; the caller fills in the
/// content.
fn new_block(id: usize, kind: BlockKind, loc: Loc, bbox: Rect) -> Block {
    Block {
        page: loc.page,
        bbox,
        loc,
        ..Block::new(id, kind)
    }
}

/// A block with the styled text `built`.
fn block_with_text(id: usize, kind: BlockKind, loc: Loc, bbox: Rect, built: Built) -> Block {
    let mut block = new_block(id, kind, loc, bbox);
    block.spans = built.spans;
    block.line_texts = built.line_texts;
    block.hlines = built.hlines;
    block
}

/// Union of the boxes of the lines.
fn lines_bbox(lines: &[Line]) -> Rect {
    lines.iter().fold(Rect::EMPTY, |bbox, line| bbox.union(&line.bbox))
}

/// Concatenated text of spans.
fn spans_text(spans: &[Span]) -> String {
    spans.iter().map(|span| span.text.as_str()).collect()
}

/// The label of a reference entry ("12" of `[12]` or "12."), if it has one.
pub(crate) fn reference_label(text: &str) -> Option<String> {
    REF_LABEL
        .captures(text.trim())
        .map(|captures| captures.name("a").or(captures.name("b")).unwrap().as_str().to_string())
}

/// Anchor-safe form of a footnote mark: symbols are spelled out, letters
/// and digits kept, anything else replaced by "x".
pub(crate) fn slug_marker(marker: &str) -> String {
    marker
        .chars()
        .map(|ch| match ch {
            '∗' | '*' => "star".to_string(),
            '†' => "dagger".to_string(),
            '‡' => "ddagger".to_string(),
            '§' => "sect".to_string(),
            '' => "para".to_string(),
            ch if ch.is_alphanumeric() => ch.to_string(),
            _ => "x".to_string(),
        })
        .collect()
}

/// Links the cross-references in every block (except equations, titles and
/// headings) and the footnote marks in every non-footnote block.
pub(crate) fn link_blocks(blocks: &mut [Block], cfg: &AssembleConfig) {
    let targets = LinkTargets::new(
        blocks
            .iter()
            .enumerate()
            .filter_map(|(index, block)| block.anchor.as_deref().map(|anchor| (index, anchor))),
        cfg.min_target_set_count,
    );
    // Footnote marks in the running text. A paper may number its notes
    // more than once (a report and its appendix), so a mark goes to the
    // note with that mark nearest after it: on its page, else the next.
    let notes: Vec<(String, usize, usize, String)> = blocks
        .iter()
        .enumerate()
        .filter_map(|(idx, block)| match (&block.kind, &block.anchor) {
            (BlockKind::Footnote { marker }, Some(anchor)) if marker.chars().all(|ch| ch.is_ascii_digit()) => {
                Some((marker.clone(), block.page, idx, anchor.clone()))
            }
            _ => None,
        })
        .collect();

    for (index, block) in blocks.iter_mut().enumerate() {
        let linkable = !matches!(
            block.kind,
            BlockKind::Equation { .. } | BlockKind::Title | BlockKind::Heading { .. }
        );
        if linkable {
            link_cross_references(block, &targets, index);
        }
        if !matches!(block.kind, BlockKind::Footnote { .. }) {
            let page = block.page;
            let note_for = |mark: &str| {
                notes
                    .iter()
                    // A note sits near its mark (a list of contributors
                    // may run on for two pages before its note); an
                    // affiliation number many pages away is not its mark.
                    .filter(|(marker, note_page, ..)| {
                        marker == mark
                            && *note_page + cfg.note_max_pages_before >= page
                            && *note_page <= page + cfg.note_max_pages_after
                    })
                    .min_by_key(|(_, note_page, note_idx, _)| {
                        (*note_page < page, note_page.abs_diff(page), note_idx.abs_diff(index))
                    })
                    .map(|(.., anchor)| anchor.clone())
            };
            link_footnote_marks(&mut block.spans, &note_for, cfg);
        }
    }
}

/// Links each entry of a table of contents to the heading it names: the
/// first heading with the same words (see
/// [`title_key`](super::contents::title_key)) after the one the previous
/// entry was linked to, so that the many "Summary" sections each get
/// their entry.
pub(crate) fn link_contents(blocks: &mut [Block]) {
    let headings: Vec<(usize, String)> = blocks
        .iter()
        .enumerate()
        .filter(|(_, block)| matches!(block.kind, BlockKind::Heading { .. }) && block.anchor.is_some())
        .map(|(idx, block)| (idx, super::contents::title_key(&spans_text(&block.spans))))
        .collect();
    let mut from = 0;
    for idx in 0..blocks.len() {
        if !matches!(blocks[idx].kind, BlockKind::ContentsEntry { .. }) {
            continue;
        }
        let key = super::contents::title_key(&spans_text(&blocks[idx].spans));
        if key.is_empty() {
            continue;
        }
        let found = headings[from..]
            .iter()
            .position(|(heading, heading_key)| *heading > idx && *heading_key == key);
        if let Some(pos) = found {
            let anchor = blocks[headings[from + pos].0].anchor.clone();
            from += pos + 1;
            for span in &mut blocks[idx].spans {
                if span.href.is_none() {
                    span.href = anchor.as_ref().map(|anchor| format!("#{anchor}"));
                }
            }
        }
    }
}

/// Links the cross-references in the running text, rows, line spans and
/// table cells of a block. References to the block's own anchor are not
/// linked in the running and line text.
fn link_cross_references(block: &mut Block, targets: &LinkTargets, at: usize) {
    let own = block.anchor.clone();
    let spans = std::mem::take(&mut block.spans);
    block.spans = link_spans(spans, targets, at, own.as_deref());
    let rows = std::mem::take(&mut block.rows);
    block.rows = rows.into_iter().map(|row| link_spans(row, targets, at, None)).collect();
    for hline in block.hlines.iter_mut() {
        let spans = std::mem::take(&mut hline.spans);
        hline.spans = link_spans(spans, targets, at, own.as_deref());
    }
    if let Some(table) = block.table.as_mut() {
        for cell in table.rows.iter_mut().flatten() {
            let spans = std::mem::take(&mut cell.spans);
            cell.spans = link_spans(spans, targets, at, None);
        }
    }
}

/// Links superscript numbers in the running text to the footnote with that
/// mark (`note_for`: mark → anchor), unless they look like exponents.
fn link_footnote_marks(spans: &mut [Span], note_for: &dyn Fn(&str) -> Option<String>, cfg: &AssembleConfig) {
    for i in 0..spans.len() {
        let span = &spans[i];
        if span.style & SUP != 0 && span.style & MATH == 0 && span.href.is_none() {
            let exponent = is_exponent(spans, i, cfg);
            if let (false, Some(anchor)) = (exponent, note_for(span.text.trim())) {
                spans[i].href = Some(format!("#{anchor}"));
            }
        }
    }
}

/// Whether the superscript span at `i` is an exponent rather than a
/// footnote mark. A footnote mark follows a word or punctuation; a digit or
/// a single letter before it means an exponent (x², c²), and so does
/// nothing or another superscript before it, and so does a closing bracket.
fn is_exponent(spans: &[Span], i: usize, cfg: &AssembleConfig) -> bool {
    i == 0 || spans[i - 1].style & SUP != 0 || {
        let prev = spans[i - 1].text.trim_end();
        let run = prev.chars().rev().take_while(|ch| ch.is_alphabetic()).count();
        match prev.chars().last() {
            Some(ch) if ch.is_ascii_digit() => true,
            // "(χ²)³", "{…}^{1/6}": a power of a bracketed expression.
            Some(')' | ']' | '}') => true,
            Some(ch) if ch.is_alphabetic() => run < cfg.mark_min_word_letters_count,
            Some(_) => false,
            None => true,
        }
    }
}