rust-cli / anstyle

ANSI text styling
https://docs.rs/anstyle
Other
106 stars 16 forks source link

RFC: Style code/reset rendering via Display #165

Closed joshtriplett closed 7 months ago

joshtriplett commented 7 months ago

This is an unusual suggestion, but I've tried it out in practice and it feels really comfortable to use. I wanted to run it by you to see if it seemed reasonable.

I found the requirement to call .render() and .render_reset() rather verbose, particularly when trying to render several color styles in one line. I started thinking about ways to make that more convenient, and this idea occurred to me.

With this PR applied, Style and Reset implement Display directly, rendering the ANSI code, without having to call .render(). That part I'm hoping will be relatively uncontroversial; that's in the first two commits.

The more unusual part of this PR: if you set the alternate format flag, a Style will print its reset code, instead.

The combination of the two makes it easy to use inline formats to render styles. Here's an example of how this looks:

use anstyle::{AnsiColor, Style};

fn main() {
    const RB: Style = AnsiColor::Red.on_default().bold();
    const GU: Style = AnsiColor::Green.on_default().underline();
    println!("{RB}Hello{RB:#}, {GU}world{GU:#}!");
}

I'm hoping this seems reasonable. If you find the use of the alternate flag too much, though, then as an alternative, you could drop the last two commits, and that would still let people render codes and resets using inline styles:

use anstyle::{AnsiColor, Reset, Style};

fn main() {
    const RESET: Reset = Reset;
    const RB: Style = AnsiColor::Red.on_default().bold();
    const GU: Style = AnsiColor::Green.on_default().underline();
    println!("{RB}Hello{RESET}, {GU}world{RESET}!");
}

(This would get even easier if anstyle had a pub const RESET: Reset = Reset;, which I'd be happy to send in a patch for.)

epage commented 7 months ago

Moving the conversation over at #166.

joshtriplett commented 7 months ago

Thanks for the merge! I'm using the new API now, and it works well.