colored

repository·master·Indexed 24 days ago

https://github.com/colored-rs/colored

A simple, safe Rust library for terminal text coloring and styling. It provides the Colorize trait for applying standard, bright, and background colors, as well as truecolor (RGB) values and text styles like bold and underline to strings. The library supports automatic color detection via environment variables (CLICOLOR_FORCE, NO_COLOR, CLICOLOR), manual overrides, and Windows virtual terminal processing.

Tokens
2.9K
Snippets
7
Records
20
Agent score
84%

What's inside colored

  1. Respect environment color standards

    master

    The library automatically respects standard terminal color environment variables:

    • CLICOLOR_FORCE: Overrules everything.
    • NO_COLOR: Overrules CLICOLOR.
    • CLICOLOR: Standard color support.

    It works on Linux, MacOS, and Windows (Powershell).

  2. Install and set up colored

    master

    To use colored in your Rust project, add it to your Cargo.toml dependencies and import the Colorize trait to access coloring methods on strings and other types.

    Cargo.toml

    [dependencies]
    colored = "3"

    main.rs / lib.rs

    use colored::Colorize;
    
    fn main() {
        println!("{}", "it works!".green());
    }
  3. Control colorization behavior

    master

    Compile-time disabling

    To disable all coloring at compile time (e.g., for tests), enable the no-color feature in your Cargo.toml.

    [features]
    dumb_terminal = ["colored/no-color"]

    Runtime overriding

    For finer runtime control, use the colored::control::set_override method.

  4. How color detection priority works

    master

    The colored crate determines whether to apply colors based on a specific hierarchy of settings. Understanding this hierarchy helps you debug why colors might not be appearing in certain environments.

    1. Manual Override: If set_override(bool) was called, this value takes absolute precedence.
    2. CLICOLOR_FORCE: If this environment variable is set to a non-zero value, it forces colorization (or lack thereof) regardless of other settings.
    3. NO_COLOR: If this environment variable is present, colorization is disabled.
    4. CLICOLOR & TTY Check: If CLICOLOR is set (and not 0), colorization is enabled, provided the output is a terminal (TTY).
  5. Use the Colorize trait to color strings

    master

    The Colorize trait is the primary way to use colored. By importing colored::Colorize, you can call various color and style methods directly on &str and String types. These methods return a ColoredString which can then be printed to the terminal.

    Commonly used methods include:

    • Foreground Colors: .red(), .blue(), .green(), .yellow(), .cyan(), .magenta(), .white(), etc.
    • Bright Colors: .bright_red(), .bright_blue(), etc.
    • Background Colors: .on_red(), .on_blue(), etc.
    • Styles: .bold(), .dimmed(), .italic(), .underline(), .blink(), .reversed(), .hidden(), .strikethrough().
    • Truecolor: .truecolor(r, g, b) and .on_truecolor(r, g, b) for RGB values.
    • Resetting: .clear() or .normal() to remove styling.
    use colored::Colorize;
    
    "this is blue".blue();
    "this is red".red();
    "this is red on blue".red().on_blue();
    "this is also red on blue".on_blue().red();
    "you can use truecolor values too!".truecolor(0, 255, 136);
    "background truecolor also works :)".on_truecolor(135, 28, 167);
    "you can make bold text".bold();
    
    println!("{} {}", "or use".cyan(), "any".italic().yellow());
  6. Apply basic colors and styles to text

    master

    The Colorize trait provides methods to apply colors and styles directly to strings.

    Standard Colors: black(), red(), green(), yellow(), blue(), magenta() (or purple()), cyan(), white().

    Bright Colors: Prepend bright_ to any color name (e.g., bright_blue()).

    Background Colors: Prepend on_ to any color name (e.g., on_blue()). For bright backgrounds, use on_bright_ (e.g., on_bright_red()).

    Text Styles: bold(), underline(), italic(), dimmed(), reversed(), blink(), hidden(), strikethrough().

    Resetting Styles: Use normal() or clear() to remove color and styling.

    "this is blue".blue();
    "this is red".red();
    "this is red on blue".red().on_blue();
    "bright colors are welcome as well".on_bright_blue().bright_red();
    "you can also make bold text".bold();
    "or clear things up. This is default color and style".red().bold().clear();
  7. Apply colors dynamically from strings or hex

    master

    You can apply colors using string names or hex codes via the .color() and .on_color() methods. The Color type implements FromStr, allowing for safe parsing.

    Usage Examples:

    • String names: .color("blue")
    • Hex codes: .color("#0057B7")
    • Safe parsing: Use .parse::<Color>() to handle invalid color strings gracefully.
  8. Use Truecolors (RGB) for arbitrary colors

    master

    For modern terminals, you can specify exact RGB values using truecolor for foreground and on_truecolor for background. You can also pass colors as tuples.

    Note: This requires a terminal that supports true color (check the $COLORTERM environment variable for truecolor or 24bit).

    "you can use truecolor values too!".truecolor(0, 255, 136);
    "background truecolor also works :)".on_truecolor(135, 28, 167);
    "truecolor from tuple".custom_color((0, 255, 136));
    "background truecolor from tuple".on_custom_color((0, 255, 136));
  9. Parse colors from strings or hex codes

    master

    The Color type implements FromStr, allowing you to parse color names or hex codes from strings. It is case-insensitive.

    Supported formats:

    • Color Names: "black", "red", "bright blue", "purple" (maps to Magenta), etc.
    • Hex Codes: "#RGB" (3-digit) or "#RRGGBB" (6-digit).

    If parsing fails, FromStr returns an error, but the From<&str> and From<String> implementations will default to Color::White instead of erroring.

  10. Enable virtual terminal processing on Windows

    master

    On Windows 10 environments, ANSI escape codes might not be correctly interpreted by the console. You can use set_virtual_terminal to enable virtual terminal processing, which allows the console to correctly colorize output using ANSI escape codes.

    Note: This function is only available on Windows build targets.

  11. Clear colors and styles from a ColoredString

    master

    If you have a ColoredString and want to remove specific parts of its styling, use the following methods:

    • clear_fgcolor(): Removes the foreground color (sets fgcolor to None).
    • clear_bgcolor(): Removes the background color (sets bgcolor to None).
    • clear_style(): Resets all text decorations (bold, italic, etc.) to the default Style.
  12. Create custom RGB colors with CustomColor

    master

    The CustomColor struct allows you to define specific colors using RGB (Red, Green, Blue) values. This is useful for generating true color output in terminals that support it. You can instantiate a color using CustomColor::new(r, g, b) or by converting a tuple of (u8, u8, u8) using CustomColor::from().

    Note: CustomColor is intended to be used with the library's coloring traits to apply these specific colors to strings.