termmd 0.1.2

A best-in-class Markdown viewer for the terminal: real typography, real tables, real images.
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
//! Folds `pulldown-cmark`'s event stream into the [`Document`] tree.
//!
//! The stream is flat -- `Start(Tag)` / content / `End(TagEnd)` -- so we keep a
//! stack of half-built nodes. Each `Start` pushes a frame, each `End` pops one
//! and hands the finished node to whatever is underneath it.
//!
//! Two details are worth knowing about. First, tight list items have no
//! `Paragraph` events at all, so inline content can arrive with a block
//! container on top of the stack; we open an implicit paragraph in that case and
//! close it when the container does. Second, footnote definitions arrive inline
//! wherever the author wrote them, but belong at the end of the rendered
//! document, so they are lifted out of the block tree as we go.

use pulldown_cmark::{
    Alignment as CmAlignment, BlockQuoteKind, CodeBlockKind, Event, HeadingLevel, Options, Parser,
    Tag, TagEnd,
};

use super::html::{self, HtmlPiece};
use super::ir::{
    AlertKind, Alignment, Block, Document, ImageRef, Inline, Inlines, List, ListItem, Table,
    plain_text,
};
use super::slug::Slugger;

/// Which Markdown extensions to enable.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ParseOptions {
    /// Tables, task lists, strikethrough, footnotes, alerts.
    pub gfm: bool,
    /// `$inline$` and `$$display$$` math.
    pub math: bool,
    /// Curly quotes, en/em dashes, ellipses.
    pub smart_punctuation: bool,
    /// `[[wikilinks]]`.
    pub wikilinks: bool,
    /// Definition lists.
    pub definition_lists: bool,
    /// Treat a leading YAML block as front matter rather than content.
    pub front_matter: bool,
}

impl Default for ParseOptions {
    fn default() -> Self {
        Self {
            gfm: true,
            math: true,
            smart_punctuation: true,
            wikilinks: true,
            definition_lists: true,
            front_matter: true,
        }
    }
}

impl ParseOptions {
    fn to_cmark(self) -> Options {
        let mut o = Options::empty();
        if self.gfm {
            o |= Options::ENABLE_TABLES
                | Options::ENABLE_FOOTNOTES
                | Options::ENABLE_STRIKETHROUGH
                | Options::ENABLE_TASKLISTS
                | Options::ENABLE_GFM;
        }
        if self.math {
            o |= Options::ENABLE_MATH;
        }
        if self.smart_punctuation {
            o |= Options::ENABLE_SMART_PUNCTUATION;
        }
        if self.wikilinks {
            o |= Options::ENABLE_WIKILINKS;
        }
        if self.definition_lists {
            o |= Options::ENABLE_DEFINITION_LIST;
        }
        if self.front_matter {
            o |= Options::ENABLE_YAML_STYLE_METADATA_BLOCKS
                | Options::ENABLE_PLUSES_DELIMITED_METADATA_BLOCKS;
        }
        o | Options::ENABLE_HEADING_ATTRIBUTES
            | Options::ENABLE_SUPERSCRIPT
            | Options::ENABLE_SUBSCRIPT
    }
}

/// Parses Markdown into a [`Document`].
pub fn parse(source: &str, options: ParseOptions) -> Document {
    Builder::new(options).run(source)
}

/// A half-built node on the stack.
enum Frame {
    Paragraph {
        inlines: Inlines,
        implicit: bool,
    },
    Heading {
        level: u8,
        id: Option<String>,
        inlines: Inlines,
    },
    BlockQuote {
        kind: Option<AlertKind>,
        blocks: Vec<Block>,
    },
    CodeBlock {
        language: Option<String>,
        code: String,
    },
    List {
        start: Option<u64>,
        items: Vec<ListItem>,
        tight: bool,
    },
    /// `loose` records whether cmark emitted a real `Paragraph` directly
    /// inside this item, which is exactly the signal that the source had a
    /// blank line -- our own implicit paragraphs must not be mistaken for it.
    Item {
        task: Option<bool>,
        blocks: Vec<Block>,
        loose: bool,
    },
    Table {
        alignments: Vec<Alignment>,
        head: Vec<Inlines>,
        rows: Vec<Vec<Inlines>>,
        in_head: bool,
    },
    TableRow {
        cells: Vec<Inlines>,
    },
    TableCell {
        inlines: Inlines,
    },
    Emphasis(Inlines),
    Strong(Inlines),
    Strike(Inlines),
    Superscript(Inlines),
    Subscript(Inlines),
    Link {
        dest: String,
        title: Option<String>,
        content: Inlines,
    },
    Image {
        dest: String,
        title: Option<String>,
        alt: Inlines,
    },
    FootnoteDefinition {
        label: String,
        blocks: Vec<Block>,
    },
    DefinitionList {
        items: Vec<(Inlines, Vec<Vec<Block>>)>,
    },
    DefinitionTitle(Inlines),
    DefinitionBody(Vec<Block>),
    /// Raw HTML accumulated across the events of one block.
    HtmlBlock(String),
    Metadata(String),
}

struct Builder {
    options: ParseOptions,
    stack: Vec<Frame>,
    blocks: Vec<Block>,
    footnotes: Vec<(String, Vec<Block>)>,
    slugger: Slugger,
    front_matter: Option<String>,
}

impl Builder {
    fn new(options: ParseOptions) -> Self {
        Self {
            options,
            stack: Vec::new(),
            blocks: Vec::new(),
            footnotes: Vec::new(),
            slugger: Slugger::new(),
            front_matter: None,
        }
    }

    fn run(mut self, source: &str) -> Document {
        for event in Parser::new_ext(source, self.options.to_cmark()) {
            self.event(event);
        }
        // Unbalanced input (a truncated file, say) can leave frames open. Close
        // them rather than losing the content.
        while !self.stack.is_empty() {
            self.close_top();
        }
        let title = self
            .front_matter
            .as_deref()
            .and_then(front_matter_title)
            .or_else(|| first_h1(&self.blocks));

        Document {
            blocks: self.blocks,
            footnotes: self.footnotes,
            title,
            front_matter: self.front_matter,
        }
    }

    fn event(&mut self, event: Event<'_>) {
        match event {
            Event::Start(tag) => self.start(tag),
            Event::End(tag) => self.end(tag),
            Event::Text(t) => {
                if let Some(Frame::CodeBlock { code, .. }) = self.stack.last_mut() {
                    code.push_str(&t);
                } else if let Some(Frame::Metadata(s)) = self.stack.last_mut() {
                    s.push_str(&t);
                } else {
                    self.push_inline(Inline::Text(t.into_string()));
                }
            }
            Event::Code(t) => self.push_inline(Inline::Code(t.into_string())),
            Event::InlineMath(t) => self.push_inline(Inline::Math {
                text: t.into_string(),
                display: false,
            }),
            Event::DisplayMath(t) => self.push_block(Block::DisplayMath(t.into_string())),
            Event::SoftBreak => self.push_inline(Inline::SoftBreak),
            Event::HardBreak => self.push_inline(Inline::HardBreak),
            Event::Rule => self.push_block(Block::Rule),
            Event::FootnoteReference(label) => {
                self.push_inline(Inline::FootnoteRef(label.into_string()))
            }
            Event::TaskListMarker(checked) => {
                // Arrives just inside the item it belongs to, possibly after an
                // implicit paragraph has been opened.
                for frame in self.stack.iter_mut().rev() {
                    if let Frame::Item { task, .. } = frame {
                        *task = Some(checked);
                        break;
                    }
                }
            }
            Event::Html(h) => {
                // An HTML block arrives as one event per line, so a tag written
                // across lines -- `<img src=` with the URL underneath, which is
                // common in hand-written READMEs -- would never be seen whole if
                // each event were scanned on its own. Collect the block first.
                match self.stack.last_mut() {
                    Some(Frame::HtmlBlock(buffer)) => buffer.push_str(&h),
                    _ => self.html_block(&h),
                }
            }
            Event::InlineHtml(h) => self.inline_html(&h),
        }
    }

    fn start(&mut self, tag: Tag<'_>) {
        match tag {
            Tag::Paragraph => {
                self.close_implicit();
                // A paragraph opened directly inside an item means the author
                // left a blank line, so the enclosing list is loose.
                if let Some(Frame::Item { loose, .. }) = self.stack.last_mut() {
                    *loose = true;
                }
                self.stack.push(Frame::Paragraph {
                    inlines: Vec::new(),
                    implicit: false,
                });
            }
            Tag::Heading { level, id, .. } => {
                self.close_implicit();
                self.stack.push(Frame::Heading {
                    level: heading_level(level),
                    id: id.map(|i| i.into_string()),
                    inlines: Vec::new(),
                });
            }
            Tag::BlockQuote(kind) => {
                self.close_implicit();
                self.stack.push(Frame::BlockQuote {
                    kind: kind.map(alert_kind),
                    blocks: Vec::new(),
                });
            }
            Tag::CodeBlock(kind) => {
                self.close_implicit();
                let language = match kind {
                    CodeBlockKind::Fenced(info) => {
                        // The info string may carry more than a language, e.g.
                        // ```rust,ignore or ```js {highlight=1}.
                        let lang = info
                            .split([',', ' ', '\t', '{'])
                            .next()
                            .unwrap_or("")
                            .trim()
                            .to_string();
                        (!lang.is_empty()).then_some(lang)
                    }
                    CodeBlockKind::Indented => None,
                };
                self.stack.push(Frame::CodeBlock {
                    language,
                    code: String::new(),
                });
            }
            Tag::List(start) => {
                self.close_implicit();
                self.stack.push(Frame::List {
                    start,
                    items: Vec::new(),
                    tight: true,
                });
            }
            Tag::Item => {
                self.stack.push(Frame::Item {
                    task: None,
                    blocks: Vec::new(),
                    loose: false,
                });
            }
            Tag::Table(aligns) => {
                self.close_implicit();
                self.stack.push(Frame::Table {
                    alignments: aligns.into_iter().map(convert_alignment).collect(),
                    head: Vec::new(),
                    rows: Vec::new(),
                    in_head: false,
                });
            }
            Tag::TableHead => {
                if let Some(Frame::Table { in_head, .. }) = self.stack.last_mut() {
                    *in_head = true;
                }
                self.stack.push(Frame::TableRow { cells: Vec::new() });
            }
            Tag::TableRow => self.stack.push(Frame::TableRow { cells: Vec::new() }),
            Tag::TableCell => self.stack.push(Frame::TableCell {
                inlines: Vec::new(),
            }),
            Tag::Emphasis => self.stack.push(Frame::Emphasis(Vec::new())),
            Tag::Strong => self.stack.push(Frame::Strong(Vec::new())),
            Tag::Strikethrough => self.stack.push(Frame::Strike(Vec::new())),
            Tag::Superscript => self.stack.push(Frame::Superscript(Vec::new())),
            Tag::Subscript => self.stack.push(Frame::Subscript(Vec::new())),
            Tag::Link {
                dest_url, title, ..
            } => self.stack.push(Frame::Link {
                dest: dest_url.into_string(),
                title: non_empty(title.into_string()),
                content: Vec::new(),
            }),
            Tag::Image {
                dest_url, title, ..
            } => self.stack.push(Frame::Image {
                dest: dest_url.into_string(),
                title: non_empty(title.into_string()),
                alt: Vec::new(),
            }),
            Tag::FootnoteDefinition(label) => {
                self.close_implicit();
                self.stack.push(Frame::FootnoteDefinition {
                    label: label.into_string(),
                    blocks: Vec::new(),
                });
            }
            Tag::DefinitionList => {
                self.close_implicit();
                self.stack.push(Frame::DefinitionList { items: Vec::new() });
            }
            Tag::DefinitionListTitle => self.stack.push(Frame::DefinitionTitle(Vec::new())),
            Tag::DefinitionListDefinition => self.stack.push(Frame::DefinitionBody(Vec::new())),
            Tag::HtmlBlock => {
                self.close_implicit();
                self.stack.push(Frame::HtmlBlock(String::new()));
            }
            Tag::MetadataBlock(_) => self.stack.push(Frame::Metadata(String::new())),
        }
    }

    fn end(&mut self, tag: TagEnd) {
        match tag {
            // Containers close their implicit paragraph before closing themselves.
            TagEnd::Item
            | TagEnd::BlockQuote(_)
            | TagEnd::FootnoteDefinition
            | TagEnd::DefinitionListDefinition => {
                self.close_implicit();
                self.close_top();
            }
            TagEnd::HtmlBlock => {
                self.close_implicit();
                self.close_top();
            }
            _ => self.close_top(),
        }
    }

    /// Pops the top frame and folds it into its parent.
    fn close_top(&mut self) {
        let Some(frame) = self.stack.pop() else {
            return;
        };
        match frame {
            Frame::Paragraph { inlines, .. } => {
                if let Some(block) = paragraph_block(inlines) {
                    self.push_block(block);
                }
            }
            Frame::Heading { level, id, inlines } => {
                let text = plain_text(&inlines);
                let id = id.unwrap_or_else(|| self.slugger.slug(&text));
                self.push_block(Block::Heading {
                    level,
                    id,
                    content: inlines,
                });
            }
            Frame::BlockQuote { kind, blocks } => {
                self.push_block(Block::BlockQuote { kind, blocks })
            }
            Frame::CodeBlock { language, code } => {
                // Fenced blocks always end with a newline the author did not type.
                let code = code.strip_suffix('\n').map(str::to_string).unwrap_or(code);
                self.push_block(Block::CodeBlock { language, code });
            }
            Frame::List {
                start,
                items,
                tight,
            } => self.push_block(Block::List(List {
                start,
                tight,
                items,
            })),
            Frame::Item {
                task,
                blocks,
                loose,
            } => {
                if let Some(Frame::List { items, tight, .. }) = self.stack.last_mut() {
                    if loose {
                        *tight = false;
                    }
                    items.push(ListItem { task, blocks });
                }
            }
            Frame::Table {
                alignments,
                head,
                rows,
                ..
            } => self.push_block(Block::Table(Table {
                alignments,
                head,
                rows,
            })),
            Frame::TableRow { cells } => {
                if let Some(Frame::Table {
                    head,
                    rows,
                    in_head,
                    ..
                }) = self.stack.last_mut()
                {
                    if *in_head {
                        *head = cells;
                        *in_head = false;
                    } else {
                        rows.push(cells);
                    }
                }
            }
            Frame::TableCell { inlines } => {
                if let Some(Frame::TableRow { cells }) = self.stack.last_mut() {
                    cells.push(inlines);
                }
            }
            Frame::Emphasis(c) => self.push_inline(Inline::Emph(c)),
            Frame::Strong(c) => self.push_inline(Inline::Strong(c)),
            Frame::Strike(c) => self.push_inline(Inline::Strike(c)),
            Frame::Superscript(c) => self.push_inline(Inline::Superscript(c)),
            Frame::Subscript(c) => self.push_inline(Inline::Subscript(c)),
            Frame::Link {
                dest,
                title,
                content,
            } => self.push_inline(Inline::Link {
                dest,
                title,
                content,
            }),
            Frame::Image { dest, title, alt } => {
                let alt = plain_text(&alt);
                self.push_inline(Inline::Image(ImageRef {
                    url: dest,
                    alt,
                    title,
                }));
            }
            Frame::FootnoteDefinition { label, blocks } => self.footnotes.push((label, blocks)),
            Frame::DefinitionList { items } => self.push_block(Block::DefinitionList(items)),
            Frame::DefinitionTitle(inlines) => {
                if let Some(Frame::DefinitionList { items }) = self.stack.last_mut() {
                    items.push((inlines, Vec::new()));
                }
            }
            Frame::DefinitionBody(blocks) => {
                if let Some(Frame::DefinitionList { items }) = self.stack.last_mut() {
                    if let Some(last) = items.last_mut() {
                        last.1.push(blocks);
                    }
                }
            }
            Frame::HtmlBlock(raw) => self.html_block(&raw),
            Frame::Metadata(text) => self.front_matter = Some(text),
        }
    }

    /// Closes a paragraph we opened ourselves for a tight list item.
    fn close_implicit(&mut self) {
        if matches!(
            self.stack.last(),
            Some(Frame::Paragraph { implicit: true, .. })
        ) {
            self.close_top();
        }
    }

    /// Adds an inline to the nearest frame that accepts one, opening an implicit
    /// paragraph if the nearest frame is a block container.
    fn push_inline(&mut self, inline: Inline) {
        match self.stack.last_mut() {
            Some(Frame::Paragraph { inlines, .. })
            | Some(Frame::Heading { inlines, .. })
            | Some(Frame::TableCell { inlines })
            | Some(Frame::Emphasis(inlines))
            | Some(Frame::Strong(inlines))
            | Some(Frame::Strike(inlines))
            | Some(Frame::Superscript(inlines))
            | Some(Frame::Subscript(inlines))
            | Some(Frame::DefinitionTitle(inlines)) => inlines.push(inline),
            Some(Frame::Link { content, .. }) => content.push(inline),
            Some(Frame::Image { alt, .. }) => alt.push(inline),
            _ => {
                self.stack.push(Frame::Paragraph {
                    inlines: vec![inline],
                    implicit: true,
                });
            }
        }
    }

    /// Adds a finished block to the nearest block container.
    fn push_block(&mut self, block: Block) {
        self.close_implicit();
        for frame in self.stack.iter_mut().rev() {
            match frame {
                Frame::Item { blocks, .. }
                | Frame::BlockQuote { blocks, .. }
                | Frame::FootnoteDefinition { blocks, .. }
                | Frame::DefinitionBody(blocks) => {
                    blocks.push(block);
                    return;
                }
                _ => {}
            }
        }
        self.blocks.push(block);
    }

    /// Turns a raw HTML block into whatever we can actually draw.
    fn html_block(&mut self, raw: &str) {
        let pieces = html::simplify(raw);
        if pieces.is_empty() {
            return;
        }
        let mut inlines = Vec::new();
        for piece in pieces {
            match piece {
                HtmlPiece::Text(t) => inlines.push(Inline::Text(t)),
                HtmlPiece::Summary(t) => inlines.push(Inline::Strong(vec![Inline::Text(t)])),
                HtmlPiece::Image(img) => {
                    // Each picture becomes its own figure. A terminal cannot put
                    // two images side by side on one row anyway, and a row of
                    // badges reads better stacked than merged into a sentence.
                    if let Some(block) = paragraph_block(std::mem::take(&mut inlines)) {
                        self.push_block(block);
                    }
                    if let Some(block) = paragraph_block(vec![Inline::Image(img)]) {
                        self.push_block(block);
                    }
                }
                HtmlPiece::Break => {
                    // Flush what we have; each break starts a fresh paragraph so
                    // banner-style HTML does not run together.
                    if let Some(block) = paragraph_block(std::mem::take(&mut inlines)) {
                        self.push_block(block);
                    }
                }
            }
        }
        if let Some(block) = paragraph_block(inlines) {
            self.push_block(block);
        }
    }

    fn inline_html(&mut self, raw: &str) {
        for piece in html::simplify(raw) {
            match piece {
                HtmlPiece::Text(t) | HtmlPiece::Summary(t) => self.push_inline(Inline::Text(t)),
                HtmlPiece::Image(img) => self.push_inline(Inline::Image(img)),
                HtmlPiece::Break => self.push_inline(Inline::HardBreak),
            }
        }
    }
}

/// Builds a paragraph, promoting an image-only paragraph to a figure.
///
/// Authors write `![alt](x.png)` on a line of its own to mean "show this
/// picture", not "here is a sentence containing a picture", and the distinction
/// decides how much room we give it.
fn paragraph_block(inlines: Inlines) -> Option<Block> {
    let mut meaningful = inlines.iter().filter(|i| !is_blank(i));
    if let Some(Inline::Image(img)) = meaningful.next() {
        if meaningful.next().is_none() {
            let caption = if img.alt.is_empty() {
                Vec::new()
            } else {
                vec![Inline::Text(img.alt.clone())]
            };
            return Some(Block::Figure {
                image: img.clone(),
                caption,
            });
        }
    }
    if inlines.iter().all(is_blank) {
        return None;
    }
    Some(Block::Paragraph(inlines))
}

fn is_blank(i: &Inline) -> bool {
    match i {
        Inline::Text(t) => t.trim().is_empty(),
        Inline::SoftBreak | Inline::HardBreak => true,
        _ => false,
    }
}

fn non_empty(s: String) -> Option<String> {
    (!s.is_empty()).then_some(s)
}

fn heading_level(l: HeadingLevel) -> u8 {
    match l {
        HeadingLevel::H1 => 1,
        HeadingLevel::H2 => 2,
        HeadingLevel::H3 => 3,
        HeadingLevel::H4 => 4,
        HeadingLevel::H5 => 5,
        HeadingLevel::H6 => 6,
    }
}

fn convert_alignment(a: CmAlignment) -> Alignment {
    match a {
        CmAlignment::None => Alignment::None,
        CmAlignment::Left => Alignment::Left,
        CmAlignment::Center => Alignment::Center,
        CmAlignment::Right => Alignment::Right,
    }
}

fn alert_kind(k: BlockQuoteKind) -> AlertKind {
    match k {
        BlockQuoteKind::Note => AlertKind::Note,
        BlockQuoteKind::Tip => AlertKind::Tip,
        BlockQuoteKind::Important => AlertKind::Important,
        BlockQuoteKind::Warning => AlertKind::Warning,
        BlockQuoteKind::Caution => AlertKind::Caution,
    }
}

/// Pulls `title:` out of YAML front matter without a YAML parser.
fn front_matter_title(fm: &str) -> Option<String> {
    fm.lines().find_map(|line| {
        let rest = line.strip_prefix("title:")?;
        let v = rest.trim().trim_matches(['"', '\'']).trim();
        (!v.is_empty()).then(|| v.to_string())
    })
}

fn first_h1(blocks: &[Block]) -> Option<String> {
    blocks.iter().find_map(|b| match b {
        Block::Heading {
            level: 1, content, ..
        } => Some(plain_text(content)),
        _ => None,
    })
}

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

    fn doc(src: &str) -> Document {
        parse(src, ParseOptions::default())
    }

    #[test]
    fn parses_headings_with_slugs() {
        let d = doc("# Hello World\n## Hello World\n");
        assert_eq!(d.blocks.len(), 2);
        match (&d.blocks[0], &d.blocks[1]) {
            (Block::Heading { id: a, .. }, Block::Heading { id: b, .. }) => {
                assert_eq!(a, "hello-world");
                assert_eq!(b, "hello-world-1", "duplicate headings must not collide");
            }
            other => panic!("unexpected {other:?}"),
        }
        assert_eq!(d.title.as_deref(), Some("Hello World"));
    }

    #[test]
    fn explicit_heading_ids_win() {
        let d = doc("# Title {#custom}\n");
        assert!(matches!(&d.blocks[0], Block::Heading { id, .. } if id == "custom"));
    }

    #[test]
    fn distinguishes_tight_and_loose_lists() {
        let tight = doc("- a\n- b\n");
        assert!(matches!(&tight.blocks[0], Block::List(l) if l.tight));

        let loose = doc("- a\n\n- b\n");
        assert!(matches!(&loose.blocks[0], Block::List(l) if !l.tight));
    }

    #[test]
    fn tight_items_still_carry_their_text() {
        let d = doc("- hello\n");
        let Block::List(list) = &d.blocks[0] else {
            panic!("expected list")
        };
        assert_eq!(list.items.len(), 1);
        assert_eq!(
            plain_text(match &list.items[0].blocks[0] {
                Block::Paragraph(p) => p,
                other => panic!("unexpected {other:?}"),
            }),
            "hello"
        );
    }

    #[test]
    fn parses_task_lists() {
        let d = doc("- [x] done\n- [ ] todo\n");
        let Block::List(list) = &d.blocks[0] else {
            panic!("expected list")
        };
        assert_eq!(list.items[0].task, Some(true));
        assert_eq!(list.items[1].task, Some(false));
    }

    #[test]
    fn parses_nested_lists() {
        let d = doc("- a\n  - b\n    - c\n");
        let Block::List(l1) = &d.blocks[0] else {
            panic!()
        };
        let Block::List(l2) = &l1.items[0].blocks[1] else {
            panic!("expected nested list")
        };
        assert!(matches!(&l2.items[0].blocks[1], Block::List(_)));
    }

    #[test]
    fn parses_tables_with_alignment() {
        let d = doc("| a | b |\n|:--|--:|\n| 1 | 2 |\n");
        let Block::Table(t) = &d.blocks[0] else {
            panic!("expected table")
        };
        assert_eq!(t.alignments, vec![Alignment::Left, Alignment::Right]);
        assert_eq!(t.head.len(), 2);
        assert_eq!(t.rows.len(), 1);
        assert_eq!(plain_text(&t.rows[0][1]), "2");
    }

    #[test]
    fn parses_github_alerts() {
        let d = doc("> [!WARNING]\n> Careful.\n");
        let Block::BlockQuote { kind, blocks } = &d.blocks[0] else {
            panic!("expected quote")
        };
        assert_eq!(*kind, Some(AlertKind::Warning));
        assert_eq!(blocks.len(), 1);
    }

    #[test]
    fn collects_footnotes_separately() {
        let d = doc("Text[^1]\n\n[^1]: The note.\n");
        assert_eq!(d.footnotes.len(), 1);
        assert_eq!(d.footnotes[0].0, "1");
        assert!(
            !d.blocks
                .iter()
                .any(|b| matches!(b, Block::FootnoteDefinition { .. }))
        );
    }

    #[test]
    fn code_blocks_keep_language_and_drop_trailing_newline() {
        let d = doc("```rust,ignore\nfn main() {}\n```\n");
        let Block::CodeBlock { language, code } = &d.blocks[0] else {
            panic!()
        };
        assert_eq!(language.as_deref(), Some("rust"));
        assert_eq!(code, "fn main() {}");
    }

    #[test]
    fn lone_images_become_figures() {
        let d = doc("![A cat](cat.png)\n");
        let Block::Figure { image, caption } = &d.blocks[0] else {
            panic!("expected figure")
        };
        assert_eq!(image.url, "cat.png");
        assert_eq!(plain_text(caption), "A cat");

        // ...but an image with text beside it stays inline.
        let d = doc("see ![A cat](cat.png) here\n");
        assert!(matches!(&d.blocks[0], Block::Paragraph(_)));
    }

    #[test]
    fn extracts_front_matter_and_title() {
        let d = doc("---\ntitle: From Front Matter\n---\n\n# Body\n");
        assert_eq!(d.title.as_deref(), Some("From Front Matter"));
        assert!(d.front_matter.as_deref().unwrap().contains("title:"));
    }

    #[test]
    fn html_images_survive() {
        let d = doc("<p align=\"center\"><img src=\"banner.png\" alt=\"Banner\"></p>\n");
        assert!(
            d.blocks
                .iter()
                .any(|b| matches!(b, Block::Figure { image, .. } if image.url == "banner.png")),
            "expected the HTML img to become a figure, got {:?}",
            d.blocks
        );
    }

    #[test]
    fn html_tags_split_across_lines_still_work() {
        // Regression: cmark emits an HTML block one line at a time, so this tag
        // reaches the parser in three pieces.
        let d = doc("<p>\n<img src=\n\"pic.png\"\n width=\"300px\">\n</p>\n");
        assert!(
            d.blocks
                .iter()
                .any(|b| matches!(b, Block::Figure { image, .. } if image.url == "pic.png")),
            "expected the image to survive being split: {:?}",
            d.blocks
        );
    }

    #[test]
    fn several_html_images_in_one_block_are_all_kept() {
        let d = doc("<p>\n<img src=\"a.png\">\n<img src=\"b.png\">\n</p>\n");
        let urls: Vec<&str> = d
            .blocks
            .iter()
            .filter_map(|b| match b {
                Block::Figure { image, .. } => Some(image.url.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(urls, vec!["a.png", "b.png"]);
    }

    #[test]
    fn parses_math() {
        let d = doc("Inline $x^2$ and\n\n$$\\int f$$\n");
        assert!(matches!(&d.blocks[1], Block::DisplayMath(_)));
    }

    #[test]
    fn parses_definition_lists() {
        let d = doc("Term\n\n: Definition here\n");
        assert!(matches!(&d.blocks[0], Block::DefinitionList(items) if items.len() == 1));
    }

    #[test]
    fn handles_truncated_input_without_losing_content() {
        let d = doc("> quote with no end\n\n- item");
        assert!(d.blocks.len() >= 2);
    }

    #[test]
    fn empty_input_yields_empty_document() {
        assert_eq!(doc(""), Document::default());
    }
}