kakemono 0.22.1

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
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
//! Markdown output: the document as one `.md` file, built from the same
//! [`Document`] as the HTML modes. Headings, lists, captions, references and
//! code listings get their Markdown syntax; rebuilt tables become pipe
//! tables: in friendly mode every one of them, spanning cells and header
//! rows flattened; in medium mode only those
//! without spanning cells, the others staying HTML tables; formulas whose
//! structure is known become LaTeX between `$$`; figures (and the other
//! formulas) are pictures of their area of the page, written to an image
//! folder next to the file (or embedded as data URIs).

pub(crate) mod inline;

use super::latex::math::latex;
use super::{
    CAP_LABEL, Equations, HtmlOptions, ImageStore, Mode, PageImage, caption_first, code, code_run, doc_title,
    equation_math, figure_alt, float_class, heading_tag, is_abstract_text, is_scene_break, plain,
    stray_equation_number, table_walk,
};
use crate::analysis::pipeline::Analysis;
use crate::backend::PdfFile;
use crate::model::{Block, BlockKind, Document, FloatKind, ImageSpec, Span, Table, TableCell};
use crate::render::Pictures;
use inline::{Inline, escape, escape_line_start, note_label, spans_html};
use std::collections::HashSet;

/// Code fences are at least this many backticks long.
const MIN_FENCE: usize = 3;
/// Spaces that nest a list item one level deeper (past a parent marker
/// such as `10. `).
const MD_NEST_INDENT: usize = 4;
/// Spaces of indentation per level of a table of contents.
const CONTENTS_INDENT: usize = 2;

/// Everything that controls how a document is written as Markdown.
#[derive(Debug, Clone)]
pub struct MarkdownOptions {
    /// Embed the pictures as data URIs (one self-contained file) instead of
    /// writing them to [`MarkdownOptions::asset_dir`].
    pub inline_images: bool,
    /// Directory (relative to the Markdown file) of the picture files.
    pub asset_dir: String,
    /// Pixels per PDF point of the pictures of figures and formulas.
    pub scale: f32,
    /// Worker threads for drawing the pictures (0 = one per CPU).
    pub jobs: usize,
    /// How displayed formulas are written: [`Equations::MathMl`] gives LaTeX
    /// (`$$ … $$`) rebuilt from the glyphs where the structure of the
    /// formula is clear, pictures elsewhere.
    pub equations: Equations,
    /// How tables are written. [`Mode::Friendly`] adapts every rebuilt
    /// table to a pipe table: the header rows become one, and a cell that
    /// spans rows or columns is repeated in each of them. [`Mode::Medium`]
    /// keeps the layout of the table: pipe tables only for tables without
    /// spanning cells, HTML tables for the others. [`Mode::Hard`] and
    /// [`Mode::Hard95`] are written as medium.
    pub mode: Mode,
}

impl Default for MarkdownOptions {
    /// Pictures written to `images/` at 3 pixels per point, formulas as
    /// LaTeX where their structure is clear, tables adapted to Markdown
    /// (friendly), one worker thread per CPU.
    fn default() -> Self {
        Self {
            mode: Mode::Friendly,
            inline_images: false,
            asset_dir: "images".into(),
            scale: 3.0,
            jobs: 0,
            equations: Equations::MathMl,
        }
    }
}

/// The result of the Markdown output: the text and, when pictures are not
/// embedded, the picture files it refers to.
pub struct MarkdownOutput {
    /// The Markdown document.
    pub markdown: String,
    /// Files to write next to the Markdown file: (relative path, contents).
    pub files: Vec<(String, Vec<u8>)>,
}

/// Writes an analysed document as Markdown.
///
/// The text is written first, with placeholders for the pictures; the
/// pictures are then drawn from `pdf` (on `opts.jobs` threads) and either
/// embedded as data URIs or returned in [`MarkdownOutput::files`].
pub fn render_markdown(analysis: &Analysis, pdf: Option<&PdfFile>, opts: &MarkdownOptions) -> MarkdownOutput {
    let html_opts = HtmlOptions {
        mode: Mode::Friendly,
        inline_images: opts.inline_images,
        asset_dir: opts.asset_dir.clone(),
        scale: opts.scale,
        page_image: PageImage::Svg,
        jobs: opts.jobs,
        embed_fonts: false,
        equations: opts.equations,
    };
    let mut images = ImageStore {
        opts: &html_opts,
        jobs: Vec::new(),
        svg_as_pdf: false,
    };
    // Added notes are numbered across the document.
    let numbered = super::notes::numbered_analysis(analysis);
    let doc = &numbered.as_ref().unwrap_or(analysis).doc;
    let anchors = linked_anchors(doc);
    let mut writer = Writer {
        opts,
        inline: Inline {
            anchors: &anchors,
            math: opts.equations == Equations::MathMl,
        },
        images: &mut images,
        out: String::new(),
        list_indent: 0,
        bracket_src: !opts.inline_images && opts.asset_dir.contains(' '),
    };
    writer.write(doc);
    let text = writer.out.trim_end().to_string() + "\n";
    let out = images.finish(Pictures::new(pdf, &analysis.doc), text);
    MarkdownOutput {
        markdown: out.html,
        files: out.files,
    }
}

/// The anchors of the blocks that some text links to: only those get an
/// `<a id>`, so that the Markdown is not cluttered with unused ones.
pub(crate) fn linked_anchors(doc: &Document) -> HashSet<String> {
    let targets: HashSet<&str> = doc
        .blocks
        .iter()
        .flat_map(|block| block.spans.iter().chain(block.rows.iter().flatten()))
        .chain(
            doc.blocks
                .iter()
                .filter_map(|block| block.table.as_ref())
                .flat_map(|table| table.rows.iter().flatten().flat_map(|cell| cell.spans.iter())),
        )
        .filter_map(|span| span.href.as_deref()?.strip_prefix('#'))
        .collect();
    doc.blocks
        .iter()
        .filter_map(|block| block.anchor.as_deref())
        .filter(|anchor| targets.contains(anchor))
        .map(str::to_string)
        .collect()
}

/// Writes the Markdown of a document, block by block.
struct Writer<'a, 'r> {
    /// The output options.
    opts: &'a MarkdownOptions,
    /// Writes the text of the blocks.
    inline: Inline<'a>,
    /// The pictures; each `src` is a placeholder until the end.
    images: &'a mut ImageStore<'r>,
    /// The Markdown so far.
    out: String,
    /// Indentation of the content of the list item written last (the
    /// width of its marker): a continuation paragraph is indented by it.
    list_indent: usize,
    /// Picture paths hold a space: they go in angle brackets.
    bracket_src: bool,
}

impl Writer<'_, '_> {
    /// Writes every block of `doc`. Runs of code paragraphs become one
    /// listing, the title blocks one title, and an abstract without a
    /// heading gets one.
    fn write(&mut self, doc: &Document) {
        let blocks: Vec<&Block> = doc.blocks.iter().collect();
        let mut idx = 0;
        let mut in_abstract = false;
        let mut after_front = false;
        while idx < blocks.len() {
            crate::common::cancel::check();
            let block = blocks[idx];
            if !after_front && !matches!(block.kind, BlockKind::Title | BlockKind::Authors | BlockKind::Note) {
                self.arxiv_link(doc);
                after_front = true;
            }
            if let Some(end) = code_run(&blocks, idx) {
                self.anchor(block);
                self.fence(&code::listing_lines(&blocks[idx..end]));
                (idx, in_abstract) = (end, false);
                continue;
            }
            match &block.kind {
                BlockKind::Title => {
                    let start = idx;
                    idx = self.title(doc, &blocks, idx);
                    blocks[start..idx].iter().for_each(|block| self.note_definitions(block));
                    continue;
                }
                BlockKind::Paragraph { in_abstract: true } => {
                    let had_heading = idx > 0
                        && matches!(blocks[idx - 1].kind, BlockKind::Heading { .. })
                        && is_abstract_text(&blocks[idx - 1].spans);
                    if !in_abstract && !had_heading {
                        self.paragraph(&format!("{} Abstract", heading_marks(1)));
                    }
                    in_abstract = true;
                }
                BlockKind::Equation { .. } => {}
                _ => in_abstract = false,
            }
            // An equation whose number was read as a paragraph of its own
            // takes it back.
            if let BlockKind::Equation { image, number: None } = &block.kind
                && let Some(number) = blocks.get(idx + 1).and_then(|next| stray_equation_number(next))
            {
                self.equation(block, image.as_ref(), Some(&number));
                idx += 2;
                continue;
            }
            self.block(block);
            self.note_definitions(block);
            idx += 1;
        }
        if !after_front {
            self.arxiv_link(doc);
        }
    }

    /// Writes one block.
    fn block(&mut self, block: &Block) {
        self.anchor(block);
        match &block.kind {
            BlockKind::Title => self.paragraph(&format!("# {}", self.inline.spans(&block.spans))),
            BlockKind::Authors => self.authors(block),
            BlockKind::Note => self.text_paragraph(&block.spans),
            BlockKind::Heading { level } => {
                let text = self.inline.spans(&block.spans);
                self.paragraph(&format!("{} {text}", heading_marks(*level)));
            }
            BlockKind::Paragraph { .. } if is_scene_break(&block.spans) => self.paragraph("* * *"),
            BlockKind::Paragraph { .. } => self.text_paragraph(&block.spans),
            BlockKind::ListItem { marker, level } => self.list_item(block, marker.as_deref(), *level),
            BlockKind::ListContinuation => {
                let text = escape_line_start(&self.inline.spans(&block.spans));
                self.paragraph(&format!("{}{text}", " ".repeat(self.list_indent.max(2))));
            }
            BlockKind::Reference { .. } => self.text_paragraph(&block.spans),
            // A note without a mark (a note in the margin of a book) is set
            // apart as a quotation.
            BlockKind::Footnote { marker } if marker.is_empty() => {
                let text = self.inline.spans(&block.spans);
                if !text.is_empty() {
                    self.paragraph(&format!("> {text}"));
                }
            }
            BlockKind::Footnote { marker } => {
                let mark = format!("<sup>{}</sup> ", escape(marker));
                self.paragraph(&format!("{mark}{}", self.inline.spans(&block.spans)));
            }
            BlockKind::Equation { image, number } => self.equation(block, image.as_ref(), number.as_deref()),
            BlockKind::Figure { kind, image, label } => self.figure(block, *kind, image.as_ref(), label),
            BlockKind::ContentsEntry { level, page } => {
                let indent = " ".repeat(usize::from(level.saturating_sub(1)) * CONTENTS_INDENT);
                let text = self.inline.spans(&block.spans);
                let page = if page.is_empty() {
                    String::new()
                } else {
                    format!(" — {}", escape(page))
                };
                self.line(&format!("{indent}- {text}{page}"));
            }
            BlockKind::Code => {
                let lines: Vec<String> = block
                    .rows
                    .iter()
                    .map(|row| row.iter().map(|span| span.text.as_str()).collect())
                    .collect();
                self.fence(&lines);
            }
        }
    }

    /// Writes the added notes of `block` as footnote definitions
    /// (`[^n1]: …`), after the block.
    fn note_definitions(&mut self, block: &Block) {
        for call in super::notes::calls(&[block]) {
            let text = self.inline.spans(call.note.as_deref().unwrap_or_default());
            if !call.text.is_empty() {
                self.paragraph(&format!("[^{}]: {text}", note_label(call)));
            }
        }
    }

    /// Writes `text` as a block, followed by a blank line.
    fn paragraph(&mut self, text: &str) {
        self.end_tight_list();
        self.out.push_str(text);
        self.out.push_str("\n\n");
    }

    /// Writes `text` as one line of a tight list (no blank line after it).
    fn line(&mut self, text: &str) {
        self.out.push_str(text);
        self.out.push('\n');
    }

    /// Ends a tight list (lines written by [`Writer::line`]) with a blank
    /// line.
    fn end_tight_list(&mut self) {
        if !self.out.is_empty() && !self.out.ends_with("\n\n") {
            self.out.push('\n');
        }
    }

    /// Writes spans as a paragraph of running text.
    fn text_paragraph(&mut self, spans: &[Span]) {
        let text = self.inline.spans(spans);
        if !text.is_empty() {
            self.paragraph(&escape_line_start(&text));
        }
    }

    /// Writes the `<a id>` of a block that some text links to.
    fn anchor(&mut self, block: &Block) {
        if let Some(anchor) = block
            .anchor
            .as_deref()
            .filter(|anchor| self.inline.anchors.contains(*anchor))
        {
            self.end_tight_list();
            self.out.push_str(&format!("<a id=\"{}\"></a>\n\n", super::esc(anchor)));
        }
    }

    /// Writes a link to the arXiv page of the paper, after the front matter.
    fn arxiv_link(&mut self, doc: &Document) {
        if let Some(id) = &doc.meta.arxiv_id {
            self.paragraph(&format!("[arXiv:{}](https://arxiv.org/abs/{id})", escape(id)));
        }
    }

    /// Writes the title blocks that start at `blocks[start]` as one title
    /// and returns the index of the block after them.
    fn title(&mut self, doc: &Document, blocks: &[&Block], start: usize) -> usize {
        let end = start
            + blocks[start..]
                .iter()
                .take_while(|block| matches!(block.kind, BlockKind::Title))
                .count();
        let mut spans: Vec<Span> = Vec::new();
        for block in &blocks[start..end] {
            self.anchor(block);
            if !spans.is_empty() {
                spans.push(Span::plain(" "));
            }
            spans.extend(block.spans.iter().cloned());
        }
        let text = self.inline.spans(&spans);
        if text.is_empty() {
            self.paragraph(&format!("# {}", escape(&doc_title(doc))));
        } else {
            self.paragraph(&format!("# {text}"));
        }
        end
    }

    /// Writes an author group: the name in bold, then the affiliation
    /// lines, each on a line of its own.
    fn authors(&mut self, block: &Block) {
        let rows = if block.rows.is_empty() {
            std::slice::from_ref(&block.spans)
        } else {
            &block.rows[..]
        };
        let lines: Vec<String> = rows
            .iter()
            .enumerate()
            .map(|(i, row)| {
                let text = self.inline.spans(row);
                if i == 0 && !text.is_empty() && !text.contains('*') {
                    format!("**{text}**")
                } else {
                    text
                }
            })
            .filter(|text| !text.is_empty())
            .collect();
        if !lines.is_empty() {
            self.paragraph(&escape_line_start(&lines.join("  \n")));
        }
    }

    /// Writes a list item: a numbered one (`3.`) when its marker is a
    /// number, a bullet item otherwise, with any other marker kept as its
    /// first word.
    fn list_item(&mut self, block: &Block, marker: Option<&str>, level: u8) {
        let number = marker
            .map(|marker| marker.trim_end_matches(['.', ')']))
            .filter(|digits| !digits.is_empty() && digits.len() <= 9 && digits.bytes().all(|b| b.is_ascii_digit()));
        let rest = marker.and_then(|marker| strip_label(&block.spans, marker));
        let prefix = match (number, marker, &rest) {
            (Some(number), _, _) => format!("{number}. "),
            (None, Some(marker), Some(_)) => format!("- {} ", escape(marker)),
            _ => "- ".to_string(),
        };
        let text = self.inline.spans(rest.as_deref().unwrap_or(&block.spans));
        // A nested item is indented past the marker of its parent.
        let nest = " ".repeat(usize::from(level) * MD_NEST_INDENT);
        self.list_indent = nest.len() + if number.is_some() { prefix.len() } else { 2 };
        self.paragraph(&format!("{nest}{prefix}{text}"));
    }

    /// Writes code lines as a fenced code block.
    fn fence(&mut self, lines: &[String]) {
        let longest = lines
            .iter()
            .flat_map(|line| line.split(|ch| ch != '`'))
            .map(str::len)
            .max()
            .unwrap_or(0);
        let fence = "`".repeat((longest + 1).max(MIN_FENCE));
        let body = lines.join("\n");
        self.paragraph(&format!("{fence}\n{}\n{fence}", body.trim_end()));
    }

    /// Writes a displayed formula: as LaTeX when its structure is known
    /// (and wanted), as a picture otherwise; with its number.
    fn equation(&mut self, block: &Block, image: Option<&ImageSpec>, number: Option<&str>) {
        let tag = number.map(|number| number.trim().trim_start_matches('(').trim_end_matches(')').trim());
        if let Some(math) = equation_math(block, image, self.opts.equations) {
            let tag = tag.map(|tag| format!(" \\tag{{{tag}}}")).unwrap_or_default();
            self.paragraph(&format!("$$\n{}{tag}\n$$", latex(math)));
            return;
        }
        let shown = match image {
            Some(image) => self.picture(image, &plain(&block.spans), "eq"),
            None => escape(&plain(&block.spans)),
        };
        let number = number.map(|number| format!(" {}", escape(number))).unwrap_or_default();
        self.paragraph(&format!("{shown}{number}"));
    }

    /// Writes a float: the rebuilt table or the picture, and the caption
    /// on the side it had in the paper. A float whose text is all code is
    /// a listing.
    fn figure(&mut self, block: &Block, kind: FloatKind, image: Option<&ImageSpec>, label: &Option<String>) {
        let caption = (!block.spans.is_empty()).then(|| self.caption(&block.spans));
        if kind == FloatKind::Algorithm
            && block.table.is_none()
            && let Some(lines) = code::float_listing_lines(block)
        {
            if let Some(caption) = &caption {
                self.paragraph(caption);
            }
            return self.fence(&lines);
        }
        let caption_first = caption_first(block, image);
        if caption_first && let Some(caption) = &caption {
            self.paragraph(caption);
        }
        if let Some(table) = &block.table {
            let text = self.table(table);
            self.paragraph(&text);
        } else if let Some(spec) = image {
            let picture = self.picture(spec, &figure_alt(block, label), float_class(kind));
            self.paragraph(&picture);
        }
        if !caption_first && let Some(caption) = &caption {
            self.paragraph(caption);
        }
    }

    /// A caption, with its label ("Figure 3:") in bold.
    fn caption(&self, spans: &[Span]) -> String {
        if let Some(first) = spans.first()
            && let Some(found) = CAP_LABEL.find(&first.text)
        {
            let label = first.text[..found.end()].trim_end();
            let mut rest = spans.to_vec();
            rest[0].text = first.text[label.len()..].to_string();
            let text = self.inline.spans(&rest);
            return format!("**{}** {text}", escape(label)).trim_end().to_string();
        }
        escape_line_start(&self.inline.spans(spans))
    }

    /// The Markdown picture of a page area, whose `src` is drawn later.
    fn picture(&mut self, spec: &ImageSpec, alt: &str, hint: &str) -> String {
        let src = self.images.region(spec, hint);
        let alt = escape(&alt.replace(['\n', '\r'], " "));
        if self.bracket_src {
            format!("![{alt}](<{src}>)")
        } else {
            format!("![{alt}]({src})")
        }
    }

    /// A rebuilt table: in friendly mode a flattened pipe table; in the
    /// others a pipe table when it has one header row and no cell spans
    /// several positions, an HTML table otherwise.
    fn table(&self, table: &Table) -> String {
        if self.opts.mode == Mode::Friendly && table.n_cols > 0 {
            return flat_table(&self.inline, table);
        }
        let simple = table.header_rows == 1
            && table.n_cols > 0
            && table
                .rows
                .iter()
                .flatten()
                .all(|cell| cell.colspan == 1 && cell.rowspan == 1);
        if simple {
            self.pipe_table(table)
        } else {
            self.html_table(table)
        }
    }

    /// A table as a GitHub-flavoured pipe table.
    fn pipe_table(&self, table: &Table) -> String {
        let mut lines = Vec::new();
        let mut pace = crate::common::cancel::Pace::default();
        for (row_idx, row) in table.rows.iter().enumerate() {
            pace.tick();
            let mut cells = vec![String::new(); table.n_cols];
            for cell in row.iter().filter(|cell| cell.col < table.n_cols) {
                cells[cell.col] = self.inline.cell(&cell.spans);
            }
            lines.push(format!("| {} |", cells.join(" | ")));
            if row_idx == 0 {
                let rule: Vec<&str> = (0..table.n_cols)
                    .map(|col| match table.col_align.get(col).copied() {
                        Some("center") => ":---:",
                        Some("right") => "---:",
                        _ => "---",
                    })
                    .collect();
                lines.push(format!("| {} |", rule.join(" | ")));
            }
        }
        lines.join("\n")
    }

    /// A table as plain HTML (no classes), with its spanning cells.
    fn html_table(&self, table: &Table) -> String {
        let mut out = String::from("<table>");
        let mut open_row: Option<usize> = None;
        table_walk(table, |row_idx, _, cell| {
            if open_row != Some(row_idx) {
                if open_row.is_some() {
                    out.push_str("</tr>");
                }
                out.push_str("\n<tr>");
                open_row = Some(row_idx);
            }
            let tag = if row_idx < table.header_rows { "th" } else { "td" };
            out.push_str(&match cell {
                None => format!("<{tag}></{tag}>"),
                Some(cell) => self.html_cell(cell, tag),
            });
        });
        if open_row.is_some() {
            out.push_str("</tr>");
        }
        out.push_str("\n</table>");
        out
    }

    /// One cell of an HTML table.
    fn html_cell(&self, cell: &TableCell, tag: &str) -> String {
        format!(
            "<{tag}{}>{}</{tag}>",
            super::span_attrs(cell),
            spans_html(&cell.spans, self.inline.anchors)
        )
    }
}

/// A table as a pipe table, whatever its spanning cells: the meaning of
/// every cell is kept, not its layout.
///
/// - The header rows become one: each column is headed by the texts
///   above it, from top to bottom. A group header (a cell over several
///   columns) is followed by a colon ("BLEU: EN-DE"); a header over one
///   column only is the line before, and a space follows it ("train
///   steps"). A header across the whole table that no header row below
///   splits is not a group but a header the analysis could not cut: it
///   is written once, in the first column.
/// - A cell of the body spanning rows is repeated in each, so that every
///   row reads on its own. A cell spanning columns is repeated in each
///   when they are under one group header (one cost for two language
///   pairs), and written once in the first otherwise (a note across the
///   row).
/// - A row holding one cell across the whole table (a group label) is
///   written in bold in the first column.
/// - A table without header rows gets an empty one, which a pipe table
///   needs.
fn flat_table(inline: &Inline<'_>, table: &Table) -> String {
    let grid = covering_cells(table);
    let header_rows = table.header_rows.min(grid.len());
    let head = &grid[..header_rows];
    let header: Vec<String> = (0..table.n_cols)
        .map(|col| flat_header(inline, head, col, table.n_cols))
        .collect();
    let rule: Vec<&str> = (0..table.n_cols)
        .map(|col| match table.col_align.get(col).copied() {
            Some("center") => ":---:",
            Some("right") => "---:",
            _ => "---",
        })
        .collect();
    let mut pace = crate::common::cancel::Pace::default();
    let body: Vec<Vec<String>> = grid[header_rows..]
        .iter()
        .filter_map(|row| {
            pace.tick();
            flat_row(inline, head, row, table.n_cols)
        })
        .collect();
    // A column empty in every row (one a merged cell covers, written once)
    // is left out.
    let keep: Vec<bool> = (0..table.n_cols)
        .map(|col| !header[col].is_empty() || body.iter().any(|row| !row[col].is_empty()))
        .collect();
    let kept = |cells: &[String]| -> Vec<String> {
        cells
            .iter()
            .zip(&keep)
            .filter(|(_, keep)| **keep)
            .map(|(cell, _)| cell.clone())
            .collect()
    };
    let rule: Vec<String> = rule
        .iter()
        .zip(&keep)
        .filter(|(_, keep)| **keep)
        .map(|(rule, _)| (*rule).to_string())
        .collect();
    let mut lines = vec![pipe_row(&kept(&header)), pipe_row(&rule)];
    lines.extend(body.iter().map(|cells| {
        pace.tick();
        pipe_row(&kept(cells))
    }));
    lines.join("\n")
}

/// The header of column `col` of a flattened table: the texts of the header
/// rows above it, from top to bottom (see [`flat_table`]).
fn flat_header(inline: &Inline<'_>, head: &[Vec<Option<&TableCell>>], col: usize, n_cols: usize) -> String {
    let mut out = String::new();
    let mut group = false;
    for (row_idx, row) in head.iter().enumerate() {
        let Some(cell) = row[col] else { continue };
        let is_group = is_group(head, row_idx, cell, n_cols);
        // A wide group header no header row splits (a form's title) heads
        // only its first column.
        let repeated = is_group && (cell.colspan <= MAX_REPEATED_COLS || splits_below(head, row_idx, cell));
        if col != cell.col && !repeated {
            continue;
        }
        let text = inline.cell(&cell.spans);
        if text.is_empty() || out.ends_with(&text) {
            continue;
        }
        if !out.is_empty() {
            out.push_str(if group { HEADER_GROUP_JOIN } else { " " });
        }
        out.push_str(text.strip_suffix(':').unwrap_or(&text).trim_end());
        group = is_group;
    }
    out
}

/// The cells of a body row of a flattened table (see [`flat_table`]), or
/// `None` when the row is empty.
fn flat_row(
    inline: &Inline<'_>,
    head: &[Vec<Option<&TableCell>>],
    row: &[Option<&TableCell>],
    n_cols: usize,
) -> Option<Vec<String>> {
    let mut cells: Vec<String> = (0..n_cols)
        .map(|col| match row[col] {
            Some(cell) if col == cell.col || under_one_group(head, cell, n_cols) => inline.cell(&cell.spans),
            _ => String::new(),
        })
        .collect();
    if cells.iter().all(String::is_empty) {
        return None;
    }
    let label = n_cols > 1
        && row
            .iter()
            .all(|cell| cell.is_some_and(|cell| row[0].is_some_and(|first| std::ptr::eq(cell, first))));
    if label {
        let text = std::mem::take(&mut cells[0]);
        cells.iter_mut().for_each(String::clear);
        cells[0] = if text.starts_with("**") {
            text
        } else {
            format!("**{text}**")
        };
    }
    Some(cells)
}

/// Follows a group header (over several columns) in the header of a
/// column of a flattened table, before the header below it.
const HEADER_GROUP_JOIN: &str = ": ";

/// One row of a pipe table.
fn pipe_row<S: AsRef<str>>(cells: &[S]) -> String {
    let cells: Vec<&str> = cells.iter().map(AsRef::as_ref).collect();
    format!("| {} |", cells.join(" | "))
}

/// A header cell over several columns is a group header ("BLEU" over
/// "EN-DE" and "EN-FR"), unless it is across the whole table and no header
/// row below splits it: then it is a row of headers the analysis could not
/// cut ("Dataset Sampling prop. Epochs Disk size").
fn is_group(header: &[Vec<Option<&TableCell>>], row_idx: usize, cell: &TableCell, n_cols: usize) -> bool {
    cell.colspan > 1 && (cell.colspan < n_cols || splits_below(header, row_idx, cell))
}

/// A header row below the header cell `cell` splits its columns into other
/// cells.
fn splits_below(header: &[Vec<Option<&TableCell>>], row_idx: usize, cell: &TableCell) -> bool {
    header[row_idx + 1..].iter().any(|row| {
        row.iter()
            .skip(cell.col)
            .take(cell.colspan)
            .any(|below| below.is_some_and(|below| !std::ptr::eq(below, cell) && !below.spans.is_empty()))
    })
}

/// The most columns a cell under a group header is repeated in: one over
/// more (a form's merged field) is written once.
const MAX_REPEATED_COLS: usize = 4;

/// A cell spanning several columns (at most [`MAX_REPEATED_COLS`]) lies
/// under one group header: a group header covers all of its columns (as
/// "Training Cost" over its two language pairs).
fn under_one_group(header: &[Vec<Option<&TableCell>>], cell: &TableCell, n_cols: usize) -> bool {
    (2..=MAX_REPEATED_COLS).contains(&cell.colspan)
        && header.iter().enumerate().any(|(row_idx, row)| {
            row.get(cell.col).copied().flatten().is_some_and(|group| {
                group.col <= cell.col
                    && group.col + group.colspan >= cell.col + cell.colspan
                    && is_group(header, row_idx, group, n_cols)
            })
        })
}

/// For each position `[row][col]` of the grid, the cell that covers it:
/// the cell that starts there or one spanning from an earlier row or
/// column.
fn covering_cells(table: &Table) -> Vec<Vec<Option<&TableCell>>> {
    let n_rows = table.rows.len();
    let mut grid = vec![vec![None; table.n_cols]; n_rows];
    let mut pace = crate::common::cancel::Pace::default();
    for (row_idx, row) in table.rows.iter().enumerate() {
        pace.tick();
        for cell in row {
            let rows_end = (row_idx + cell.rowspan.max(1)).min(n_rows);
            let cols_end = (cell.col + cell.colspan.max(1)).min(table.n_cols);
            for grid_row in &mut grid[row_idx..rows_end] {
                for slot in grid_row.iter_mut().take(cols_end).skip(cell.col) {
                    *slot = Some(cell);
                }
            }
        }
    }
    grid
}

/// The `#` marks of a heading of `level` (`##` for sections: `#` is the
/// title), as for the HTML headings.
fn heading_marks(level: u8) -> &'static str {
    match heading_tag(level) {
        "h2" => "##",
        "h3" => "###",
        "h4" => "####",
        _ => "#####",
    }
}

/// The spans after the label `label` at the start of their text (and the
/// spaces after it), or `None` when the text does not start with it.
pub(crate) fn strip_label(spans: &[Span], label: &str) -> Option<Vec<Span>> {
    let first = spans.first()?;
    let rest = first.text.strip_prefix(label).filter(|_| !label.is_empty())?;
    let mut spans = spans.to_vec();
    spans[0].text = rest.trim_start().to_string();
    Some(spans)
}

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

    fn cell(col: usize, colspan: usize, rowspan: usize, text: &str) -> TableCell {
        TableCell {
            col,
            colspan,
            rowspan,
            spans: vec![Span::plain(text)],
        }
    }

    fn table(n_cols: usize, header_rows: usize, rows: Vec<Vec<TableCell>>) -> Table {
        let n_rows = rows.len();
        Table {
            n_cols,
            header_rows,
            col_align: vec!["left"; n_cols],
            rows,
            rule_above: vec![vec![0; n_cols]; n_rows],
            rule_bottom: vec![0; n_cols],
            rule_left: vec![vec![false; n_cols]; n_rows],
            rule_right: vec![false; n_rows],
            geom: TableGeom::default(),
        }
    }

    fn flat(table: &Table) -> String {
        let anchors = HashSet::new();
        let inline = Inline {
            anchors: &anchors,
            math: false,
        };
        flat_table(&inline, table)
    }

    #[test]
    fn a_form_s_wide_merged_fields_are_written_once() {
        // A title over 6 of 8 columns, then a label and a field merged over
        // 6 columns: the field once, and the columns it covers (and the last,
        // empty) left out.
        let table = table(
            8,
            1,
            vec![
                vec![cell(0, 6, 1, "Application"), cell(6, 1, 1, "Date")],
                vec![cell(0, 1, 1, "Name"), cell(1, 6, 1, "Taro")],
            ],
        );
        assert_eq!(
            flat(&table),
            "| Application |  | Date |\n| --- | --- | --- |\n| Name | Taro |  |"
        );
    }

    #[test]
    fn flat_table_joins_header_rows_and_repeats_spanning_cells() {
        // Model | BLEU (2 columns) | Cost (2 columns), then the language
        // pairs; a model spanning two rows; a cost over both pairs; a note
        // across columns that are not one group.
        let table = table(
            5,
            2,
            vec![
                vec![cell(0, 1, 2, "Model"), cell(1, 2, 1, "BLEU"), cell(3, 2, 1, "Cost")],
                vec![
                    cell(1, 1, 1, "DE"),
                    cell(2, 1, 1, "FR"),
                    cell(3, 1, 1, "DE"),
                    cell(4, 1, 1, "FR"),
                ],
                vec![
                    cell(0, 1, 2, "A"),
                    cell(1, 1, 1, "1"),
                    cell(2, 1, 1, "2"),
                    cell(3, 2, 1, "9"),
                ],
                vec![cell(1, 3, 1, "same as above"), cell(4, 1, 1, "8")],
                vec![cell(0, 5, 1, "Ensembles")],
            ],
        );
        assert_eq!(
            flat(&table),
            "| Model | BLEU: DE | BLEU: FR | Cost: DE | Cost: FR |\n\
             | --- | --- | --- | --- | --- |\n\
             | A | 1 | 2 | 9 | 9 |\n\
             | A | same as above |  |  | 8 |\n\
             | **Ensembles** |  |  |  |  |"
        );
    }

    #[test]
    fn flat_table_joins_a_wrapped_header_with_a_space() {
        let table = table(
            2,
            2,
            vec![
                vec![cell(0, 1, 1, "train"), cell(1, 1, 2, "BLEU")],
                vec![cell(0, 1, 1, "steps")],
                vec![cell(0, 1, 1, "100K"), cell(1, 1, 1, "25.8")],
            ],
        );
        assert_eq!(flat(&table), "| train steps | BLEU |\n| --- | --- |\n| 100K | 25.8 |");
    }

    #[test]
    fn flat_table_writes_an_unsplit_header_once() {
        // The analysis could not cut the header: one cell across the table.
        let table = table(
            3,
            1,
            vec![
                vec![cell(0, 3, 1, "Dataset Prop. Size")],
                vec![cell(0, 1, 1, "C4"), cell(1, 1, 1, "15%"), cell(2, 1, 1, "783 GB")],
            ],
        );
        assert_eq!(
            flat(&table),
            "| Dataset Prop. Size |  |  |\n| --- | --- | --- |\n| C4 | 15% | 783 GB |"
        );
    }

    #[test]
    fn flat_table_without_header_rows_has_an_empty_header() {
        let table = table(2, 0, vec![vec![cell(0, 1, 1, "mass"), cell(1, 1, 1, "36 | 5")]]);
        assert_eq!(flat(&table), "|  |  |\n| --- | --- |\n| mass | 36 \\| 5 |");
    }
}