tread 0.4.2

A terminal reader for markdown, CSV, JSON and source code. Zero dependencies.
//! `tread` — a terminal markdown reader. Entry point and wiring.
//!
//! Argument parsing, input resolution, the panic guard, the interactive event
//! loop and the non-interactive dump path all hang off here.
//!
//! There is deliberately no crate-wide `allow(dead_code)`: an unused item is
//! either drift or a missing keybinding, and both should fail the build's
//! warning check rather than hide.

// `sys` is the only module allowed to contain `unsafe`. Every other module
// carries its own `#![deny(unsafe_code)]` inner attribute (repeating it here
// as an outer attribute is redundant), and this file contains none itself.
mod sys;

mod cli;
mod code;
mod lens;
mod csv;
mod open;
mod dump;
mod json;
mod key;
mod md;
mod nav;
mod pager;
mod plat;
mod render;
mod select;
mod source;
mod term;
mod theme;
mod url;

use std::env;
use std::io::Write;
use std::path::{Path, PathBuf};

use open::{build_source, resolve_input, toc_text, Fail, Input};
use source::Source;

const EXIT_OK: i32 = 0;
const EXIT_ERROR: i32 = 1;
const EXIT_USAGE: i32 = 2;

fn main() {
    std::process::exit(run());
}

fn run() -> i32 {
    let args = match cli::parse(env::args().skip(1)) {
        Ok(a) => a,
        Err(e) => {
            fatal(&e.to_string());
            return EXIT_USAGE;
        }
    };
    if args.help {
        return emit(&cli::help_text());
    }
    if args.version {
        return emit(&cli::version_text());
    }
    // `--lens list` is a question, not a run: it prints what there is and
    // exits 2, the same code an unknown name gets (SPEC.md §Lenses — the flag
    // is explicit, so "which are there" is answered rather than guessed).
    if args.lens_list {
        emit(&lens::list_text());
        return EXIT_USAGE;
    }
    install_panic_hook();
    match start(&args) {
        Ok(()) => EXIT_OK,
        Err(f) => {
            fatal(&f.msg);
            f.code
        }
    }
}

fn start(args: &cli::Args) -> Result<(), Fail> {
    let input = resolve_input(args)?;
    // An export, not a view: it never enters the pager, and it streams, so a
    // document too big to hold costs a read window (SPEC.md §JSON).
    if args.to_jsonl {
        let stdout = std::io::stdout();
        let mut out = std::io::BufWriter::new(stdout.lock());
        return open::to_jsonl(&input, &mut out);
    }
    if args.toc {
        emit(&toc_text(&input, args)?);
        return Ok(());
    }
    let src = build_source(&input, args)?;
    if sys::is_tty(sys::STDOUT) {
        // Interactive: hand the document to the pager. A missing controlling
        // terminal is not fatal — fall through to the dump path.
        match interactive(args, &input, src) {
            Ok(()) => return Ok(()),
            Err(PagerExit::NoTty(src)) => return dump_source(args, src),
            Err(PagerExit::Fatal(f)) => return Err(f),
        }
    }
    dump_source(args, src)
}

/// Width the non-interactive path lays out at.
fn dump_width(args: &cli::Args) -> usize {
    let cols = sys::winsize_of(sys::STDOUT).or_else(sys::winsize).map(|(c, _)| c as usize);
    dump::layout_width(args.width, cols)
}

/// Non-interactive rendering: one full-fidelity pass to stdout.
fn dump_source(args: &cli::Args, mut src: Box<dyn Source>) -> Result<(), Fail> {
    let plain = plain_mode(
        args.plain,
        env::var("NO_COLOR").ok(),
        sys::is_tty(sys::STDOUT),
    );
    // A terminal has a viewport, so overflowing rows are clipped the way the
    // pager clips them; a file or pipe keeps the full row.
    let clip = sys::is_tty(sys::STDOUT);
    // Streamed, not accumulated: a window of rows is painted and written before
    // the next is laid out, so `tread huge.csv | head` prints at once and a
    // file too big to hold never becomes a String (SPEC.md §CSV).
    let stdout = std::io::stdout();
    let mut sink = Sink(std::io::BufWriter::new(stdout.lock()));
    let _ = dump::write_source(src.as_mut(), dump_width(args), plain, clip, &mut sink);
    let _ = sink.0.flush();
    Ok(())
}

/// A [`std::fmt::Write`] over an [`std::io::Write`], which is what lets the
/// dump path write into stdout and into a test's `String` through one call.
/// A failed write — the closed pipe `| head` leaves behind — comes back as an
/// error so the walk stops rather than laying out the rest of the file for
/// nobody; like [`emit`], it is not a failure of the run.
struct Sink<W: Write>(W);

impl<W: Write> std::fmt::Write for Sink<W> {
    fn write_str(&mut self, s: &str) -> std::fmt::Result {
        self.0.write_all(s.as_bytes()).map_err(|_| std::fmt::Error)
    }
}

/// Why the interactive path did not run to completion. `NoTty` hands the
/// document back so the caller can fall back to dumping it.
enum PagerExit {
    NoTty(Box<dyn Source>),
    Fatal(Fail),
}

/// Is this terminal error "there is nothing interactive here", i.e. should the
/// reader quietly dump the document instead of failing?
///
/// Both variants mean that: `NoTty` is no console at all, and `RawMode` is a
/// console that will not enter raw mode — on unix a `tcsetattr` refusal, on
/// Windows a pre-1703 conhost that cannot do
/// `ENABLE_VIRTUAL_TERMINAL_PROCESSING`, which the backend reports by returning
/// `None` from `set_raw` after undoing everything it changed. Painting ANSI at a
/// console that would print it literally is worse than not painting, and
/// `sys/mod.rs` documents `set_raw`'s `None` as exactly this fallback.
fn is_non_interactive(e: &term::TermError) -> bool {
    matches!(e, term::TermError::NoTty | term::TermError::RawMode)
}

/// Enter raw mode and run the event loop until the pager asks to quit.
fn interactive(
    args: &cli::Args,
    input: &Input,
    src: Box<dyn Source>,
) -> Result<(), PagerExit> {
    // One NO_COLOR rule for both paths: `Term` reads no environment itself.
    let opts = term::TermOptions {
        alt_screen: !args.no_alt,
        plain: plain_mode(args.plain, env::var("NO_COLOR").ok(), true),
    };
    let mut term = match term::Term::new(opts) {
        Ok(t) => t,
        Err(ref e) if is_non_interactive(e) => return Err(PagerExit::NoTty(src)),
        Err(e) => return Err(PagerExit::Fatal(Fail::runtime(format!("terminal: {e:?}")))),
    };
    let (cols, rows) = term.size();
    let label = status_label(input);
    // The pager is handed a `Box<dyn Source>` and never learns the format
    // (SPEC.md §The `Source` seam); picking one was `build_source`'s job.
    let mut pager = pager::Pager::new(src, label, cols as usize, rows as usize, args.width);
    // `--no-browser` restores refuse-and-show (SPEC.md §"Opening a link outside
    // the reader"). The pager holds the policy; the spawn happens below.
    pager.set_browser(!args.no_browser);
    // Anything that produces links gets a corpus: relative links, history and
    // the index all hang off it. That is markdown, a code file (its imports)
    // and a directory listing (its entries) — see `open::navigable`.
    if let Some(path) = input.path.as_ref().filter(|_| open::navigable(input)) {
        let cwd = env::current_dir().unwrap_or_else(|_| PathBuf::from("."));
        // Markdown finds its own corpus from a README that links to the
        // document. Code and directory listings have no such index, so their
        // corpus is the project they sit in — without it the root is whatever
        // folder the file is in, and every import of a sibling directory is
        // refused for escaping it (`open::corpus_root`).
        let index = match (&args.index, input.format) {
            (Some(i), _) => Some(i.clone()),
            (None, source::detect::Format::Markdown) => None,
            (None, _) => open::corpus_root(path, &cwd),
        };
        pager.attach_nav(nav::Navigator::new(path, index.as_deref(), &cwd));
    }
    let result = event_loop(&mut term, &mut pager);
    // Runs on the error path too: `result` is only unwrapped afterwards.
    term.restore();
    result.map_err(PagerExit::Fatal)
}

/// One buffered frame per iteration; blocks in `read` between frames.
fn event_loop(term: &mut term::Term, pager: &mut pager::Pager) -> Result<(), Fail> {
    let mut decoder = key::Decoder::new();
    let mut buf = [0u8; 4096];
    loop {
        if pager.take_dirty() {
            let mut frame = term.frame();
            pager.paint(&mut frame);
            term.flush(&frame)
                .map_err(|e| Fail::runtime(format!("write: {e:?}")))?;
        }
        match term.read(&mut buf) {
            sys::ReadOutcome::Bytes(n) => {
                for ev in decoder.feed(&buf[..n]) {
                    pager.handle(ev);
                }
            }
            // The idle tick is also when a lazily indexed format gets its
            // bounded slice of scanning (SPEC.md §CSV).
            sys::ReadOutcome::Timeout => pager.idle(),
            sys::ReadOutcome::Eof => return Ok(()),
            sys::ReadOutcome::Error(e) => return Err(Fail::runtime(format!("read: errno {e}"))),
        }
        if let Some(y) = pager.take_yank() {
            let msg = deliver_yank(term, &y);
            pager.notify(msg);
        }
        // `Enter` on an external link the allowlist accepted. The pager decided;
        // this only starts the process, and never waits on it.
        if let Some(url) = pager.take_open() {
            pager.notify(open_external(&url));
        }
        // SIGWINCH is polled, never handled inline: the handler only sets a flag.
        if term.resize_pending() {
            let (c, r) = term.refresh_size();
            pager.resize(c as usize, r as usize);
        }
        pager.tick();
        // SIGTERM/SIGHUP/SIGQUIT are caught (sys::install_signal_handlers) so
        // that they land here and the caller's `term.restore()` still runs,
        // instead of the default disposition killing us in raw mode.
        if pager.should_quit() || term.interrupt_pending() || term.terminate_pending() {
            return Ok(());
        }
    }
}

/// Hand an accepted URL to this platform's opener and describe the outcome for
/// the status bar (SPEC.md §"Opening a link outside the reader").
///
/// Which program runs is [`sys::browser`]'s business and is not knowable from
/// here; a missing opener is a message, never an error exit.
///
/// The pager already checked the allowlist before queueing the URL, so the
/// refusal arm is unreachable in practice. It is still *written*, because
/// `sys::browser::open` takes a [`sys::browser::Vetted`] and the only way to get
/// one is to ask the allowlist again — which is the point: the check is not
/// something this function could forget.
fn open_external(url: &str) -> String {
    match nav::external::vetted(url) {
        Ok(v) => match sys::browser::open(v) {
            Ok(program) => format!("opening in {program}: {url}"),
            Err(e) => e.message(),
        },
        Err(why) => why.message(url),
    }
}

/// Put a yank on the system clipboard and on disk, and describe the outcome
/// for the status bar.
///
/// OSC 52 is wrapped for whichever multiplexer is in the way, and the full text
/// always goes to this platform's cache file as well (`~/.cache` on Linux,
/// `~/Library/Caches` on macOS, `%LOCALAPPDATA%` on Windows — see
/// `plat::dirs`), so a terminal that refuses the escape never loses the copy
/// silently (SPEC.md §Keybindings).
fn deliver_yank(term: &mut term::Term, yank: &select::Yank) -> String {
    let saved = select::clip::write_fallback(&yank.text);
    // `$HOME` does not exist on Windows; `plat::dirs` knows what does.
    let home = plat::dirs::home(plat::Platform::HOST, &plat::dirs::Env::from_process())
        .map(PathBuf::from);
    let shown = saved
        .as_ref()
        .map(|p| select::clip::display_path(p, home.as_deref()));
    let (frame, report) = clipboard_frame(term.frame(), &yank.text, select::clip::mux_from_env());
    let report = match term.flush(&frame) {
        Ok(()) => Some(report),
        Err(_) => None,
    };
    select::clip::yank_message(&yank.what, report, shown.as_deref())
}

/// Put the OSC 52 sequence for `text` into `frame`.
///
/// The sequence is not part of the next frame's layout, so it goes out on its
/// own single write — but still through the frame buffer, never `print!`
/// (SPEC.md §7). Split out of [`deliver_yank`] so the delivery path can be
/// tested without a terminal. `raw` is used rather than `span` because the
/// bytes are a control sequence, not styled text: plain mode must not strip it.
fn clipboard_frame(
    mut frame: term::Frame,
    text: &str,
    mux: select::clip::Mux,
) -> (term::Frame, term::ClipReport) {
    let (seq, report) = select::clip::clipboard_sequence(text, mux);
    frame.raw(&seq);
    (frame, report)
}

/// Status-bar label: the file name as given, or `<stdin>`.
fn status_label(input: &Input) -> String {
    Path::new(&input.label)
        .file_name()
        .map(|n| n.to_string_lossy().into_owned())
        .unwrap_or_else(|| input.label.clone())
}

/// Colour is off when asked for, when `NO_COLOR` is set non-empty, or when
/// stdout is not a terminal.
///
/// This is the *only* NO_COLOR rule in the crate — `Term` reads no environment
/// of its own — so `tread doc.md` and `tread doc.md | cat` can never disagree. An
/// empty `NO_COLOR=` does not count, per the no-color.org spec.
fn plain_mode(flag: bool, no_color: Option<String>, stdout_tty: bool) -> bool {
    flag || no_color.map(|v| !v.is_empty()).unwrap_or(false) || !stdout_tty
}

/// All non-TUI stdout goes through here; a closed pipe is not an error.
fn emit(s: &str) -> i32 {
    let stdout = std::io::stdout();
    let _ = stdout.lock().write_all(s.as_bytes());
    let _ = std::io::stdout().flush();
    EXIT_OK
}

fn fatal(msg: &str) {
    // Permitted by SPEC §7: startup/teardown errors, never UI.
    eprintln!("{}: {}", cli::BIN, msg);
}

/// Restore the terminal before the default hook prints the panic message,
/// otherwise the message lands on the alternate screen in raw mode.
fn install_panic_hook() {
    let previous = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        term::emergency_restore();
        previous(info);
    }));
}

#[cfg(test)]
#[path = "main_tests.rs"]
mod tests;