(Rust) Coloring terminal so simple you already know how to do it !

Overview

Colored

Build Status Crates.io Crates.io

Coloring terminal so simple, you already know how to do it!

    "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);
    "bright colors are welcome as well".on_bright_blue().bright_red();
    "you can also make bold comments".bold();
    println!("{} {} {}", "or use".cyan(), "any".italic().yellow(), "string type".cyan());
    "or change advice. This is red".yellow().blue().red();
    "or clear things up. This is default color and style".red().bold().clear();
    "purple and magenta are the same".purple().magenta();
    "and so are normal and clear".normal().clear();
    "you can specify color by string".color("blue").on_color("red");
    String::from("this also works!").green().bold();
    format!("{:30}", "format works as expected. This will be padded".blue());
    format!("{:.3}", "and this will be green but truncated to 3 chars".green());

How to use

Add this in your Cargo.toml:

[dependencies]
colored = "2"

and add this to your lib.rs or main.rs:

    extern crate colored; // not needed in Rust 2018

    use colored::*;

    // test the example with `cargo run --example most_simple`
    fn main() {
        // TADAA!
        println!("{} {} !", "it".green(), "works".blue().bold());
    }

Features

  • Safe rust, easy to use, minimal dependencies, complete test suite
  • Respect the CLICOLOR/CLICOLOR_FORCE behavior (see the specs)
  • Respect the NO_COLOR behavior (see the specs)
  • Works on Linux, MacOS, and Windows (Powershell)

Colors:

  • black
  • red
  • green
  • yellow
  • blue
  • magenta (or purple)
  • cyan
  • white

Bright colors: prepend the color by bright_. So easy. Background colors: prepend the color by on_. Simple as that. Bright Background colors: prepend the color by on_bright_. Not hard at all.

Truecolors

Colored has support for truecolors where you can specify any arbitrary rgb value.

This feature will only work correctly in terminals which support true colors (i.e. most modern terminals).

You can check if your terminal supports true color by checking the value of the environment variable $COLORTERM on your terminal. A value of truecolor or 24bit indicates that it will work.

Styles:

  • bold
  • underline
  • italic
  • dimmed
  • reversed
  • blink
  • hidden
  • strikethrough

You can clear color and style anytime by using normal() or clear()

Advanced Control:

Dynamic color from str

As Color implements FromStr, From<&str>, and From<String>, you can easily cast a string into a color like that:

// the easy way
"blue string yo".color("blue");

// this will default to white
"white string".color("zorglub");

// the safer way via a Result
let color_res : Result<Color, ()> = "zorglub".parse();
"red string".color(color_res.unwrap_or(Color::Red));
Colorization control

If you want to disable any coloring at compile time, you can simply do so by using the no-color feature.

For example, you can do this in your Cargo.toml to disable color in tests:

[features]
# this effectively enable the feature `no-color` of colored when testing with
# `cargo test --feature dumb_terminal`
dumb_terminal = ["colored/no-color"]

You can use have even finer control by using the colored::control::set_override method.

Build with Docker

Install Docker

Use the install instructions located here

Build the Docker image

docker build -t colored_image .

Build the library

docker run --rm -it -v "$PWD":/src -u `id -u`:`id -g` colored_image /bin/bash -c "cargo build"

Test the library

docker run --rm -it -v "$PWD":/src -u `id -u`:`id -g` colored_image /bin/bash -c "cargo test"

Todo

  • More tests ?: We always welcome more tests! Please contribute!

Credits

This library wouldn't have been the same without the marvelous ruby gem colored.

Thanks for the ansi_term crate for providing a reference implementation, which greatly helped making this crate output correct strings.

License

Mozilla Public License 2.0. See the LICENSE file at the root of the repository.

In non legal terms it means that:

  • if you fix a bug, you MUST give me the code of the fix (it's only fair)
  • if you change/extend the API, you MUST give me the code you changed in the files under MPL2.
  • you CAN'T sue me for anything about this code
  • apart from that, you can do almost whatever you want. See the LICENSE file for details.

Contributors

Comments
  • Ignore coloring cues on windows

    Ignore coloring cues on windows

    Currently colored doesn't have true windows support. In the mean time to allow some cross platform usability without risking dumping ANSI codes to the terminal the colored string can ignore coloring on the windows platform.

    opened by robojeb 8
  • Fix various warnings and issues

    Fix various warnings and issues

    I've listed the details of each fix into its own commit message

    Warnings were found by running

    cargo clippy

    and

    cargo test

    rust version 1.43.0

    @kurtlawrence

    opened by MichaelAquilina 7
  • Windows 10+ supports ANSI codes

    Windows 10+ supports ANSI codes

    Currently, it is stated everywhere that Windows support will be added in the future. I know how this is meant, you want to support older Windows consoles that do not have support for ANSI codes. However, it should be mentioned that recent Windows versions have full support for the coloring implementation of this crate, just to ensure that people are not running away frightened because they think that there is absolutely no coloring support on Windows.

    https://blogs.msdn.microsoft.com/commandline/2016/09/22/24-bit-color-in-the-windows-console/

    opened by Fleshgrinder 7
  • Colour output does not work in IntelliJ integrated run window

    Colour output does not work in IntelliJ integrated run window

    Not sure if this is something getting incorrectly detected in this library, or a bug with the IDE, but colours set by this library don't display inside the IDE's integrated run output. This is possibly because it's internally redirected?

    Repro:

    use colored::*
    
    fn main() {
      println!("{}", "hello world".blue())
    }
    

    In the IDE: image

    In Kitty: image

    opened by JakeStanger 5
  • Doesn't work on windows when binary is installed with cargo install

    Doesn't work on windows when binary is installed with cargo install

    Using v1.9.3.

    I'm not sure how to debug this. I'm on Windows 10 using the command prompt. When I build my app from source, colored works as expected. But if I cargo install my program from crates.io (from the same source), I get output like this:

     Hello
    

    term_painter works as expected from either source or cargo install. Running from cargo install for Linux and Mac work fine. Any ideas why this would be happening?

    opened by cmontella 5
  • Combining color and style ends up not showing prints correctly

    Combining color and style ends up not showing prints correctly

    As it can be seen here, when combining styling and color in the same print, both color and style are reset when one of them stop, instead of returning to the color.

    opened by Razican 5
  • Programatically force/disable the colors

    Programatically force/disable the colors

    It would be great to have a static API which would enable/disable coloring. It would help for a finer control.

    Example 1:

    fn log_something(msg: String) {
        colored::force_colors(Some(ApplyColors::Never));  // never color
        log_with_colors_in_file(msg);                     // no colors applied
        colored::force_colors(Some(ApplyColors::Always)); // always color when asked
        log_with_colors_in_stdout(msg);                   // colors applied
        colored::force_colors(None);
        // back to default behavior
    }
    

    It could be with a color token (Example 2):

    fn log_something(msg: String) {
        let token = colored::force_colors_scoped(Some(ApplyColors::Never));  // never color
        log_with_colors_in_file(msg);                     // no colors applied
        // first token goes out of scope, restoring default behavior
        // second token is emited
        let token = colored::force_colors_scoped(Some(ApplyColors::Always)); // always color when asked
        log_with_colors_in_stdout(msg);                   // colors applied
        // back to default behavior because second token goes out of scope
    }
    
    opened by mackwic 5
  • Support global toggle via env variable

    Support global toggle via env variable

    Via popular demand, the user should be able to force turning ON or OFF colored via an environment variable.

    I consider using RUST_NOCOLOR and RUST_FORCECOLOR, but I would like to have the opinion of other implementers on the matter and see if we can coordinate a little.

    This is the tracking issue.

    opened by mackwic 5
  • Is there any way to clean a string which wasn't initially stored as colored

    Is there any way to clean a string which wasn't initially stored as colored

    I hope this example will make clear what I mean. Currently this test fails but is there any way to make it work?

            use colored::Colorize;
            let a = "something";
            let b = a.red().to_string();
            let c = a.clear().to_string();
            assert_eq!(a, c);
    
    opened by zhiburt 4
  • Question: How are the color methods attached to every string?

    Question: How are the color methods attached to every string?

    I used your crate in a project recently, and wanted to know how it worked.

    Specifically, I wanted to understand how, by just adding

    use colored::*

    all of my strings suddenly got these color methods attached to them. Curious what the mechanism is that does this magic ✨

    opened by maxuuell 4
  • Convert between bright and non-bright colours

    Convert between bright and non-bright colours

    I would like it if there was a way to convert, say Color::Red to Color::BrightRed and back again with a method, maybe by splitting out the bright colours from Color into BrightColor. To convert, methods such as .bright() on Color and .normal() on BrightColor could be added.

    opened by arzg 4
  • no colors on stderr when redirecting stdout

    no colors on stderr when redirecting stdout

    If I want color output on stderr or stdout, I get colors. If I have colored stdout and redirect stderr to /dev/null, I still get color on stdout. If I have colored stderr and redirect stdout to /dev/null, I no longer get color on stderr. Is this expected behavior?

    I ran into this issue when using simple_logger 4.0.0, but the problem appears to lie with colored (see here: https://docs.rs/colored/latest/src/colored/control.rs.html#108). The version of colored used was 2.0.0 and this was seen on macOS. Here is the original ticket I made in simple_logger: https://github.com/borntyping/rust-simple_logger/issues/71

    opened by andbleo 0
  • A simple question

    A simple question

    Im trying to build a little app for fun with https://chat.openai.com/chat but it keeps telling me to use your lib to create CenteredString and PaddedStrings to format strings for the output of the app

    the ia said:

     apologize for the confusion. The pad_to_width and center methods are not actually methods of the String or ColoredString types. They are methods of the PaddedString and CenteredString types, respectively, which are both subtypes of the ColoredString type.
    
    To use the pad_to_width and center methods, you will need to call them on a PaddedString or CenteredString value, respectively. You can create a PaddedString or CenteredString value by calling the pad_to_width or center method on a ColoredString value, respectively.
    
    Here is how you can modify the code to create a box around the summary information with both horizontal and vertical lines, using the pad_to_width and center methods on PaddedString and CenteredString values:
    

    and

    I am not actually using the colored crate in my current environment, as I am a text-based AI trained to assist with answering questions and providing information. I do not have the ability to run code or use external libraries.
    
    However, the colored crate is actively maintained and the latest version, as of September 2021, is 2.0.3. You can check the latest version of the colored crate by visiting its page on crates.io:
    
    https://crates.io/crates/colored
    
    

    There never was a 2.0.3 version of Colored right ?

    opened by Bowarc 1
  • Feature: Support parsing `TrueColor` from RGB string

    Feature: Support parsing `TrueColor` from RGB string

    Problem

    Currently the from_str function supports parsing color names to Color enum based on the names. But this function does not parse TrueColor.

    https://github.com/mackwic/colored/blob/11ffd20e7b5d1b48e4de7bb78ced26131ae5e114/src/color.rs#L88

    Expectation

    Given a string like rgb(<u8>,<u8>,<u8>), from_str should support parsing it to a Color::TrueColor instance.

    Suggestion

    In a project of mine, I've used a regex check to determine if the string matches the specific pattern and converts it to Color::TrueColor. A refined version of this could be added in the crate to be supported out-of-the-box.

    let true_color = Regex::new(r"(?x)^
        (?:bg:)?
        rgb\(
            (?P<red>\d{1,3}),\s?
            (?P<green>\d{1,3}),\s?
            (?P<blue>\d{1,3})
        \)
    $").unwrap();
    
    let mut color: Option<Color> = None;
    if let Some(caps) = true_color.captures(style) { // RGB colors
        let channels: Vec<u8> = vec!["red", "green", "blue"]
            .into_iter()
            .map(|x| caps[x].parse().expect("Must be int between 0 and 255."))
            .collect();
        color = Some(Color::TrueColor { r: channels[0], g: channels[1], b: channels[2] });
    }
    
    opened by dhruvkb 0
  • chore: replace atty with is-terminal

    chore: replace atty with is-terminal

    atty is unmaintained and has a potential unaligned read. See https://github.com/rustsec/advisory-db/blob/main/crates/atty/RUSTSEC-2021-0145.md.

    is-terminal is a replacement based on atty, with the soundness issue fixed and an (IMO) nicer to use API, mirroring what's available in the std lib on nightly with std::io::IsTerminal.

    opened by jcgruenhage 0
  • Added println_color macro

    Added println_color macro

    Added a macro to print colored output directly to the terminal.

    Examples

    println_color!(blue, bold, "This will be {} and {}!", "blue", "bold");
    
    // is equivalent to:
    
    println!("{}", format!("This will be {} and {}!", "blue", "bold").blue().bold());
    
    // inner colorization will be applied on top
    println_color!(magenta, "Most of this is magenta, but {} is red", "this".red());
    
    opened by e-rhodes 0
Releases(v1.9.0)
Owner
Thomas Wickham
Thomas Wickham
A CLI tool that allow you to create a temporary new rust project using cargo with already installed dependencies

cargo-temp A CLI tool that allow you to create a new rust project in a temporary directory with already installed dependencies. Install Requires Rust

Yohan Boogaert 61 Oct 31, 2022
Store your transfer.sh links, so you can remember them later and know when they will expire, but now written in Rust.

Transfer.sh helper Rusted The idea of the script is to store your transfer.sh links and simplify its usage, so you can remember them later and know wh

Reinaldo Rozato Junior 10 Nov 30, 2022
A bilibili downloader built by Tauri and the language you-know-who.

Bilibili Downloader A bilibili video downloader app built by Tauri, Vue and Rust! Explore the docs » View Demo · Report Bug · Request Feature Table of

王翼翔 35 Jun 19, 2023
zigfi is an open-source stocks, commodities and cryptocurrencies price monitoring CLI app, written fully in Rust, where you can organize assets you're watching easily into watchlists for easy access on your terminal.

zigfi zigfi is an open-source stocks, commodities and cryptocurrencies price monitoring CLI app, written fully in Rust, where you can organize assets

Aldrin Zigmund Cortez Velasco 18 Oct 24, 2022
A simple and efficient terminal UI implementation with ratatui.rs for getting quick insights from csv files right on the terminal

CSV-GREP csv-grep is an intuitive TUI application writting with ratatui.rs for reading, viewing and quickly analysing csv files right on the terminal.

Anthony Ezeabasili 16 Mar 10, 2024
A terminal ASCII media player. View images, gifs, videos, webcam, YouTube, etc.. directly in the terminal as ASCII art.

Terminal Media Player View images, videos (files or YouTube links), webcam, etc directly in the terminal as ASCII. All images you see below are just m

Max Curzi 36 May 8, 2023
ask.sh: AI terminal assistant that can read and write your terminal directly!

ask.sh: AI terminal assistant that read from & write to your terminal ask.sh is an AI terminal assistant based on OpenAI APIs such as GPT-3.5/4! What'

hmirin 5 Jun 20, 2023
Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Warp is a blazingly fast, Rust-based terminal that makes you and your team more productive at running, debugging, and deploying code and infrastructure.

Warp 10.4k Jan 4, 2023
Rust crate that allows you to display status & progress information in a terminal

status-line This crate allows you to display status & progress information in a terminal This crate handles the problem of displaying a small amount o

Piotr Kołaczkowski 20 Dec 27, 2022
A fun rust terminal program so you can make Christmas trees!

Xmastree 2021 A fun christmas tree where you can add ornaments! Then, you can export the file into either: a rust file a txt file About Taking a break

Junhao 2 Dec 21, 2021
a simple program that you can scrap, is shit and really simple but is cool.

if you want to run it you need to have installed curl by default scrap youtube, but you can change it, also change the number of threads and run: carg

pai 7 Oct 15, 2021
Display a random Shiba from your terminal whenever you feel the need to. Because why not?

Shiba CLI Command-line interface (CLI) to display a random Shiba Inu whenever needed, by just running shiba on your terminal. How To Use • How Does It

null 17 Sep 25, 2022
Terminal UI for leetcode. Lets you browse questions through different topics. View, solve, run and submit questions from TUI.

Leetcode TUI Use Leetcode in your terminal. Why this TUI: My motivation for creating leetcode-tui stemmed from my preference for tools that are lightw

Akarsh 8 Aug 10, 2023
fas stand for Find all stuff and it's a go app that simplify the find command and allow you to easily search everything you nedd

fas fas stands for Find all stuff and it's a rust app that simplify the find command and allow you to easily search everything you need. Note: current

M4jrT0m 1 Dec 24, 2021
Shellfirm - Intercept any risky patterns (default or defined by you) and prompt you a small challenge for double verification

shellfirm Opppppsss you did it again? ?? ?? ?? Protect yourself from yourself! rm -rf * git reset --hard before saving? kubectl delete ns which going

elad 652 Dec 29, 2022
Dura - You shouldn't ever lose your work if you're using Git

Dura Dura is a background process that watches your Git repositories and commits your uncommitted changes without impacting HEAD, the current branch,

Tim Kellogg 4.1k Jan 8, 2023
This automatically patches the RoPro extension for you, allowing you to have pro_tier for free.

RoPro Patcher This automatically patches the RoPro extension for you, allowing you to have pro_tier for free. NOTE Chrome, Brave (and possibly other b

Stefan 10 Jan 1, 2023
Sero is a web server that allows you to easily host your static sites without pain. The idea was inspired by surge.sh but gives you full control.

sero Lightning-fast, static web publishing with zero configuration and full control ?? Table Of Contents ?? Table Of Contents ?? Tools ❓ About The Pro

Dmitry Miasnenko 6 Nov 13, 2023
A dead simple ANSI terminal color painting library for Rust.

yansi A dead simple ANSI terminal color painting library for Rust. use yansi::Paint; print!("{} light, {} light!", Paint::green("Green"), Paint::red(

Sergio Benitez 169 Dec 25, 2022