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
//! End-to-end tests that run the built binary.
//!
//! These check the things unit tests cannot: argument handling, exit codes, what
//! reaches stdout versus stderr, and that piped output is clean.

use std::io::Write;
use std::process::{Command, Stdio};

/// Runs termmd with `args` and no stdin, returning (stdout, stderr, success).
fn run(args: &[&str]) -> (String, String, bool) {
    run_with_stdin(args, "")
}

fn run_with_stdin(args: &[&str], stdin: &str) -> (String, String, bool) {
    run_with_env(args, stdin, &[])
}

fn run_with_env(args: &[&str], stdin: &str, env: &[(&str, &str)]) -> (String, String, bool) {
    let mut child = Command::new(env!("CARGO_BIN_EXE_termmd"))
        .args(args)
        .envs(env.iter().copied())
        // A fixed environment keeps results the same on a developer's machine
        // and in CI, where TERM and friends differ wildly.
        .env_remove("TERM_PROGRAM")
        .env_remove("COLORTERM")
        .env_remove("KITTY_WINDOW_ID")
        .env_remove("TMUX")
        .env("TERM", "xterm-256color")
        .env("TERMMD_CONFIG", "/nonexistent/termmd.toml")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to run termmd");
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(stdin.as_bytes())
        .unwrap();
    let out = child.wait_with_output().unwrap();
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

fn fixture(name: &str) -> String {
    format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"))
}

#[test]
fn renders_a_file_to_stdout() {
    let (out, err, ok) = run(&["--width", "60", &fixture("sample.md")]);
    assert!(ok, "termmd failed: {err}");
    assert!(out.contains("Sample Document"));
    assert!(err.is_empty(), "unexpected stderr: {err}");
}

#[test]
fn reads_markdown_from_stdin() {
    let (out, _, ok) = run_with_stdin(&["--width", "40"], "# From stdin\n\nBody text.\n");
    assert!(ok);
    assert!(out.contains("From stdin"));
    assert!(out.contains("Body text."));
}

#[test]
fn a_dash_also_means_stdin() {
    let (out, _, ok) = run_with_stdin(&["-", "--width", "40"], "# Dash\n");
    assert!(ok);
    assert!(out.contains("Dash"));
}

#[test]
fn piped_output_carries_no_escape_sequences() {
    // stdout is a pipe here, so colour must be off without being asked.
    let (out, _, ok) = run(&["--width", "60", &fixture("sample.md")]);
    assert!(ok);
    assert!(
        !out.contains('\x1b'),
        "piped output should be plain: {out:?}"
    );
}

#[test]
fn colour_can_be_forced_through_a_pipe() {
    let (out, _, ok) = run(&[
        "--color",
        "truecolor",
        "--width",
        "60",
        &fixture("sample.md"),
    ]);
    assert!(ok);
    assert!(out.contains("\x1b[38;2;"), "expected truecolor sequences");
}

#[test]
fn plain_strips_everything() {
    let (out, _, ok) = run(&["--plain", "--color", "always", &fixture("sample.md")]);
    assert!(ok);
    assert!(!out.contains('\x1b'), "--plain must win over --color");
}

#[test]
fn width_is_respected() {
    for width in [40usize, 72] {
        let (out, _, ok) = run(&["--width", &width.to_string(), &fixture("sample.md")]);
        assert!(ok);
        for line in out.lines() {
            let columns = unicode_width::UnicodeWidthStr::width(line);
            assert!(
                columns <= width,
                "line exceeds width {width}: {line:?} ({columns})"
            );
        }
    }
}

#[test]
fn prints_a_table_of_contents() {
    let (out, _, ok) = run(&["--toc", &fixture("sample.md")]);
    assert!(ok);
    assert!(out.contains("Sample Document"));
    assert!(
        out.contains("#sample-document"),
        "anchors should be shown: {out}"
    );
    // The TOC is not the document.
    assert!(
        !out.contains("paragraph"),
        "TOC should list headings only: {out}"
    );
}

#[test]
fn the_table_of_contents_reads_as_the_page_does() {
    // A shortcode and a formula are expanded when the page is drawn, not when
    // it is parsed. The contents must follow the page, not the source.
    let heading = "# Launch :rocket: $x^2$\n\ntext\n";
    let utf8 = [("LANG", "C.UTF-8")];
    let (out, _, ok) = run_with_env(&["--toc", "-"], heading, &utf8);
    assert!(ok);
    assert!(out.contains("Launch 🚀 x²"), "{out}");
    // Under --ascii the page keeps the names, so the contents do too.
    let (out, _, ok) = run_with_env(&["--toc", "--ascii", "-"], heading, &utf8);
    assert!(ok);
    assert!(out.contains("Launch :rocket: x^2"), "{out}");
}

#[test]
fn reports_capabilities() {
    let (out, _, ok) = run(&["--caps"]);
    assert!(ok);
    for field in ["colour", "images", "hyperlinks", "theme", "width"] {
        assert!(out.contains(field), "--caps should report {field}: {out}");
    }
}

#[test]
fn lists_themes_and_languages() {
    let (out, _, ok) = run(&["--list-themes"]);
    assert!(ok);
    assert!(out.lines().count() > 5, "expected several themes");

    let (out, _, ok) = run(&["--list-languages"]);
    assert!(ok);
    assert!(out.contains("Rust"), "expected Rust among the languages");
}

#[test]
fn missing_files_fail_with_a_useful_message() {
    let (out, err, ok) = run(&["/no/such/file.md"]);
    assert!(!ok, "should exit non-zero");
    assert!(out.is_empty());
    assert!(
        err.contains("no/such/file.md"),
        "error should name the file: {err}"
    );
}

#[test]
fn an_unknown_theme_is_rejected() {
    let (_, err, ok) = run(&["--theme", "no-such-theme", &fixture("sample.md")]);
    assert!(!ok);
    assert!(err.contains("no-such-theme"));
}

#[test]
fn several_files_are_concatenated_and_labelled() {
    // Run from the fixtures directory and name the files relatively. The label
    // echoes the path as typed, so an absolute path on a deep checkout wraps
    // mid-filename at this width -- which says nothing about the behaviour
    // under test, but does make the test fail on some machines and not others.
    let dir = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures");
    let (out, err, ok) = run_in(&dir, &["--width", "60", "sample.md", "second.md"]);
    assert!(ok, "stderr: {err}");
    assert!(out.contains("Sample Document"));
    assert!(out.contains("Second Document"));
    assert!(
        out.contains("second.md"),
        "each file should be labelled: {out}"
    );
}

#[test]
fn tables_are_drawn_within_the_width() {
    let (out, _, ok) = run(&["--width", "50", &fixture("sample.md")]);
    assert!(ok);
    assert!(
        out.contains('│') || out.contains('|'),
        "expected a table: {out}"
    );
    let table_rows: Vec<&str> = out.lines().filter(|l| l.contains('│')).collect();
    assert!(table_rows.len() >= 3, "expected several table rows");
    let widths: Vec<usize> = table_rows
        .iter()
        .map(|l| unicode_width::UnicodeWidthStr::width(*l))
        .collect();
    assert!(
        widths.windows(2).all(|w| w[0] == w[1]),
        "table rows are ragged: {widths:?}"
    );
}

#[test]
fn images_become_placeholders_when_no_protocol_is_available() {
    let (out, _, ok) = run(&["--images", "none", "--width", "60", &fixture("sample.md")]);
    assert!(ok);
    assert!(
        out.contains("A picture"),
        "the alt text should survive: {out}"
    );
}

#[test]
fn remote_images_are_refused_by_default() {
    let markdown = "![remote](https://example.invalid/nope.png)\n";
    let (out, _, ok) = run_with_stdin(&["--images", "kitty", "--width", "40"], markdown);
    assert!(ok, "a remote image must not be a fatal error");
    assert!(out.contains("remote"), "should fall back to the alt text");
}

#[test]
fn the_pager_refuses_to_run_without_a_terminal() {
    // `--pager` is a request for the pager whatever the document's length, so
    // this must fail rather than quietly printing a short file. Windows
    // consoles report a size even with stdout redirected, which is how the
    // shortcut used to swallow this.
    let (_, err, ok) = run(&["--pager", &fixture("sample.md")]);
    assert!(!ok);
    assert!(err.contains("terminal"), "should explain why: {err}");
}

#[test]
fn empty_input_is_not_an_error() {
    let (out, err, ok) = run_with_stdin(&[], "");
    assert!(ok, "stderr: {err}");
    assert!(out.trim().is_empty());
}

#[test]
fn help_and_version_work() {
    let (out, _, ok) = run(&["--help"]);
    assert!(ok);
    assert!(out.contains("--width"));
    assert!(
        out.contains("--caps"),
        "the help should mention the diagnostic flag"
    );

    let (out, _, ok) = run(&["--version"]);
    assert!(ok);
    assert!(out.contains(env!("CARGO_PKG_VERSION")));
}

/// A 16x8 PNG, embedded so the tests need no binary fixtures on disk.
const TINY_PNG: &[u8] = &[
    0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52,
    0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x08, 0x08, 0x02, 0x00, 0x00, 0x00, 0x7f, 0x14, 0xe8,
    0xc0, 0x00, 0x00, 0x00, 0x17, 0x49, 0x44, 0x41, 0x54, 0x78, 0xda, 0x63, 0x3c, 0x11, 0xa0, 0xc1,
    0x40, 0x0a, 0x60, 0x62, 0x20, 0x11, 0x8c, 0x6a, 0x20, 0x06, 0x00, 0x00, 0xf5, 0xf7, 0x01, 0x50,
    0x0f, 0x2c, 0x93, 0x87, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
];

/// Runs termmd from a given working directory.
fn run_in(dir: &std::path::Path, args: &[&str]) -> (String, String, bool) {
    let out = Command::new(env!("CARGO_BIN_EXE_termmd"))
        .args(args)
        .current_dir(dir)
        .env_remove("TERM_PROGRAM")
        .env_remove("COLORTERM")
        .env("TERM", "xterm-256color")
        .env("TERMMD_CONFIG", "/nonexistent/termmd.toml")
        .stdin(Stdio::null())
        .output()
        .expect("failed to run termmd");
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.success(),
    )
}

/// Builds `<tmp>/<name>/doc/page.md` next to `<tmp>/<name>/doc/images/pic.png`.
fn image_tree(name: &str) -> std::path::PathBuf {
    let root = std::env::temp_dir().join(name);
    let _ = std::fs::remove_dir_all(&root);
    std::fs::create_dir_all(root.join("doc/images")).unwrap();
    std::fs::write(root.join("doc/images/pic.png"), TINY_PNG).unwrap();
    std::fs::write(
        root.join("doc/page.md"),
        "# Page\n\n![The picture](images/pic.png)\n",
    )
    .unwrap();
    root
}

#[test]
fn a_relative_image_resolves_against_the_document_not_the_shell() {
    // Regression: the image URL is rebased against the document's directory at
    // parse time, and was then joined with a base directory a second time, so
    // `doc/images/pic.png` was looked for at `doc/doc/images/pic.png` and every
    // image silently became a placeholder. Only absolute paths worked.
    let root = image_tree("termmd-relative-image");
    let (out, err, ok) = run_in(&root, &["--images", "kitty", "-P", "doc/page.md"]);
    assert!(ok, "stderr: {err}");
    assert!(
        out.contains("\x1b_G"),
        "expected a kitty image sequence, got a placeholder instead:\n{out}"
    );
}

#[test]
fn images_resolve_the_same_way_from_any_directory() {
    let root = image_tree("termmd-image-cwd");
    let absolute = root.join("doc/page.md");

    // From the repository root, from inside the document's directory, and by
    // absolute path: all three must find the same picture.
    let cases: Vec<(std::path::PathBuf, String)> = vec![
        (root.clone(), "doc/page.md".to_string()),
        (root.join("doc"), "page.md".to_string()),
        (std::env::temp_dir(), absolute.display().to_string()),
    ];
    for (dir, arg) in cases {
        let (out, err, ok) = run_in(&dir, &["--images", "kitty", "-P", &arg]);
        assert!(ok, "stderr: {err}");
        assert!(
            out.contains("\x1b_G"),
            "no image when run from {} with {arg}:\n{out}",
            dir.display()
        );
    }
}

#[test]
fn a_missing_image_still_shows_its_alt_text() {
    let root = image_tree("termmd-missing-image");
    std::fs::remove_file(root.join("doc/images/pic.png")).unwrap();
    let (out, _, ok) = run_in(&root, &["--images", "kitty", "-P", "doc/page.md"]);
    assert!(ok);
    assert!(
        out.contains("The picture"),
        "alt text should survive: {out}"
    );
}

#[test]
fn local_document_links_are_emitted_as_file_uris() {
    let root = image_tree("termmd-file-uri");
    std::fs::write(root.join("doc/other.md"), "# Other\n").unwrap();
    std::fs::write(root.join("doc/page.md"), "[see other](other.md)\n").unwrap();
    let (out, _, ok) = run_in(
        &root,
        &[
            "--links",
            "hyperlink",
            "--color",
            "always",
            "-P",
            "doc/page.md",
        ],
    );
    assert!(ok);
    assert!(
        out.contains("\x1b]8;;file:///"),
        "expected a file:// hyperlink:\n{out}"
    );
}

#[test]
fn writes_completion_scripts() {
    for (shell, marker) in [
        ("bash", "_termmd()"),
        ("zsh", "#compdef termmd"),
        ("fish", "complete -c termmd"),
        ("elvish", "termmd"),
        ("powershell", "termmd"),
    ] {
        let (out, err, ok) = run(&["--completions", shell]);
        assert!(ok, "--completions {shell} failed: {err}");
        assert!(
            out.contains(marker),
            "the {shell} script should contain {marker:?}: {out}"
        );
        // A completion script is redirected into a file, so a stray escape
        // sequence from the capability probe would be written into it.
        assert!(
            !out.contains('\x1b'),
            "the {shell} script carries an escape sequence"
        );
        // Generated from the parser itself, so a flag added without touching
        // this test still turns up. Named without its dashes, because fish
        // spells a long option `-l remote-images`.
        assert!(
            out.contains("remote-images"),
            "the {shell} script is missing a flag termmd accepts"
        );
    }

    let (_, err, ok) = run(&["--completions", "tcsh"]);
    assert!(!ok, "an unsupported shell should be an error");
    assert!(
        err.contains("tcsh"),
        "the error should name the shell: {err}"
    );
}

#[test]
fn writes_a_man_page() {
    let (out, err, ok) = run(&["--man"]);
    assert!(ok, "--man failed: {err}");
    assert!(out.starts_with(".ie"), "roff starts with its own preamble");
    for section in [".TH termmd 1", ".SH NAME", ".SH SYNOPSIS", ".SH OPTIONS"] {
        assert!(
            out.contains(section),
            "the man page has no {section}: {out}"
        );
    }
    // The hand-written sections, which clap knows nothing about.
    assert!(out.contains(".SH FILES") && out.contains("config.toml"));
    assert!(
        !out.contains('\x1b'),
        "the man page carries an escape sequence"
    );
    assert!(
        out.contains("--remote-images"),
        "the man page is missing a flag termmd accepts"
    );
}

#[test]
fn prints_front_matter_when_asked() {
    let (out, _, ok) = run(&["--front-matter", &fixture("front-matter.md")]);
    assert!(ok);
    assert!(out.contains("title: Fixture with front matter"), "{out}");
    assert!(out.contains("tags: [one, two]"), "{out}");
    assert!(
        !out.contains("Body text"),
        "the document itself is not it: {out}"
    );

    // It stays out of the rendered page, where it is not content.
    let (page, _, ok) = run(&["-P", &fixture("front-matter.md")]);
    assert!(ok);
    assert!(page.contains("Body text"));
    assert!(!page.contains("tags:"), "{page}");

    // A document without any is not an error, it is an empty answer.
    let (out, err, ok) = run(&["--front-matter", &fixture("sample.md")]);
    assert!(ok, "{err}");
    assert!(out.trim().is_empty(), "{out}");
}

#[test]
fn front_matter_is_printed_for_every_file_given() {
    // Several files: each block is introduced by a `---` line naming its file,
    // which is a YAML document marker plus a comment, so the output is still
    // one YAML stream. A file without any contributes nothing, not a header.
    let with = fixture("front-matter.md");
    let (out, err, ok) = run(&["--front-matter", &with, &fixture("sample.md"), &with]);
    assert!(ok, "{err}");
    let markers: Vec<&str> = out.lines().filter(|l| l.starts_with("--- # ")).collect();
    assert_eq!(markers.len(), 2, "{out}");
    assert!(markers[0].ends_with("front-matter.md"), "{out}");
    assert_eq!(
        out.matches("title: Fixture with front matter").count(),
        2,
        "{out}"
    );
    assert!(!out.contains("sample.md"), "{out}");

    // One file, as before: no marker, just the front matter.
    let (out, _, _) = run(&["--front-matter", &with]);
    assert!(!out.contains("--- #"), "{out}");
}

#[test]
fn a_directory_is_rendered_as_an_index_of_its_markdown() {
    let dir = std::env::temp_dir().join("termmd-cli-directory");
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("guides")).unwrap();
    std::fs::write(dir.join("README.md"), "# The Readme\n\nBody.\n").unwrap();
    std::fs::write(dir.join("notes.md"), "# Some Notes\n").unwrap();
    std::fs::write(dir.join("photo.png"), "not markdown").unwrap();
    std::fs::write(dir.join("guides/one.md"), "# One\n").unwrap();

    let (out, err, ok) = run(&["-P", "--width", "70", dir.to_str().unwrap()]);
    assert!(ok, "{err}");
    assert!(out.contains("README.md"), "{out}");
    assert!(
        out.contains("The Readme"),
        "the heading says what it is: {out}"
    );
    assert!(out.contains("Some Notes"), "{out}");
    assert!(
        out.contains("guides/"),
        "a directory with Markdown in it: {out}"
    );
    assert!(!out.contains("photo.png"), "not Markdown: {out}");
    // The index is a document about the directory, not the documents in it.
    assert!(!out.contains("Body."), "{out}");
}

#[test]
fn a_url_that_is_not_a_url_is_still_a_path() {
    // The error has to name what was actually looked for, or a typo in a URL
    // reads as a mysteriously missing file.
    let (_, err, ok) = run(&["/no/such/directory/at/all"]);
    assert!(!ok);
    assert!(err.contains("/no/such/directory/at/all"), "{err}");
}

#[test]
fn a_closed_pipe_is_not_an_error() {
    // `termmd big.md | head` is an ordinary thing to type, and it used to end
    // with "termmd: Broken pipe (os error 32)" and a non-zero exit.
    let path = std::env::temp_dir().join("termmd-cli-broken-pipe.md");
    let big: String = (0..4000)
        .map(|i| format!("## Section {i}\n\nSome text in section {i}.\n\n"))
        .collect();
    std::fs::write(&path, big).unwrap();

    let mut child = Command::new(env!("CARGO_BIN_EXE_termmd"))
        .args(["-P", "--width", "60", path.to_str().unwrap()])
        .env("TERM", "xterm-256color")
        .env("TERMMD_CONFIG", "/nonexistent/termmd.toml")
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("failed to run termmd");

    // The reader goes away with the document half written.
    drop(child.stdout.take());
    let out = child.wait_with_output().unwrap();

    let err = String::from_utf8_lossy(&out.stderr);
    assert!(err.is_empty(), "nothing to report: {err}");
    assert!(out.status.success(), "and nothing to fail about");
}