mdo-cli 0.6.1

A simple Rust CLI to convert Markdown to HTML5 (styled with simple.css), with optional file watching
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
//! # mdo
//!
//! `mdo` is a small command-line tool that converts Markdown (`.md`) files to HTML.
//!
//! By default it produces a complete, HTML5-compliant document styled with
//! [simple.css](https://simplecss.org/) (vendored at build time, no network access at runtime).
//!
//! ## Usage
//!
//! ```sh
//! mdo [OPTIONS] <INPUT>
//! ```
//!
//! If no output path is given, the output is written next to the input with
//! the extension changed to `.html` (e.g. `foo.md` → `foo.html`). Existing
//! files are overwritten.
//!
//! Options:
//! - `-o, --output <FILE>`  Write to `<FILE>` instead of the derived name
//! - `-w, --watch`          Keep running and re-render on file changes
//! - `-b, --bare`           Emit only the HTML fragment (no `<html>`, `<head>`, `<body>`, no CSS)
//! - `--css <FILE>`         Append custom CSS after mdo's default styling
//! - `--unsafe-html`        Preserve raw HTML from the Markdown source
//! - `-v, --verbose`        Report render-workflow timings on stderr
//! - `--setup`               Show a cautious first-run setup
//!
//! Without `--watch`, the tool converts once and exits.
//!
//! ## Credits
//!
//! Forked with gratitude from Hafiz Ali Raza's original Markdown-to-HTML CLI.
//! Bundles [simple.css](https://simplecss.org/) (© 2020 Kev Quirk, MIT).

use std::io::{self, IsTerminal, Write};
use std::path::PathBuf;
use std::sync::mpsc::channel;
use std::time::Duration;

use clap::Parser;
use mdo_cli::{
    convert_with_diagnostics, derive_output, file_manager, launch_browser, open_setup_sample,
    temp_output_for,
};
use notify::{recommended_watcher, EventKind, RecursiveMode, Watcher};

/// Markdown to HTML converter. Converts once by default; pass --watch to keep watching.
#[derive(Parser)]
#[command(name = "mdo", author, version, about)]
struct Cli {
    /// Input Markdown file
    input: Option<PathBuf>,

    /// Output HTML file (defaults to <input>.html alongside the input,
    /// or to a temp directory when --open is used). Existing files are overwritten.
    #[arg(short, long)]
    output: Option<PathBuf>,

    /// Watch the input file and re-render on every change
    #[arg(short, long)]
    watch: bool,

    /// Emit only the HTML fragment (no <html>, <head>, <body>, no CSS)
    #[arg(short, long)]
    bare: bool,

    /// Append a custom CSS file after mdo's default styling
    #[arg(long, value_name = "FILE")]
    css: Option<PathBuf>,

    /// Preserve raw HTML from the Markdown source instead of sanitizing it
    #[arg(long)]
    unsafe_html: bool,

    /// Report timing diagnostics for the render workflow (read, markdown,
    /// sanitize, assemble, write, total) on stderr. The generated HTML is
    /// unchanged.
    #[arg(short, long)]
    verbose: bool,

    /// Render to a temp directory and launch the system default browser.
    /// The source folder is left untouched unless --output is given.
    #[arg(long)]
    open: bool,

    /// Show a first-run setup with safe next steps for new users.
    #[arg(long)]
    setup: bool,

    /// Install per-user file-manager integration for Markdown files.
    ///
    /// On Windows this registers Open as HTML with Explorer. On Linux this
    /// writes an XDG desktop entry and icon.
    #[arg(long)]
    install_file_manager: bool,

    /// Remove per-user file-manager integration installed by mdo.
    #[arg(long)]
    uninstall_file_manager: bool,

    /// When installing on Linux, make Open as HTML the default Markdown
    /// handler. Windows still requires choosing the default app interactively.
    #[arg(long)]
    set_default: bool,
}

fn setup_is_interactive() -> bool {
    io::stdin().is_terminal() && io::stdout().is_terminal()
}

/// What the single setup decision resolved to. Setup stays one clear choice
/// per run: install (or reinstall) the integration, or leave things unchanged.
#[derive(Debug, PartialEq, Eq)]
enum SetupIntegrationChoice {
    Install,
    LeaveUnchanged,
    Help,
    Invalid,
}

/// The prompt adapts to the cheap owned-state check: an already-configured
/// user is offered leave-unchanged (default) or reinstall, instead of being
/// greeted like a first-time installer.
fn setup_integration_prompt(already_installed: bool) -> &'static str {
    if already_installed {
        "Reinstall Open as HTML file-manager integration? [y/N] "
    } else {
        "Install Open as HTML file-manager integration now? [Y/n] "
    }
}

fn setup_integration_choice(answer: &str, already_installed: bool) -> SetupIntegrationChoice {
    match answer.trim().to_ascii_lowercase().as_str() {
        "" => {
            if already_installed {
                SetupIntegrationChoice::LeaveUnchanged
            } else {
                SetupIntegrationChoice::Install
            }
        }
        "y" | "yes" => SetupIntegrationChoice::Install,
        "n" | "no" => SetupIntegrationChoice::LeaveUnchanged,
        "?" | "h" | "help" => SetupIntegrationChoice::Help,
        _ => SetupIntegrationChoice::Invalid,
    }
}

fn print_landing_page() {
    println!(
        "\
Open Markdown as HTML.

  mdo FILE.md          create FILE.html
  mdo --open FILE.md   open rendered HTML in your browser
  mdo --setup          set up file-manager integration
  mdo --help           show all options"
    );
}

fn print_first_run_setup(can_install_file_manager: bool) {
    println!(
        "\
Welcome to mdo.

mdo turns Markdown files into standalone HTML and can open the result in your
default browser without leaving generated files beside your notes.

Try these when you are ready:

  mdo notes.md                 render notes.html beside notes.md
  mdo --open notes.md          render to a temp path and open the browser
  mdo --watch notes.md         keep notes.html updated while you edit
  mdo --help                   show every command-line option
"
    );

    if can_install_file_manager {
        println!(
            "\
Optional desktop integration:

  mdo --install-file-manager   add an \"Open as HTML\" file-manager action
  mdo --uninstall-file-manager remove that integration later

The installer is per-user. It does not need admin rights and does not change
your default Markdown app unless you opt into the platform-specific default
handler flow.
"
        );
    } else {
        println!(
            "\
Optional desktop integration:

This platform does not have a built-in mdo installer yet. You can still wire
your file manager to run `mdo --open <file>`; see the README for platform
recipes.
"
        );
    }
}

fn run_first_run_setup() -> io::Result<()> {
    let interactive = setup_is_interactive();
    let can_install_file_manager = cfg!(any(target_os = "linux", target_os = "windows"));

    print_first_run_setup(can_install_file_manager);

    if !interactive {
        return Ok(());
    }

    if can_install_file_manager {
        let already_installed = file_manager::integration_installed();
        if already_installed {
            println!("Open as HTML file-manager integration is already installed for this user.");
        }
        loop {
            print!("{}", setup_integration_prompt(already_installed));
            io::stdout().flush()?;

            let mut answer = String::new();
            if io::stdin().read_line(&mut answer)? == 0 {
                return Ok(());
            }

            match setup_integration_choice(&answer, already_installed) {
                SetupIntegrationChoice::Install => {
                    match file_manager::install(false) {
                        Ok(()) => {
                            if already_installed {
                                println!(
                                    "Integration reinstalled. No default app was changed by mdo."
                                );
                            } else {
                                println!(
                                    "Integration installed. No default app was changed by mdo."
                                );
                            }
                        }
                        Err(e) => {
                            eprintln!("Could not install file-manager integration: {e}");
                            println!("No default app was changed by mdo.");
                            wait_for_setup_close()?;
                            return Err(e);
                        }
                    }
                    break;
                }
                SetupIntegrationChoice::LeaveUnchanged => {
                    if already_installed {
                        println!(
                            "Left unchanged. Run `mdo --uninstall-file-manager` if you ever want to remove it."
                        );
                    } else {
                        println!(
                            "No changes made. Run `mdo --install-file-manager` whenever you are ready."
                        );
                    }
                    break;
                }
                SetupIntegrationChoice::Help => {
                    if already_installed {
                        println!(
                            "Reinstalling rewrites mdo's own per-user registration in place. \
                             It is reversible with `mdo --uninstall-file-manager`."
                        );
                    } else {
                        println!(
                            "This adds an \"Open as HTML\" action for Markdown files in your file manager. \
                             It is reversible with `mdo --uninstall-file-manager`."
                        );
                    }
                }
                SetupIntegrationChoice::Invalid => println!("Please answer y or n."),
            }
        }
    }

    wait_for_setup_close()?;
    println!("Opening a welcome sample in your browser...");
    match open_setup_sample() {
        Ok(()) => println!("🌐 Opened welcome sample in default browser"),
        Err(e) => eprintln!("⚠️  Failed to open welcome sample: {e}"),
    }
    Ok(())
}

fn wait_for_setup_close() -> io::Result<()> {
    println!("Press Enter to close this setup.");
    let mut ignored = String::new();
    io::stdin().read_line(&mut ignored)?;
    Ok(())
}

fn main() -> notify::Result<()> {
    let args = Cli::parse();

    // Parse first so Clap retains ownership of --help, --version, and errors.
    // Only the truly argument-free invocation gets the short landing page.
    if std::env::args_os().len() == 1 {
        print_landing_page();
        return Ok(());
    }

    if args.install_file_manager && args.uninstall_file_manager {
        eprintln!("❌ Choose only one of --install-file-manager or --uninstall-file-manager");
        std::process::exit(2);
    }

    if args.setup {
        if args.input.is_some()
            || args.output.is_some()
            || args.watch
            || args.bare
            || args.css.is_some()
            || args.unsafe_html
            || args.verbose
            || args.open
            || args.install_file_manager
            || args.uninstall_file_manager
            || args.set_default
        {
            eprintln!("❌ --setup cannot be combined with render or integration options");
            std::process::exit(2);
        }

        if let Err(e) = run_first_run_setup() {
            eprintln!("❌ Setup failed: {e}");
            std::process::exit(1);
        }

        return Ok(());
    }

    if args.set_default && !args.install_file_manager {
        eprintln!("❌ --set-default can only be used with --install-file-manager");
        std::process::exit(2);
    }

    if args.bare && args.css.is_some() {
        eprintln!("❌ --css cannot be combined with --bare because bare output emits no CSS");
        std::process::exit(2);
    }

    if args.install_file_manager || args.uninstall_file_manager {
        if args.input.is_some()
            || args.output.is_some()
            || args.watch
            || args.bare
            || args.css.is_some()
            || args.unsafe_html
            || args.verbose
            || args.open
            || args.setup
        {
            eprintln!(
                "❌ File-manager integration commands cannot be combined with render options"
            );
            std::process::exit(2);
        }

        let result = if args.install_file_manager {
            file_manager::install(args.set_default)
        } else {
            file_manager::uninstall()
        };

        if let Err(e) = result {
            eprintln!("❌ File-manager integration failed: {e}");
            std::process::exit(1);
        }

        return Ok(());
    }

    let input = match args.input {
        Some(input) => input,
        None => {
            eprintln!("❌ Missing input Markdown file");
            eprintln!("Run `mdo --help` for usage or `mdo --setup` for a first-run guide.");
            std::process::exit(2);
        }
    };

    // Output precedence:
    //   1. explicit --output           (always wins)
    //   2. --open without --output     → temp dir (don't pollute the source folder)
    //   3. neither                     → next to the input
    let (output, private_output) = match (args.output.clone(), args.open) {
        (Some(p), _) => (p, false),
        (None, true) => match temp_output_for(&input) {
            Ok(path) => (path, true),
            Err(e) => {
                eprintln!("❌ Failed to prepare temp output directory: {}", e);
                std::process::exit(1);
            }
        },
        (None, false) => (derive_output(&input), false),
    };

    // Register the watch BEFORE the initial render so a save that lands
    // while that render runs is queued by the watcher rather than silently
    // lost; the watch loop below drains it and re-renders. Registration
    // failure aborts before any rendering, which is fine — the user asked
    // for a watch we cannot deliver.
    //
    // Watch the parent DIRECTORY rather than the file itself. Editors that
    // save atomically (write a temp file, then rename it over the target)
    // replace the target's inode; a watch on the file itself goes dead the
    // moment that happens because the inode/handle notify was watching is
    // gone. Watching the directory survives renames, deletes, and recreates
    // — we just have to filter directory events down to ones that touch our
    // target file.
    //
    // Resolve the target once, up front. Comparing later events against
    // this fixed absolute path — rather than re-canonicalizing each event's
    // path — matters because the target may momentarily not exist
    // mid-rename, which would make canonicalize fail and misclassify a
    // perfectly relevant event.
    //
    // Known limitation: canonicalizing a symlinked input means we watch the
    // TARGET's parent, so edits made through the link are seen, but an
    // editor atomically replacing the symlink itself is not. Watching both
    // parents isn't worth the complexity until someone actually hits this.
    let watch_setup = if args.watch {
        let input_absolute = std::fs::canonicalize(&input).unwrap_or_else(|_| {
            std::env::current_dir()
                .map(|cwd| cwd.join(&input))
                .unwrap_or_else(|_| input.clone())
        });
        let watch_dir = input_absolute
            .parent()
            .map(PathBuf::from)
            .unwrap_or_else(|| PathBuf::from("."));
        let target_file_name = input_absolute.file_name().map(|n| n.to_os_string());

        let (tx, rx) = channel();
        let mut watcher = recommended_watcher(tx)?;
        watcher.watch(&watch_dir, RecursiveMode::NonRecursive)?;
        Some((watcher, rx, watch_dir, target_file_name))
    } else {
        None
    };

    let converted = convert_with_diagnostics(
        &input,
        &output,
        args.bare,
        args.unsafe_html,
        private_output,
        args.css.as_deref(),
        args.verbose,
    );

    // Track whether --open promised a browser launch and failed to deliver
    // one, so the one-shot exit code below can be honest about it.
    let mut open_launch_failed = false;
    if args.open && converted {
        // Browser launch is reported separately from the render workflow:
        // launch_browser only initiates the launch (fire-and-forget), so
        // this measures initiation, not the browser starting up.
        let launch_start = std::time::Instant::now();
        match launch_browser(&output) {
            Ok(()) => {
                if args.verbose {
                    eprintln!(
                        "⏱  Browser launch initiated in {:.3} ms",
                        launch_start.elapsed().as_secs_f64() * 1000.0
                    );
                }
                println!("🌐 Opened {:?} in default browser", output);
            }
            Err(e) => {
                // The render already succeeded and nothing removes the
                // rendered file on a launch failure, so point the user at it
                // instead of silently downgrading this to a warning.
                eprintln!("❌ Failed to launch browser: {}", e);
                eprintln!("   Rendered output is available at {:?}", output);
                open_launch_failed = true;
            }
        }
    }

    if !args.watch {
        // Exit non-zero on a failed one-shot render so scripts and the docs
        // pipeline can detect errors. A failed --open browser launch is the
        // same kind of broken promise even though the render itself
        // succeeded: `mdo --open` only fully succeeds when the file is both
        // rendered AND opened, so it exits non-zero here too. In watch mode
        // we deliberately do NOT apply this exit-code check: watch's
        // contract is to keep running regardless of a one-time --open
        // failure, since the whole point is to keep re-rendering on future
        // edits. The stderr message above still fires so the user learns
        // about the failed launch either way.
        if converted && !open_launch_failed {
            return Ok(());
        }
        std::process::exit(1);
    }

    let (_watcher, rx, watch_dir, target_file_name) =
        watch_setup.expect("watch setup was built above whenever --watch is set");

    // Still named after the file, not the directory: that's what the user
    // asked to watch, even though the underlying notify watch is scoped one
    // level up.
    println!("👀 Watching {:?} for changes... (Ctrl+C to stop)", input);

    // Trailing-edge debounce window: once a relevant event arrives we keep
    // draining/absorbing further relevant events for this long before
    // rendering, so a burst (e.g. truncate + write, or temp-file write +
    // rename) collapses into exactly one render of the final content. This
    // is unlike a leading-edge "ignore anything for N ms after the last
    // render" debounce, which can drop the trailing event of a burst if the
    // burst runs longer than the window.
    const DEBOUNCE: Duration = Duration::from_millis(200);

    loop {
        // Block for the next event. Anything that isn't a relevant,
        // content-changing event (wrong file, Access events, watcher
        // errors) is skipped without starting a debounce window.
        let event = match rx.recv() {
            Ok(Ok(event)) => event,
            Ok(Err(e)) => {
                eprintln!("⚠️  Watcher error: {}", e);
                continue;
            }
            Err(_) => return Ok(()), // watcher/channel gone; nothing left to watch
        };

        if !is_relevant_event(&event, target_file_name.as_deref(), &watch_dir) {
            continue;
        }

        // Drain/absorb further relevant events for a quiet window, then
        // render once. This covers direct writes, truncate+rewrite, and
        // atomic saves (temp file write followed by a rename onto the
        // target) uniformly: whichever event kinds the editor and platform
        // happen to emit (Create, Modify, Rename-as-Modify(Name), Remove
        // followed by a Create), each just extends the quiet window until
        // the burst settles. Only RELEVANT events extend the deadline:
        // sibling-file noise merely waits out the remaining window, so a
        // busy directory (a build churning artifacts next to the watched
        // file) cannot postpone the render indefinitely.
        let mut deadline = std::time::Instant::now() + DEBOUNCE;
        loop {
            let remaining = deadline.saturating_duration_since(std::time::Instant::now());
            if remaining.is_zero() {
                break;
            }
            match rx.recv_timeout(remaining) {
                Ok(Ok(event)) => {
                    if is_relevant_event(&event, target_file_name.as_deref(), &watch_dir) {
                        deadline = std::time::Instant::now() + DEBOUNCE;
                    }
                    // Irrelevant events neither extend nor cut the window.
                }
                Ok(Err(e)) => eprintln!("⚠️  Watcher error: {}", e),
                Err(_) => break, // quiet window elapsed (or channel closed)
            }
        }

        println!("🔁 File changed, re-rendering...");
        // A failed render (e.g. convert ran while the file was momentarily
        // absent mid-rename) must not end watch mode; convert_with_diagnostics
        // already reports the ❌ error itself, so we just loop and wait for
        // the next event.
        convert_with_diagnostics(
            &input,
            &output,
            args.bare,
            args.unsafe_html,
            private_output,
            args.css.as_deref(),
            args.verbose,
        );
    }
}

/// True if `event` plausibly changed the content of the file named
/// `target_file_name` inside `watch_dir`. We match by file name (and, when
/// notify reports one, by parent directory) rather than canonicalizing the
/// event's path, since the target can momentarily not exist mid-rename.
/// Access events (reads, permission-bit-only changes) are excluded; every
/// other kind (Create, Modify, Remove, Any, Other) is treated as a possible
/// content change so recreation-after-remove and atomic renames are all
/// covered by the same check.
fn is_relevant_event(
    event: &notify::Event,
    target_file_name: Option<&std::ffi::OsStr>,
    watch_dir: &std::path::Path,
) -> bool {
    if matches!(event.kind, EventKind::Access(_)) {
        return false;
    }

    let Some(target_file_name) = target_file_name else {
        return false;
    };

    event.paths.iter().any(|p| {
        p.file_name() == Some(target_file_name)
            && match p.parent() {
                Some(parent) => parent == watch_dir,
                None => true,
            }
    })
}

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

    #[test]
    fn first_time_setup_defaults_to_install() {
        assert_eq!(
            setup_integration_choice("", false),
            SetupIntegrationChoice::Install
        );
        assert_eq!(
            setup_integration_choice("y\n", false),
            SetupIntegrationChoice::Install
        );
        assert_eq!(
            setup_integration_choice("no", false),
            SetupIntegrationChoice::LeaveUnchanged
        );
    }

    #[test]
    fn already_installed_setup_defaults_to_leave_unchanged() {
        assert_eq!(
            setup_integration_choice("", true),
            SetupIntegrationChoice::LeaveUnchanged
        );
        assert_eq!(
            setup_integration_choice("n\n", true),
            SetupIntegrationChoice::LeaveUnchanged
        );
        assert_eq!(
            setup_integration_choice("YES", true),
            SetupIntegrationChoice::Install
        );
    }

    #[test]
    fn setup_answers_share_help_and_invalid_handling() {
        for already_installed in [false, true] {
            assert_eq!(
                setup_integration_choice("?", already_installed),
                SetupIntegrationChoice::Help
            );
            assert_eq!(
                setup_integration_choice("help", already_installed),
                SetupIntegrationChoice::Help
            );
            assert_eq!(
                setup_integration_choice("maybe", already_installed),
                SetupIntegrationChoice::Invalid
            );
        }
    }

    #[test]
    fn setup_prompt_matches_detected_state() {
        assert!(setup_integration_prompt(false).starts_with("Install "));
        assert!(setup_integration_prompt(false).contains("[Y/n]"));
        assert!(setup_integration_prompt(true).starts_with("Reinstall "));
        assert!(setup_integration_prompt(true).contains("[y/N]"));
    }
}