termmd 0.1.4

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
//! The document tree.
//!
//! `pulldown-cmark` hands us a flat event stream, which is ideal for streaming
//! to HTML and awkward for laying out a terminal page: to wrap a table column or
//! indent a nested list we need to know the whole subtree first. So the parser
//! folds events into this tree once, and every later stage works on it.

use std::borrow::Cow;

/// A parsed document plus the bits of metadata worth keeping.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Document {
    pub blocks: Vec<Block>,
    /// Footnote bodies, in first-reference order.
    pub footnotes: Vec<(String, Vec<Block>)>,
    /// Title from YAML front matter, or the first level-1 heading.
    pub title: Option<String>,
    /// Raw front matter, kept so the CLI can expose it.
    pub front_matter: Option<String>,
}

impl Document {
    /// Headings in document order, for the table of contents.
    pub fn headings(&self) -> Vec<(u8, String, String)> {
        self.headings_by(&|_, s| Cow::Borrowed(s))
    }

    /// Headings with their text flattened by `leaf`, so a table of contents
    /// can show a heading the way the page draws it -- see [`plain_text_by`].
    pub fn headings_by(&self, leaf: &LeafText<'_>) -> Vec<(u8, String, String)> {
        let mut out = Vec::new();
        collect_headings(&self.blocks, leaf, &mut out);
        out
    }
}

fn collect_headings(blocks: &[Block], leaf: &LeafText<'_>, out: &mut Vec<(u8, String, String)>) {
    for b in blocks {
        match b {
            Block::Heading { level, id, content } => {
                out.push((*level, plain_text_by(content, leaf), id.clone()));
            }
            Block::BlockQuote { blocks, .. } => collect_headings(blocks, leaf, out),
            Block::List(list) => {
                for item in &list.items {
                    collect_headings(&item.blocks, leaf, out);
                }
            }
            _ => {}
        }
    }
}

/// The kinds of text an inline tree bottoms out in. What a renderer does to
/// each differs: a shortcode in prose becomes an emoji, the same characters
/// in a code span stay as typed, and TeX becomes Unicode.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Leaf {
    Text,
    Code,
    Math,
}

/// How to turn a leaf's text into what should stand for it.
pub type LeafText<'l> = dyn for<'a> Fn(Leaf, &'a str) -> Cow<'a, str> + 'l;

/// Flattens inline content to plain text, for slugs, titles and search.
pub fn plain_text(inlines: &[Inline]) -> String {
    plain_text_by(inlines, &|_, s| Cow::Borrowed(s))
}

/// Flattens inline content, letting `leaf` say what each piece of text
/// becomes. `plain_text` is this with the identity.
pub fn plain_text_by(inlines: &[Inline], leaf: &LeafText<'_>) -> String {
    let mut s = String::new();
    push_plain(inlines, leaf, &mut s);
    s
}

fn push_plain(inlines: &[Inline], leaf: &LeafText<'_>, out: &mut String) {
    for i in inlines {
        match i {
            Inline::Text(t) => out.push_str(&leaf(Leaf::Text, t)),
            Inline::Code(t) => out.push_str(&leaf(Leaf::Code, t)),
            Inline::Math { text, .. } => out.push_str(&leaf(Leaf::Math, text)),
            Inline::Emph(c) | Inline::Strong(c) | Inline::Strike(c) => push_plain(c, leaf, out),
            Inline::Superscript(c) | Inline::Subscript(c) => push_plain(c, leaf, out),
            Inline::Link { content, .. } => push_plain(content, leaf, out),
            Inline::Image(img) => out.push_str(&img.alt),
            Inline::SoftBreak | Inline::HardBreak => out.push(' '),
            Inline::FootnoteRef(label) => {
                out.push('[');
                out.push_str(label);
                out.push(']');
            }
            Inline::Html(_) => {}
        }
    }
}

/// A block-level element.
#[derive(Debug, Clone, PartialEq)]
pub enum Block {
    Heading {
        level: u8,
        id: String,
        content: Inlines,
    },
    Paragraph(Inlines),
    CodeBlock {
        language: Option<String>,
        code: String,
    },
    /// A quote, or one of GitHub's alert callouts when `kind` is set.
    BlockQuote {
        kind: Option<AlertKind>,
        blocks: Vec<Block>,
    },
    List(List),
    Table(Table),
    /// A paragraph whose only content is an image, which we can render large.
    Figure {
        image: ImageRef,
        caption: Inlines,
    },
    Rule,
    /// Raw HTML we choose to show rather than silently drop.
    Html(String),
    /// `$$ ... $$`
    DisplayMath(String),
    /// Terms and their definitions.
    DefinitionList(Vec<(Inlines, Vec<Vec<Block>>)>),
    /// A footnote body, rendered at the end of the document.
    FootnoteDefinition {
        label: String,
        blocks: Vec<Block>,
    },
}

/// GitHub's alert callouts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertKind {
    Note,
    Tip,
    Important,
    Warning,
    Caution,
}

impl AlertKind {
    pub fn label(self) -> &'static str {
        match self {
            Self::Note => "NOTE",
            Self::Tip => "TIP",
            Self::Important => "IMPORTANT",
            Self::Warning => "WARNING",
            Self::Caution => "CAUTION",
        }
    }
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct List {
    /// `Some(start)` for ordered lists.
    pub start: Option<u64>,
    /// Tight lists set their items solid; loose lists get blank lines between.
    pub tight: bool,
    pub items: Vec<ListItem>,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct ListItem {
    /// `Some(checked)` when this is a task list item.
    pub task: Option<bool>,
    pub blocks: Vec<Block>,
}

#[derive(Debug, Clone, PartialEq, Default)]
pub struct Table {
    pub alignments: Vec<Alignment>,
    pub head: Vec<Cell>,
    pub rows: Vec<Vec<Cell>>,
}

/// Cell contents; a cell is inline-only in GFM.
pub type Cell = Inlines;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Alignment {
    #[default]
    None,
    Left,
    Center,
    Right,
}

pub type Inlines = Vec<Inline>;

#[derive(Debug, Clone, PartialEq)]
pub enum Inline {
    Text(String),
    Code(String),
    Emph(Inlines),
    Strong(Inlines),
    Strike(Inlines),
    Superscript(Inlines),
    Subscript(Inlines),
    Link {
        dest: String,
        title: Option<String>,
        content: Inlines,
    },
    Image(ImageRef),
    SoftBreak,
    HardBreak,
    FootnoteRef(String),
    Math {
        text: String,
        display: bool,
    },
    Html(String),
}

/// A reference to an image, before we have gone looking for the bytes.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct ImageRef {
    pub url: String,
    pub alt: String,
    pub title: Option<String>,
}

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

    #[test]
    fn plain_text_flattens_nested_inlines() {
        let inlines = vec![
            Inline::Text("a ".into()),
            Inline::Strong(vec![Inline::Emph(vec![Inline::Text("b".into())])]),
            Inline::SoftBreak,
            Inline::Code("c".into()),
        ];
        assert_eq!(plain_text(&inlines), "a b c");
    }

    #[test]
    fn headings_are_collected_in_document_order() {
        let doc = Document {
            blocks: vec![
                Block::Heading {
                    level: 1,
                    id: "one".into(),
                    content: vec![Inline::Text("One".into())],
                },
                Block::BlockQuote {
                    kind: None,
                    blocks: vec![Block::Heading {
                        level: 2,
                        id: "two".into(),
                        content: vec![Inline::Text("Two".into())],
                    }],
                },
            ],
            ..Default::default()
        };
        let h = doc.headings();
        assert_eq!(h.len(), 2);
        assert_eq!(h[0], (1, "One".to_string(), "one".to_string()));
        assert_eq!(h[1].0, 2);
    }
}

/// Rewrites relative image and link URLs so they resolve against `base`.
///
/// Done once after parsing, which means later stages never need to know which
/// file a node came from -- and a document assembled from several files keeps
/// each part's own idea of where `./diagram.png` lives.
/// What a document's relative URLs resolve against.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UrlBase<'a> {
    /// A document read from the file system.
    Dir(&'a std::path::Path),
    /// A document fetched over HTTP, whose own URL is the base.
    Url(&'a str),
}

pub fn rebase_urls(doc: &mut Document, base: UrlBase<'_>) {
    rebase_blocks(&mut doc.blocks, base);
    for (_, blocks) in &mut doc.footnotes {
        rebase_blocks(blocks, base);
    }
}

fn rebase_blocks(blocks: &mut [Block], base: UrlBase<'_>) {
    for block in blocks {
        match block {
            Block::Heading { content, .. } | Block::Paragraph(content) => {
                rebase_inlines(content, base)
            }
            Block::BlockQuote { blocks, .. } | Block::FootnoteDefinition { blocks, .. } => {
                rebase_blocks(blocks, base)
            }
            Block::List(list) => {
                for item in &mut list.items {
                    rebase_blocks(&mut item.blocks, base);
                }
            }
            Block::Table(table) => {
                for cell in table.head.iter_mut().chain(table.rows.iter_mut().flatten()) {
                    rebase_inlines(cell, base);
                }
            }
            Block::Figure { image, caption } => {
                rebase_url(&mut image.url, base);
                rebase_inlines(caption, base);
            }
            Block::DefinitionList(items) => {
                for (term, defs) in items {
                    rebase_inlines(term, base);
                    for blocks in defs {
                        rebase_blocks(blocks, base);
                    }
                }
            }
            Block::CodeBlock { .. } | Block::Rule | Block::Html(_) | Block::DisplayMath(_) => {}
        }
    }
}

fn rebase_inlines(inlines: &mut [Inline], base: UrlBase<'_>) {
    for inline in inlines {
        match inline {
            Inline::Image(img) => rebase_url(&mut img.url, base),
            Inline::Link { dest, content, .. } => {
                rebase_url(dest, base);
                rebase_inlines(content, base);
            }
            Inline::Emph(c) | Inline::Strong(c) | Inline::Strike(c) => rebase_inlines(c, base),
            Inline::Superscript(c) | Inline::Subscript(c) => rebase_inlines(c, base),
            _ => {}
        }
    }
}

/// Resolves one relative URL against the document's directory.
///
/// The result is an absolute path. That matters more than it looks: later
/// stages resolve paths too, and a relative result can be joined a second time
/// against a different base, quietly turning `doc/x.png` into `doc/doc/x.png`.
/// An absolute path cannot be re-based by accident.
fn rebase_url(url: &mut String, base: UrlBase<'_>) {
    // Fragments and anything carrying a scheme of its own stay as they are.
    if url.is_empty()
        || url.starts_with('#')
        || url.starts_with("data:")
        || url.split_once("://").is_some()
        || url.split_once(':').is_some_and(|(scheme, _)| {
            !scheme.is_empty()
                && scheme
                    .chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-')
        })
    {
        return;
    }
    match base {
        UrlBase::Dir(dir) => {
            // A leading slash is already an absolute path on this filesystem.
            // Against a URL it means something else entirely -- the root of the
            // host -- which is why this test belongs here and not above.
            if url.starts_with('/') {
                return;
            }
            let joined = dir.join(&*url);
            let absolute = std::path::absolute(&joined).unwrap_or(joined);
            if let Some(s) = absolute.to_str() {
                *url = s.to_string();
            }
        }
        UrlBase::Url(document) => {
            if let Some(joined) = join_url(document, url) {
                *url = joined;
            }
        }
    }
}

/// Resolves a relative reference against the URL of the document holding it.
///
/// Enough of RFC 3986 to be right about what a README contains: an absolute
/// path, a path relative to the document, and the `..` segments people write
/// when a repository's images live one directory up.
fn join_url(document: &str, relative: &str) -> Option<String> {
    let (scheme, rest) = document.split_once("://")?;
    // The base's own query and fragment are not part of the path.
    let rest = rest.split(['?', '#']).next().unwrap_or(rest);
    let (authority, path) = match rest.split_once('/') {
        Some((authority, path)) => (authority, path),
        None => (rest, ""),
    };

    // `//host/path` names its own host and keeps only the scheme.
    if let Some(rest) = relative.strip_prefix("//") {
        return Some(format!("{scheme}://{rest}"));
    }
    let joined = if let Some(absolute) = relative.strip_prefix('/') {
        absolute.to_string()
    } else {
        // Relative to the directory the document is in, not to the document.
        let dir = match path.rsplit_once('/') {
            Some((dir, _)) => dir,
            None => "",
        };
        if dir.is_empty() {
            relative.to_string()
        } else {
            format!("{dir}/{relative}")
        }
    };

    let mut segments: Vec<&str> = Vec::new();
    for segment in joined.split('/') {
        match segment {
            "." | "" => {}
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }
    // A trailing slash means a directory, and dropping it changes the meaning.
    let trailing = if joined.ends_with('/') { "/" } else { "" };
    Some(format!(
        "{scheme}://{authority}/{}{trailing}",
        segments.join("/")
    ))
}

#[cfg(test)]
mod rebase_tests {
    use super::*;
    use std::path::{Path, PathBuf};

    /// An absolute directory for whatever platform this is: on Windows a path
    /// needs a drive letter to count as absolute, so `/docs` will not do.
    fn base() -> PathBuf {
        std::path::absolute("docs").expect("a working directory")
    }

    #[test]
    fn a_remote_documents_relative_urls_resolve_against_it() {
        let doc = UrlBase::Url("https://example.com/repo/docs/README.md");
        assert_eq!(
            rebase_against(doc, "img.png"),
            "https://example.com/repo/docs/img.png"
        );
        assert_eq!(
            rebase_against(doc, "./img.png"),
            "https://example.com/repo/docs/img.png"
        );
        assert_eq!(
            rebase_against(doc, "../img.png"),
            "https://example.com/repo/img.png"
        );
        assert_eq!(
            rebase_against(doc, "../../img.png"),
            "https://example.com/img.png"
        );
        // Above the root is still the root, not an error.
        assert_eq!(
            rebase_against(doc, "../../../../img.png"),
            "https://example.com/img.png"
        );
        assert_eq!(
            rebase_against(doc, "/img.png"),
            "https://example.com/img.png"
        );
        assert_eq!(
            rebase_against(doc, "sub/img.png"),
            "https://example.com/repo/docs/sub/img.png"
        );
    }

    #[test]
    fn a_remote_base_ignores_its_own_query_and_fragment() {
        let doc = UrlBase::Url("https://example.com/a/b.md?raw=1#top");
        assert_eq!(rebase_against(doc, "c.png"), "https://example.com/a/c.png");
        // The relative reference keeps its own, which is how raw hosts work.
        assert_eq!(
            rebase_against(doc, "c.png?raw=1"),
            "https://example.com/a/c.png?raw=1"
        );
    }

    #[test]
    fn a_remote_base_with_no_path_still_works() {
        assert_eq!(
            rebase_against(UrlBase::Url("https://example.com"), "a.png"),
            "https://example.com/a.png"
        );
        assert_eq!(
            rebase_against(UrlBase::Url("https://example.com/"), "a.png"),
            "https://example.com/a.png"
        );
        assert_eq!(
            rebase_against(UrlBase::Url("https://example.com/dir/"), "a.png"),
            "https://example.com/dir/a.png"
        );
    }

    #[test]
    fn a_protocol_relative_url_keeps_its_host() {
        assert_eq!(
            rebase_against(
                UrlBase::Url("https://example.com/a/b.md"),
                "//cdn.example/x.png"
            ),
            "https://cdn.example/x.png"
        );
    }

    fn url_after_rebase(url: &str) -> String {
        rebase_from(&base(), url)
    }

    fn rebase_from(base: &Path, url: &str) -> String {
        rebase_against(UrlBase::Dir(base), url)
    }

    fn rebase_against(base: UrlBase<'_>, url: &str) -> String {
        let mut doc = Document {
            blocks: vec![Block::Figure {
                image: ImageRef {
                    url: url.into(),
                    ..Default::default()
                },
                caption: Vec::new(),
            }],
            ..Default::default()
        };
        rebase_urls(&mut doc, base);
        match &doc.blocks[0] {
            Block::Figure { image, .. } => image.url.clone(),
            _ => unreachable!(),
        }
    }

    #[test]
    fn makes_relative_paths_absolute() {
        // Compared as paths, not strings, so the separator does not matter.
        assert_eq!(
            Path::new(&url_after_rebase("img/logo.png")),
            base().join("img/logo.png")
        );
        assert_eq!(
            Path::new(&url_after_rebase("./logo.png")),
            base().join("logo.png")
        );
    }

    #[test]
    fn leaves_everything_else_alone() {
        for url in [
            "https://example.com/a.png",
            "http://example.com/a.png",
            "/absolute/a.png",
            "data:image/png;base64,AAAA",
            "#anchor",
            "mailto:someone@example.com",
        ] {
            assert_eq!(url_after_rebase(url), url, "{url} should not be rebased");
        }
    }

    #[test]
    fn a_relative_base_still_yields_an_absolute_path() {
        // The guard against a second base being applied further down the line.
        let url = rebase_from(Path::new("doc"), "images/x.png");
        let path = Path::new(&url);
        assert!(path.is_absolute(), "got {url}");
        assert!(path.ends_with("doc/images/x.png"), "got {url}");
    }

    #[test]
    fn rebases_inside_nested_blocks() {
        let mut doc = Document {
            blocks: vec![Block::BlockQuote {
                kind: None,
                blocks: vec![Block::Paragraph(vec![Inline::Link {
                    dest: "other.md".into(),
                    title: None,
                    content: vec![Inline::Text("x".into())],
                }])],
            }],
            ..Default::default()
        };
        rebase_urls(&mut doc, UrlBase::Dir(&base()));
        let Block::BlockQuote { blocks, .. } = &doc.blocks[0] else {
            panic!()
        };
        let Block::Paragraph(inlines) = &blocks[0] else {
            panic!()
        };
        let Inline::Link { dest, .. } = &inlines[0] else {
            panic!("expected a link")
        };
        assert_eq!(Path::new(dest), base().join("other.md"));
    }
}