crossterm-rs / crossterm

Cross platform terminal library rust
MIT License
3.29k stars 280 forks source link

API to disable ANSI escape code emission #924

Open rtbo opened 3 months ago

rtbo commented 3 months ago

New API to disable ANSI escape code emission on redirected outputs. see #921

Example of code provided by this feature:

fn print_diagnostic() {
    let _guard = style::disable_ansi(!io::stderr().is_terminal());

    // styling stderr output is now only active if stderr is not redirected
    eprintln!("{}: {}", "error".red().bold(), "something went wrong".bold());
}

A nice thing is that the code that prints doesn't need to be aware of the feature and can use the fmt API and be in a different crate.

fn write_diagnostic<W: io::Write>(out: &mut W, err: &Error) -> io::Result<()> {
    writeln!(out, "{}: {}", "error".red().bold(), err.to_string().bold());
}

fn print_diagnostic(err: &Error, force_color: bool) -> io::Result<()> {
    let stderr = io::stderr().lock();
    let _guard = style::disable_ansi(!force_color && !stderr.is_terminal());

    let mut out = BufWriter::new(stderr);
    write_diagnostic(&mut out, err)?;
    out.flush()
}

New API is behind a cargo feature because there is a runtime check for each escape code emitted. Not everyone wants to pay this cost.

Without this PR, managing redirected output is tedious and generally requires to double the print code. (with and without style)