markdown-viewer-rs 0.8.0

Render a Markdown file with GitHub styling and live-reload it in your browser
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
use crate::platform::Canonical;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::io::{Read as _, Write as _};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Duration;

use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser};

mod browser;
mod codeblocks;
mod config;
mod desktop;
mod docs;
mod editor;
#[cfg(target_os = "macos")]
mod finder;
mod frontmatter;
mod gitdiff;
mod github;
mod instances;
mod links;
mod lint;
mod obsidian;
mod pdf;
mod platform;
mod recent;
mod references;
mod render;
mod server;
mod site;
mod tables;
mod tasks;
mod theme;
mod toc;

use config::{Config, Prefs};
use render::{FrontMatter, PageOptions, RenderOptions, Renderer, Style, Theme};

/// Render Markdown with GitHub styling and view it in your browser.
#[derive(Debug, Parser)]
#[command(name = "markdown-viewer", version, about)]
struct Cli {
    /// Markdown file to render, a folder to browse (default: the current
    /// folder), or "-" to read standard input. Folders are always served
    /// with live reload.
    file: Option<PathBuf>,

    /// Serve the page and live-reload it whenever the file changes.
    #[arg(short, long)]
    watch: bool,

    /// Write the rendered HTML to this file ("-" for stdout) instead of
    /// opening it. For a folder, write a static site into this folder.
    #[arg(short, long, value_name = "PATH", conflicts_with_all = ["watch", "pdf"])]
    output: Option<PathBuf>,

    /// Write a PDF to this file instead of opening it (needs Chrome,
    /// Chromium, Edge, Brave or Vivaldi).
    #[arg(long, value_name = "PATH", conflicts_with = "watch")]
    pdf: Option<PathBuf>,

    /// Preview the clipboard instead of a file. With --watch, the page
    /// follows the clipboard as it changes.
    #[arg(long, conflicts_with = "file")]
    clipboard: bool,

    /// Scroll a running viewer to FILE:LINE, starting one if needed. For
    /// editor commands (see editors/ in the repository).
    #[arg(long, value_name = "FILE:LINE", conflicts_with_all = ["file", "clipboard", "output", "pdf"])]
    goto: Option<String>,

    /// With --goto: do nothing if no viewer is showing the file (for
    /// editors following the cursor, so a closed preview stays closed).
    #[arg(long, requires = "goto")]
    if_running: bool,

    /// Check links and images in FILE (or every Markdown file in a folder)
    /// and report broken ones; exits with status 1 if any are.
    #[arg(long, conflicts_with_all = ["watch", "output", "pdf", "clipboard", "goto"])]
    check_links: bool,

    /// Show the files and folders you opened recently (also what you get
    /// with no FILE in your home folder).
    #[arg(long, conflicts_with_all = ["file", "clipboard", "goto", "output", "pdf", "check_links", "lint"])]
    recent: bool,

    /// With --check-links: also check web links (needs curl).
    #[arg(long, requires = "check_links")]
    online: bool,

    /// Report writing problems in FILE (or every Markdown file in a
    /// folder): skipped heading levels, images without alt text, empty
    /// links and more; exits with status 1 if there are any. Combines with
    /// --check-links.
    #[arg(long, conflicts_with_all = ["watch", "output", "pdf", "clipboard", "goto"])]
    lint: bool,

    /// Port for --watch (default: any free port).
    #[arg(short, long)]
    port: Option<u16>,

    /// Don't open a browser.
    #[arg(long)]
    no_open: bool,

    /// Browser to open instead of the default (e.g. "Google Chrome", "firefox").
    #[arg(long, value_name = "NAME")]
    browser: Option<String>,

    /// Open as a minimal app window with no tabs or address bar (default).
    /// Chrome, Edge, Brave, Chromium and Vivaldi only; other browsers get
    /// a new window.
    #[arg(long, group = "open_as")]
    app: bool,

    /// Open in a normal new browser window.
    #[arg(long, group = "open_as")]
    window: bool,

    /// Open in a tab of an existing browser window.
    #[arg(long, group = "open_as")]
    tab: bool,

    /// With --watch: exit once the page has been closed (used by the Finder
    /// integration, where there's no terminal to press Ctrl-C in).
    #[arg(long)]
    exit_when_closed: bool,

    /// macOS: add "Markdown Viewer" to Finder (Open With, double-click and a
    /// right-click Quick Action) for the current user.
    #[arg(long, exclusive = true, hide = !cfg!(target_os = "macos"))]
    install_finder: bool,

    /// macOS: remove the Finder integration.
    #[arg(long, exclusive = true, hide = !cfg!(target_os = "macos"))]
    uninstall_finder: bool,

    /// Linux: add "Markdown Viewer" to your desktop's applications, for
    /// Open With on Markdown, CSV and TSV files (current user only).
    #[arg(long, exclusive = true, hide = cfg!(any(target_os = "macos", windows)))]
    install_desktop: bool,

    /// Linux: remove the desktop integration.
    #[arg(long, exclusive = true, hide = cfg!(any(target_os = "macos", windows)))]
    uninstall_desktop: bool,

    /// Colour theme (default: the one you last chose in the viewer, else
    /// auto). Press t in the viewer to switch.
    #[arg(long, value_enum)]
    theme: Option<Theme>,

    /// Page style.
    #[arg(long, value_enum)]
    style: Option<Style>,

    /// Extra CSS file, applied after the built-in styles.
    #[arg(long, value_name = "PATH")]
    css: Option<PathBuf>,

    /// Number headings (1, 1.1, 1.2, …).
    #[arg(long)]
    number_headings: bool,

    /// Number the lines of every code block (or per block, with
    /// `showLineNumbers` in its info string).
    #[arg(long)]
    line_numbers: bool,

    /// YAML front matter: shown as a table, like GitHub (default), or hidden.
    #[arg(long, value_enum, value_name = "HOW")]
    front_matter: Option<FrontMatter>,

    /// Obsidian notes: [[wiki links]], ![[embeds]], callouts, ==highlights==
    /// and %%comments%%. On by default inside a vault (a .obsidian folder).
    #[arg(long, overrides_with = "no_obsidian")]
    obsidian: bool,

    /// Turn off Obsidian notes, even inside a vault.
    #[arg(long, overrides_with = "obsidian")]
    no_obsidian: bool,

    /// Editor for double-click-to-source, e.g. "zed" or
    /// "code -g {file}:{line}" (default: $VISUAL/$EDITOR if it's a GUI
    /// editor, else the first one found).
    #[arg(long, value_name = "COMMAND")]
    editor: Option<String>,

    /// Print a shell completion script (bash, zsh, fish, elvish, powershell).
    #[arg(long, value_enum, value_name = "SHELL", exclusive = true, hide = true)]
    generate_completions: Option<clap_complete::Shell>,

    /// Print the man page.
    #[arg(long, exclusive = true, hide = true)]
    generate_man: bool,
}

fn main() {
    if let Err(err) = run(Cli::parse()) {
        eprintln!("markdown-viewer: {err:#}");
        std::process::exit(1);
    }
}

/// Command-line options merged with the settings file.
struct Settings {
    style: Style,
    css_path: Option<PathBuf>,
    css: Option<String>,
    open: browser::Mode,
    browser: Option<String>,
    port: u16,
    /// `--theme` if given; it wins over remembered and configured themes.
    theme_flag: Option<Theme>,
    config_theme: Option<Theme>,
    number_headings: bool,
    line_numbers: bool,
    front_matter: FrontMatter,
    /// `None`: decide by whether the file is in an Obsidian vault.
    obsidian: Option<bool>,
    editor: Option<String>,
    github_references: bool,
    /// The repository for references, from the settings file.
    github_repo: Option<String>,
    lint_ignore: Vec<String>,
    /// Remember opened files for the Recent page.
    recent: bool,
}

impl Settings {
    fn new(cli: &Cli, config: Config) -> Result<Self> {
        let css_path = cli.css.clone().or(config.css.clone());
        let css = match &css_path {
            Some(p) => Some(
                std::fs::read_to_string(p)
                    .with_context(|| format!("cannot read CSS file {}", p.display()))?,
            ),
            None => None,
        };
        let open = if cli.tab {
            browser::Mode::Tab
        } else if cli.window {
            browser::Mode::Window
        } else if cli.app {
            browser::Mode::App
        } else {
            config.open_mode().unwrap_or_default()
        };
        let obsidian = if cli.obsidian {
            Some(true)
        } else if cli.no_obsidian {
            Some(false)
        } else {
            config.obsidian
        };
        Ok(Self {
            style: cli.style.or(config.style).unwrap_or_default(),
            css_path,
            css,
            open,
            browser: cli.browser.clone().or(config.browser),
            port: cli.port.or(config.port).unwrap_or(0),
            theme_flag: cli.theme,
            config_theme: config.theme,
            number_headings: cli.number_headings || config.number_headings.unwrap_or(false),
            line_numbers: cli.line_numbers || config.line_numbers.unwrap_or(false),
            front_matter: cli.front_matter.or(config.front_matter).unwrap_or_default(),
            obsidian,
            editor: cli.editor.clone().or(config.editor),
            github_references: config.github_references.unwrap_or(true),
            github_repo: config
                .github_repo
                .as_deref()
                .and_then(references::from_setting),
            lint_ignore: config.lint_ignore.unwrap_or_default(),
            recent: config.recent.unwrap_or(true),
        })
    }

    /// Theme for something you'll read now: the flag, else the last theme
    /// picked in the viewer, else the settings file, else auto.
    fn viewing_theme(&self, prefs: &Prefs) -> Theme {
        self.theme_flag
            .or(prefs.theme)
            .or(self.config_theme)
            .unwrap_or_default()
    }

    /// Theme for an exported file: the flag or settings file only.
    fn export_theme(&self) -> Theme {
        self.theme_flag.or(self.config_theme).unwrap_or_default()
    }

    fn render_options(&self, sourcepos: bool, at: &Path) -> RenderOptions {
        RenderOptions {
            sourcepos,
            obsidian: self.obsidian.unwrap_or_else(|| obsidian::in_vault(at)),
            front_matter: self.front_matter,
            line_numbers: self.line_numbers,
            github: if self.github_references {
                self.github_repo.clone().or_else(|| references::detect(at))
            } else {
                None
            },
        }
    }

    fn page(&self, title: String, theme: Theme) -> PageOptions {
        PageOptions {
            title,
            theme,
            style: self.style,
            custom_css: self.css.clone(),
            fixed_theme: self.theme_flag.is_some(),
            number_headings: self.number_headings,
            ..Default::default()
        }
    }
}

/// What to show.
enum Source {
    File(PathBuf),
    Folder(PathBuf),
    /// Text with no file behind it: standard input, the clipboard or the
    /// Recent page, served from `root` (relative links resolve there).
    Text {
        name: &'static str,
        text: String,
        root: PathBuf,
    },
}

fn run(cli: Cli) -> Result<()> {
    if let Some(shell) = cli.generate_completions {
        clap_complete::generate(
            shell,
            &mut docs_command(),
            "markdown-viewer",
            &mut std::io::stdout(),
        );
        return Ok(());
    }
    if cli.generate_man {
        clap_mangen::Man::new(docs_command()).render(&mut std::io::stdout())?;
        return Ok(());
    }
    if cli.install_finder || cli.uninstall_finder {
        return finder_integration(cli.install_finder);
    }
    if cli.install_desktop {
        return desktop::install();
    }
    if cli.uninstall_desktop {
        return desktop::uninstall();
    }
    let settings = Settings::new(&cli, Config::load()?)?;
    let cwd = std::env::current_dir()?.canonical()?;

    // --goto: scroll a viewer that's already showing the file, else start
    // one (below) opened at that line.
    let goto = cli.goto.as_deref().map(parse_goto).transpose()?;
    if let Some((file, line)) = &goto
        && let Some(url) = instances::find_serving(file)
    {
        if !instances::send_goto(&url, file, *line) {
            bail!("couldn't reach the viewer at {url}");
        }
        say(&format!("Showing {}:{line} at {url}", file.display()));
        return Ok(());
    }
    if goto.is_some() && cli.if_running {
        return Ok(());
    }
    // The Recent page: asked for, or no FILE in the home folder (browsing
    // all of it is rarely what you want). Its links go through the server,
    // so it's always served.
    let home = platform::home().and_then(|h| h.canonical().ok());
    let show_recent = cli.recent
        || (cli.file.is_none()
            && !cli.clipboard
            && goto.is_none()
            && settings.recent
            && home.as_ref() == Some(&cwd));
    let watch = cli.watch || goto.is_some() || show_recent;

    if cli.check_links || cli.lint {
        let target = cli.file.clone().unwrap_or_else(|| cwd.clone());
        return check(&settings, &target, cli.check_links, cli.online, cli.lint);
    }

    let source = if let Some((file, _)) = &goto {
        Source::File(file.clone())
    } else if cli.clipboard {
        Source::Text {
            name: "Clipboard",
            text: read_clipboard()?,
            root: cwd.clone(),
        }
    } else if show_recent {
        let home = home.context("cannot find your home folder")?;
        Source::Text {
            name: "Recent",
            text: recent::page(&Prefs::load().recent, &home),
            root: home,
        }
    } else {
        match &cli.file {
            Some(p) if p.as_os_str() == "-" => {
                let mut text = String::new();
                std::io::stdin()
                    .read_to_string(&mut text)
                    .context("cannot read standard input")?;
                Source::Text {
                    name: "stdin",
                    text,
                    root: cwd.clone(),
                }
            }
            Some(p) => {
                let path = p
                    .canonical()
                    .with_context(|| format!("cannot open {}", p.display()))?;
                if path.is_dir() {
                    Source::Folder(path)
                } else if path.is_file() {
                    Source::File(path)
                } else {
                    bail!("{} is not a file", p.display());
                }
            }
            None => Source::Folder(cwd.clone()),
        }
    };

    // Remember what was opened (not exported) for the Recent page.
    if settings.recent
        && cli.output.is_none()
        && cli.pdf.is_none()
        && let Source::File(path) | Source::Folder(path) = &source
    {
        recent::record(path);
    }

    let (markdown, dir, title) = match &source {
        Source::Folder(path) => {
            if let Some(out) = &cli.output {
                if out.as_os_str() == "-" {
                    bail!("{} is a folder; -o - needs a Markdown file", path.display());
                }
                return export_site(&settings, path, out);
            }
            if cli.pdf.is_some() {
                bail!(
                    "{} is a folder; --pdf needs a Markdown file",
                    path.display()
                );
            }
            return serve(&cli, &settings, &source, None);
        }
        Source::File(path) => (
            read(path)?,
            path.parent()
                .context("file has no parent folder")?
                .to_path_buf(),
            server::file_title(path),
        ),
        Source::Text { name, text, root } => (text.clone(), root.clone(), name.to_string()),
    };
    if !watch && (cli.exit_when_closed || cli.port.is_some()) {
        bail!("--port and --exit-when-closed need --watch");
    }

    let (renderer, mut body) = render_standalone(&settings, &markdown, &dir);
    if let Source::File(path) = &source
        && let Some(delim) = tables::delimiter(path)
    {
        body = tables::to_html(&markdown, delim);
    }

    if let Some(output) = &cli.output {
        let page = settings.page(title, settings.export_theme());
        let html = renderer.wrap_page(&body, &page);
        if output.as_os_str() == "-" {
            std::io::stdout().write_all(html.as_bytes())?;
        } else {
            std::fs::write(output, html)
                .with_context(|| format!("cannot write {}", output.display()))?;
        }
        return Ok(());
    }

    if let Some(out) = &cli.pdf {
        // PDFs are always light: they're for printing and sharing.
        let page = PageOptions {
            base_href: Some(dir_url(&dir)),
            ..settings.page(title, Theme::Light)
        };
        pdf::print(&renderer.wrap_page(&body, &page), out)?;
        say(&format!("Wrote {}", out.display()));
        return Ok(());
    }

    if watch {
        return serve(&cli, &settings, &source, goto.map(|(_, line)| line));
    }

    // One-shot: write a self-contained page to the temp dir and open it.
    let prefs = Prefs::load();
    let page = PageOptions {
        base_href: Some(dir_url(&dir)),
        ui: true,
        sidebar: prefs.sidebar.clone(),
        ..settings.page(title.clone(), settings.viewing_theme(&prefs))
    };
    let key = match &source {
        Source::File(path) => path.clone(),
        _ => dir.join(&title),
    };
    let out = temp_page_path(&key)?;
    std::fs::write(&out, renderer.wrap_page(&body, &page))
        .with_context(|| format!("cannot write {}", out.display()))?;
    say(&out.display().to_string());
    if !cli.no_open {
        browser::open(
            &platform::file_url(&out),
            settings.browser.as_deref(),
            settings.open,
        )?;
    }
    Ok(())
}

/// The command as documented in the completions and man page: the same on
/// every platform (the macOS-only flags are hidden from `--help` elsewhere,
/// but the generated files ship everywhere and say "macOS:").
fn docs_command() -> clap::Command {
    Cli::command()
        .mut_arg("install_finder", |a| a.hide(false))
        .mut_arg("uninstall_finder", |a| a.hide(false))
        .mut_arg("install_desktop", |a| a.hide(false))
        .mut_arg("uninstall_desktop", |a| a.hide(false))
}

/// Render for a page that isn't served: Obsidian links (if on) resolve
/// relative to the document's folder.
fn render_standalone(settings: &Settings, markdown: &str, dir: &Path) -> (Renderer, String) {
    let options = settings.render_options(false, dir);
    let renderer = Renderer::with_options(options.clone());
    let body = if options.obsidian {
        let root = obsidian::vault_root(dir).unwrap_or_else(|| dir.to_path_buf());
        let (files, _) = docs::markdown_files(&root);
        let ctx = obsidian::LinkContext {
            root: &root,
            dir,
            files: &files,
            served: false,
            depth: 0,
        };
        renderer.render_doc(markdown, Some(&ctx))
    } else {
        renderer.render_body(markdown)
    };
    (renderer, body)
}

/// `-o DIR` for a folder: a static site.
fn export_site(settings: &Settings, root: &Path, out: &Path) -> Result<()> {
    let options = settings.render_options(false, root);
    let renderer = Renderer::with_options(options.clone());
    let page = |title: String| settings.page(title, settings.export_theme());
    let summary = site::export(&renderer, options.obsidian, root, out, &page)?;
    if summary.truncated {
        say("Only the first 2,000 Markdown files were exported.");
    }
    let files = match summary.files {
        0 => String::new(),
        1 => " and 1 file".into(),
        n => format!(" and {n} files"),
    };
    say(&format!(
        "Wrote {} pages{files} to {} (start at {})",
        summary.pages,
        out.display(),
        out.join("index.html").display()
    ));
    Ok(())
}

/// `path/to/file.md:42` → (canonical file, 42). Without a line, line 1.
fn parse_goto(spec: &str) -> Result<(PathBuf, u32)> {
    let (path, line) = match spec.rsplit_once(':') {
        Some((p, l)) if !p.is_empty() && l.chars().all(|c| c.is_ascii_digit()) && !l.is_empty() => {
            (p, l.parse().unwrap_or(1))
        }
        _ => (spec, 1),
    };
    let file = Path::new(path)
        .canonical()
        .with_context(|| format!("cannot open {path}"))?;
    if !file.is_file() {
        bail!("{path} is not a file");
    }
    Ok((file, line.max(1)))
}

/// --check-links: report broken links; fail if there are any.
/// `--check-links` and/or `--lint`: report problems as `file:line: what
/// (why)`, and exit with status 1 if there are any.
fn check(settings: &Settings, target: &Path, links: bool, online: bool, lint: bool) -> Result<()> {
    let target = target
        .canonical()
        .with_context(|| format!("cannot open {}", target.display()))?;
    let (root, files) = if target.is_dir() {
        let (files, _) = docs::markdown_files(&target);
        let files = files.iter().map(|f| target.join(f)).collect();
        (target.clone(), files)
    } else {
        let parent = target.parent().context("file has no parent folder")?;
        let root = obsidian::vault_root(parent).unwrap_or_else(|| parent.to_path_buf());
        (root, vec![target.clone()])
    };
    let renderer = Arc::new(Renderer::with_options(settings.render_options(true, &root)));
    let checker = links::Checker::new(renderer, root.clone());
    // Lint without Obsidian embeds (other files' problems) or GitHub links.
    let lint_renderer = Renderer::with_options(RenderOptions {
        obsidian: false,
        github: None,
        ..settings.render_options(true, &root)
    });
    let shown = |f: &Path| -> String {
        let base = if target.is_dir() { &target } else { &root };
        f.strip_prefix(base)
            .map(|p| p.display().to_string())
            .unwrap_or_else(|_| f.display().to_string())
    };

    let mut problems: Vec<(String, u32, String, String)> = Vec::new();
    let mut web: Vec<(String, links::Link)> = Vec::new();
    let mut total = 0;
    let mut lint_count = 0;
    for file in &files {
        if lint {
            let text = read(file)?;
            for p in lint::check(
                &text,
                &lint_renderer.render_body(&text),
                &settings.lint_ignore,
            ) {
                lint_count += 1;
                problems.push((shown(file), p.line, p.message, p.rule.to_string()));
            }
        }
        if !links {
            continue;
        }
        let (broken, external, count) = checker.check(file);
        total += count;
        for b in broken {
            problems.push((shown(file), b.line, b.target, b.reason));
        }
        web.extend(external.into_iter().map(|l| (shown(file), l)));
    }
    if online && !web.is_empty() {
        let urls = web.iter().map(|(_, l)| l.target.clone()).collect();
        let failures = links::check_online(&urls).map_err(anyhow::Error::msg)?;
        for (file, link) in &web {
            if let Some(reason) = failures.get(&link.target) {
                problems.push((file.clone(), link.line, link.target.clone(), reason.clone()));
            }
        }
    }
    problems.sort();
    for (file, line, target, reason) in &problems {
        say(&format!("{file}:{line}: {target} ({reason})"));
    }
    let not_checked = if online || web.is_empty() {
        String::new()
    } else {
        format!(" {} web links not checked (add --online).", web.len())
    };
    let files_word = if files.len() == 1 { "file" } else { "files" };
    if links {
        say(&format!(
            "Checked {total} links in {} {files_word}: {} broken.{not_checked}",
            files.len(),
            problems.len() - lint_count
        ));
    }
    if lint {
        let word = if lint_count == 1 {
            "problem"
        } else {
            "problems"
        };
        say(&format!(
            "Linted {} {files_word}: {lint_count} {word}.",
            files.len()
        ));
    }
    if !problems.is_empty() {
        std::process::exit(1);
    }
    Ok(())
}

/// Serve with live reload. `start_line` opens the page at that line.
fn serve(cli: &Cli, settings: &Settings, source: &Source, start_line: Option<u32>) -> Result<()> {
    // What we serve from, what `/` shows, and who we are (for reuse).
    let (root, main, identity) = match source {
        Source::Folder(dir) => (dir.clone(), None, Some(dir.clone())),
        Source::File(file) => {
            let parent = file.parent().context("file has no parent folder")?;
            let options = settings.render_options(true, parent);
            // In a vault, serve the whole vault so linked notes open.
            let root = options
                .obsidian
                .then(|| obsidian::vault_root(parent))
                .flatten()
                .unwrap_or_else(|| parent.to_path_buf());
            (root, Some(file.clone()), Some(file.clone()))
        }
        Source::Text { name, root, .. } => {
            (root.clone(), Some(root.join(format!("({name})"))), None)
        }
    };

    // Already being served? Reuse that viewer (and bring its window
    // forward) instead of starting another.
    if let Some(target) = &identity
        && let Some(url) = instances::find(target)
    {
        if !cli.no_open && !browser::focus(&url, settings.browser.as_deref()) {
            browser::open(&url, settings.browser.as_deref(), settings.open)?;
        }
        say(&format!("Already open at {url}"));
        return Ok(());
    }

    let rt = tokio::runtime::Builder::new_multi_thread()
        .enable_all()
        .build()?;
    rt.block_on(async move {
        let renderer = Arc::new(Renderer::with_options(settings.render_options(true, &root)));
        let docs = docs::Docs::new(root.clone(), renderer.clone())?;
        if let (Source::Text { text, .. }, Some(key)) = (source, &main) {
            docs.add_virtual(key, docs.render_text(text, &root));
            if cli.clipboard && cli.watch {
                follow_clipboard(docs.clone(), key.clone(), root.clone(), text.clone());
            }
        }
        let saved = Prefs::load();
        let prefs = Prefs {
            theme: Some(settings.viewing_theme(&saved)),
            ..saved
        };
        let page = PageOptions {
            served: true,
            live: true,
            ui: true,
            custom_css: None,
            ..settings.page(String::new(), Theme::Auto)
        };
        let server = server::Server::bind(server::ServeOptions {
            port: settings.port,
            docs,
            renderer,
            main: main.clone(),
            page,
            custom_css: settings.css_path.clone(),
            prefs,
            remember: true,
            editor: settings.editor.clone(),
            identity: identity
                .as_ref()
                .map(|p| p.to_string_lossy().into_owned())
                .unwrap_or_default(),
        })
        .await?;
        let url = server.url();
        let port = url
            .trim_end_matches('/')
            .rsplit(':')
            .next()
            .and_then(|p| p.parse().ok())
            .unwrap_or(0);
        let _registration = identity.as_ref().and_then(|t| instances::register(t, port));
        let handle = server.handle();
        let shown = match source {
            Source::Text { name, .. } => name.to_string(),
            _ => identity
                .as_ref()
                .map(|p| p.display().to_string())
                .unwrap_or_default(),
        };
        say(&format!("Serving {shown} at {url}"));
        say("Watching for changes. Press Ctrl-C to stop.");
        let mut server = tokio::spawn(server.run());
        if !cli.no_open {
            // Set before opening: the browser may load the page before
            // `open` returns. Corrected if we could only open a tab.
            handle.set_close_on_exit(settings.open != browser::Mode::Tab);
            let page_url = match start_line {
                Some(line) => format!("{url}#mdv-line-{line}"),
                None => url.clone(),
            };
            let opened = browser::open(&page_url, settings.browser.as_deref(), settings.open)?;
            handle.set_close_on_exit(opened == browser::Opened::Window);
        }
        // With --exit-when-closed, stop once the page has been closed for a
        // few seconds (long enough to survive a reload).
        let abandoned = async {
            if cli.exit_when_closed {
                handle
                    .abandoned(Duration::from_secs(5), Duration::from_secs(60))
                    .await;
            } else {
                std::future::pending::<()>().await;
            }
        };
        tokio::select! {
            res = &mut server => res?,
            _ = abandoned => {
                say("Page closed; exiting.");
                Ok(())
            }
            _ = tokio::signal::ctrl_c() => {
                // Let pages close their window (or show "stopped") before we go.
                handle.announce_shutdown();
                tokio::time::sleep(Duration::from_millis(300)).await;
                Ok(())
            }
        }
    })
}

/// Poll the clipboard and update the page when its text changes.
fn follow_clipboard(docs: Arc<docs::Docs>, key: PathBuf, root: PathBuf, mut last: String) {
    tokio::spawn(async move {
        loop {
            tokio::time::sleep(Duration::from_millis(800)).await;
            let Ok(Ok(text)) = tokio::task::spawn_blocking(read_clipboard).await else {
                continue;
            };
            if text != last && !text.trim().is_empty() {
                let html = docs.render_text(&text, &root);
                docs.set_virtual(&key, html);
                last = text;
            }
        }
    });
}

/// The clipboard's text: pbpaste on macOS; wl-paste, xclip or xsel on Linux.
fn read_clipboard() -> Result<String> {
    let candidates: &[(&str, &[&str])] = if cfg!(target_os = "macos") {
        &[("pbpaste", &[])]
    } else if cfg!(windows) {
        &[(
            "powershell",
            &[
                "-NoProfile",
                "-NonInteractive",
                "-Command",
                "[Console]::OutputEncoding = [Text.Encoding]::UTF8; Get-Clipboard -Raw",
            ],
        )]
    } else {
        &[
            ("wl-paste", &["--no-newline"]),
            ("xclip", &["-selection", "clipboard", "-o"]),
            ("xsel", &["--clipboard", "--output"]),
        ]
    };
    for (program, args) in candidates {
        if let Ok(out) = std::process::Command::new(program).args(*args).output()
            && out.status.success()
        {
            return Ok(String::from_utf8_lossy(&out.stdout).into_owned());
        }
    }
    bail!("couldn't read the clipboard (needs pbpaste, PowerShell, wl-paste, xclip or xsel)")
}

#[cfg(target_os = "macos")]
fn finder_integration(install: bool) -> Result<()> {
    if install {
        finder::install()
    } else {
        finder::uninstall()
    }
}

#[cfg(not(target_os = "macos"))]
fn finder_integration(_install: bool) -> Result<()> {
    bail!("Finder integration is only available on macOS")
}

/// Print a status line. Unlike `println!`, this doesn't panic if stdout has
/// been closed (e.g. `markdown-viewer --watch f.md | head -1`), which would
/// otherwise take the server down with it.
fn say(msg: &str) {
    let _ = writeln!(std::io::stdout(), "{msg}");
}

fn read(path: &Path) -> Result<String> {
    std::fs::read_to_string(path).with_context(|| format!("cannot read {}", path.display()))
}

/// Stable per-source path so repeated runs reuse (and overwrite) one file.
fn temp_page_path(source: &Path) -> Result<PathBuf> {
    let dir = std::env::temp_dir().join("markdown-viewer");
    std::fs::create_dir_all(&dir)?;
    let mut h = DefaultHasher::new();
    source.hash(&mut h);
    let stem = source
        .file_stem()
        .map(|s| s.to_string_lossy().into_owned())
        .unwrap_or_else(|| "page".into());
    Ok(dir.join(format!("{stem}-{:08x}.html", h.finish() as u32)))
}

/// `file://` URL for a directory, with a trailing slash so it works as `<base>`.
fn dir_url(dir: &Path) -> String {
    let mut url = platform::file_url(dir);
    if !url.ends_with('/') {
        url.push('/');
    }
    url
}

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

    #[test]
    fn file_url_encodes_and_ends_with_slash() {
        assert_eq!(
            dir_url(Path::new("/tmp/my docs#1")),
            "file:///tmp/my%20docs%231/"
        );
    }

    #[test]
    fn generates_completions_and_man_page() {
        for shell in [
            clap_complete::Shell::Bash,
            clap_complete::Shell::Zsh,
            clap_complete::Shell::Fish,
        ] {
            let mut out = Vec::new();
            clap_complete::generate(shell, &mut docs_command(), "markdown-viewer", &mut out);
            let text = String::from_utf8(out).unwrap();
            assert!(text.contains("number-headings"), "{shell:?}");
        }
        let mut man = Vec::new();
        clap_mangen::Man::new(docs_command())
            .render(&mut man)
            .unwrap();
        assert!(
            String::from_utf8(man)
                .unwrap()
                .contains(".TH markdown-viewer")
        );
    }

    #[test]
    fn cli_is_valid() {
        use clap::CommandFactory;
        Cli::command().debug_assert();
    }
}