Skip to content

anstream println field witdth is not aware of color codes #167

@VorpalBlade

Description

@VorpalBlade

I would expect the following (rather silly minimal case) to align columns properly:

use anstream::println;
use anstyle::AnsiColor;
use anstyle::Reset;

enum MyLogLevel {
    Ok,
    Warn,
    Error,
}

impl std::fmt::Display for MyLogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            MyLogLevel::Ok => write!(f, "{}Ok{}", AnsiColor::Green.render_fg(), Reset.render()),
            MyLogLevel::Warn => write!(
                f,
                "{}Warning{}",
                AnsiColor::Yellow.render_fg(),
                Reset.render()
            ),
            MyLogLevel::Error => write!(f, "{}Error{}", AnsiColor::Red.render_fg(), Reset.render()),
        }
    }
}

fn main() {
    println!("{:<10} Everything is fine", "Ok");
    println!("{:<10} Be careful", "Warning");
    println!("{:<10} BAD BAD BAD", "Error");

    println!("{:<10} Everything is fine", MyLogLevel::Ok);
    println!("{:<10} Be careful", MyLogLevel::Warn);
    println!("{:<10} BAD BAD BAD", MyLogLevel::Error);
}

It prints:

Ok         Everything is fine
Warning    Be careful
Error      BAD BAD BAD
Ok Everything is fine
Warning Be careful
Error BAD BAD BAD

This is unexpected. So it seems the anstream println is not properly aware of how wide colour codes are.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-streamArea: anstreamC-bugCategory: Things not working as expected

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions